From b9e06f435a9832d5d520e1626f33e1fd5848f0d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:03:35 +1300 Subject: [PATCH 1/6] Implement Account retained tenant-role source transactions and exact recovery --- .github/workflows/ci.yml | 34 + .../account-service/api-contracts.md | 14 + .../account-service/runtime-and-data.md | 18 +- .../system-architecture-authentication.md | 22 +- .../system-architecture-authz-route-matrix.md | 1 + .../consequential-decision-inventory.md | 3 + .../player-access-and-session.md | 8 +- .../AccountAuditOutboxRepository.java | 44 + .../repository/AccountRepository.java | 11 + .../AccountTenantRoleMutationDigest.java | 173 ++++ .../AccountTenantRoleOperationRepository.java | 665 +++++++++++++ ...countMembershipAuthorityEventProducer.java | 363 ++++++- .../AccountTenantRoleMutationService.java | 522 ++++++++++ .../V56__account_tenant_role_operations.sql | 236 +++++ .../AccountJoinPostgresIntegrationTest.java | 854 ++++++++++++++++- ...tionRepositoryPostgresIntegrationTest.java | 333 +++++++ .../AccountTenantRoleMutationDigestTest.java | 897 ++++++++++++++++++ ...ountTenantRoleOperationRepositoryTest.java | 123 +++ ...thorityEventProducerCanonicalJoinTest.java | 6 +- ...tMembershipAuthorityEventProducerTest.java | 40 +- 20 files changed, 4338 insertions(+), 29 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V56__account_tenant_role_operations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 532d018ba8..13210f5294 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2032,6 +2032,40 @@ jobs: fi echo "::endgroup::" + - name: Capture Account retained tenant-role PostgreSQL raw proof + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-retained-tenant-role-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountJoinPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountTenantRoleOperationRepositoryPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Account retained tenant-role PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + # These prove the unwired writer against stipulated retained owner state, not actor authentication. + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationDeniesNonAdminWithoutChangingAnyAccountSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRejectsStaleMembershipWithoutChangingAnyAccountSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRejectsMissingCurrentMembershipWithoutCreatingEvidence()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationCommitsGrantRevokeTransferAndReplaysOriginalGrantAfterLaterChange()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRollsBackAllSourcesWhenEventAppendFailsAfterWriting()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRollsBackAllSourcesWhenAuditAppendFailsAfterWriting()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRollsBackAllSourcesWhenFinalCurrentReadbackFails()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRejectsWrongTenantWithoutChangingAnyAccountSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#invalidatingTenantRoleMutationDeniesFenceOverflowWithoutChangingAnyAccountSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentOpposingTenantAdminTransfersLeaveOneCurrentAdministrator()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#immutableJournalRetriesOriginalBytesAfterLaterRoleOperationAndRejectsChangedIntent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepositoryPostgresIntegrationTest#operationJournalAndMemberEvidenceRollBackTogether()' \ + account-service + - name: Verify Account tenant-generation source PostgreSQL proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 1da976e417..fcf737e97a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -16,6 +16,18 @@ The initial `platformAdmin` is established only by a separate one-time protected Role mutation remains target-only: no route, RPC, published action-family schema, or current runtime writer is selected here. Before enablement, Account must own the source mutation, an independent positive role-source version, immutable event/audit evidence, and exact same-snapshot authorization readback. The role-source version is distinct from Account authority generations, issuance fences, event-stream checkpoints, and other source versions. Exact event fields, mutation identity/digest grammar, bootstrap artifact, retained-account enrollment, and retry/recovery protocol remain open owner-contract work under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). +### Account-Owned Tenant Role Administration + +Account is the sole authority for current tenant-role assignments. The accepted policy permits a current `tenantAdmin` to grant or revoke only `designer` for an explicitly identified canonical Account UUID in the same verified tenant. It does not authorize generic delegation or `tenantAdmin` management of `player`, `moderator`, or other tenant roles. The mutation actor and target are canonical Account identities, and `tenantId` is explicit; the UI's selected tenant and any global role, billing owner, payment instrument, or Game Design service identity is not authority for this operation. + +The verified initiator of an exact owner-issued tenant-creation operation receives the first `tenantAdmin` assignment through a distinct Account-owned membership bootstrap, not through public `JOIN`. Account may perform this bootstrap only after authenticated Game Design creation evidence binds the committed tenant identity and exact creation source to the initiator's canonical Account UUID and authorization, and a same-fence Account readback proves the exact pair has no membership row, no committed membership event, and no contradictory retained history. The bootstrap's first Account membership-stream event is sequence `1` and records an `ACTIVE` control-only membership with exactly the `tenantAdmin` role, no `player`, and `gameplayAdmissionAllowed=false`. Account advances `membershipVersion` once from the actual current positive pair baseline; it never synthesizes or resets retained state. If source readback finds prior positive event history, ambiguous creator provenance, or contradictory retained state, Account preserves that state and denies bootstrap rather than renumbering it. A later actual explicit public `JOIN` may add `player` and enable gameplay admission only from this exact current creator state and only after the ordinary fresh JOIN gates pass; it consumes the next stream sequence (`2` for this newly bootstrapped pair). The creation operation itself, `PLAY`, and selector state never imply that later JOIN. Account must not infer the initiator from an Account-to-tenant identity association, numeric key, selector, UI state, billing/payment ownership, or `platformAdmin` authority. Retained or otherwise unproven role rows are not backfilled or admitted by this policy. + +A tenant-admin transfer is one atomic Account mutation from an existing same-tenant `tenantAdmin` to an explicit Account target in that tenant. Its commit predicate must preserve at least one current `tenantAdmin`; separate revoke and grant operations cannot be composed into a transfer or leave the tenant without an administrator. + +For each committed role or creator-bootstrap change, Account revalidates the exact actor, target, tenant, operation kind, and expected current source state at the owner commit. The stable operation/request identity and mutation digest bind those values, including the exact source-bound creation operation for bootstrap. An atomic administrator transfer updates both affected memberships under their existing current source states and appends each matching membership event/checkpoint in the same owner transaction. Each affected membership advances its independent `membershipVersion` once from its actual current positive baseline and appends evidence under the existing [membership evidence contract](../../system-architecture-authentication.md#membership-event-continuity). The commit's authoritative role and authority readback binds the complete applicable `authorityTuple`, `issuanceFence`, membership version, event, and checkpoint to one Account snapshot. `membershipAuthorityGeneration` advances independently for each affected membership only when the committed change records `callerBoundAuthorityInvalidated=true`; a role grant does not imply a universal generation bump. + +An exact retry may return only the immutable result of the original operation after its identity, digest, expected source, and committed owner readback match. It does not reauthorize a new mutation or create reusable authority. Changed actor, target, tenant, operation kind, or expected source conflicts; stale or contradictory source state and unavailable or incomplete authorization/readback fail closed. Concrete route, request, and event details proceed under this approved authority boundary and must be specified and proved before mutation is enabled; this contract adds no public Account route or wire encoding. + ### Account-Owned Hosted Terms and Creator Party Account is the sole target authority for the identified hosted Creator Party, operator/legal-party and terms-version catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Acceptance is an explicit party-level decision for an identified operator and hosted-terms scope; tenant roles, billing ownership, payment, caller-supplied fields, or a copied Game Design flag do not establish party, signer, or acceptance authority. Organization and other unsupported party/signer paths remain disabled until their target contract is implemented and reviewed. @@ -64,6 +76,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Authenticated tenant-role mutation and creator bootstrap remain unavailable; no role-mutation route or RPC is enabled. The unwired existing-member storage candidate does not authenticate its actor or provide the complete Account authorization-evidence bundle. Its journal and digest consequences are owned by [Runtime & Data](./runtime-and-data.md#tenant-role-mutation-storage-candidate); source, implementation, and proof gaps are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + `ProfileDto.accountId` and the explicit profile-update Account selector carry the proved canonical Account UUID, never the private Account row key; REST body/path mismatch is rejected. Profile's own `id` and the current numeric tenant selector remain distinct. This correction does not complete tenant-qualified/delegated routes or Social Groups' numeric callers; current proof and activation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded JOIN worker is readback-only: only exact positive operation, scope, membership, role, transition receipt, authority event, and version-1 `COMMITTED` audit receipt/projection evidence can terminalize; absent, minimized, unsupported, or uncertain evidence remains pending, and expiry/attempt limits never resubmit or terminalize. See [Runtime & Data](./runtime-and-data.md#current-join-readback-behavior) for the owner-local details. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c89e281c6e..5c43c95e1a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,19 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -Global-role grant/revoke production and the protected first-administrator bootstrap are not implemented. V55 remains fresh-Account explicit-empty birth evidence only; there is no retained-row enrollment or versioned role writer. Account must not source current global roles or grant authority from the legacy scalar or token claims. The target owner contract and required source/readback boundary are defined in [Account API Contracts](./api-contracts.md#account-owned-global-role-administration) under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). +Global-role grant/revoke production and the protected first-administrator bootstrap are not implemented. V55 remains fresh-Account explicit-empty birth evidence only; there is no retained-row enrollment or versioned global-role writer. Account must not source current global roles or grant authority from the legacy scalar or token claims. The target owner contract and required source/readback boundary are defined in [Account API Contracts](./api-contracts.md#account-owned-global-role-administration) under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). + +### Tenant-role mutation storage candidate + +The in-progress `AccountTenantRoleMutationService`, `AccountTenantRoleOperationRepository`, and V56 draft form an unwired Account-local storage candidate for existing `APPROVED_RETAINED` memberships only. The candidate requires a same-snapshot current membership that is `ACTIVE`, gameplay-admitting, and sourced from `EXPLICIT_JOIN`, together with matching retained tenant provenance, role snapshot, pair authority, authority tuple, and issuance fence. It changes no missing, inactive, non-admitting, creator-bootstrap, unmapped, or ambiguous membership. It has no authenticated caller ingress or route/RPC, does not verify an authenticated actor at the commit boundary, does not implement creator bootstrap, and does not produce the complete Account authorization-evidence bundle; none of those capabilities is enabled. Mutation authority and policy remain owned by [Account API Contracts](./api-contracts.md#account-owned-tenant-role-administration). + +The draft's closed persisted actions are `GRANT_DESIGNER`, `REVOKE_DESIGNER`, and `TRANSFER_TENANT_ADMIN`. Within one Account write transaction it locks the distinct actor and target Account rows in canonical UUID order; claims the operation journal; reads the existing tenant association and current caller-bound source; checks the positive expected actor and target `membershipVersion` values; then updates the existing membership and role snapshot, advances each affected membership version once from its observed value, advances authority generation only according to that membership's recorded invalidation result, and appends the existing closed `account-auth-authority-event/v1` membership event and pair-authority checkpoint to the canonical per-account/tenant stream. It appends the Account tenant audit envelope and persists the immutable operation/member result in the same transaction. For a newly claimed operation, before returning it re-reads the committed request/result, audit envelope, event bytes, pair authority, role snapshot, and current membership source and requires exact equality; a stale source, incomplete readback, or any mismatch fails the transaction rather than leaving partial role, membership, event, audit, or journal state. Designer changes persist one member result; administrator transfer persists both affected member results in canonical Account UUID order. + +V56 adds an immutable-request, one-way-commit `account_tenant_role_operations` request/result journal and immutable `account_tenant_role_operation_members` event-evidence rows; it does not rewrite a published migration, backfill role state, reset membership versions or stream checkpoints, remap retained associations, or create a parallel membership event stream. The request payload is a v1 fixed-order byte frame. For each field, `frame(x) = UInt32BE(length(UTF8(x))) || UTF8(x)`. Concatenate frames for, in order: `firemud/account/tenant-role/request/v1`, the canonical non-nil UUIDs `requestId`, `actorAccountUuid`, `tenantUuid`, and `targetAccountUuid`, the exact action name above, positive `expectedActorMembershipVersion` as a base-10 decimal string, and positive `expectedTargetMembershipVersion` as a base-10 decimal string. `requestDigest` is `sha256:` plus lowercase hexadecimal SHA-256 of those exact bytes. Canonical UUID fields use lowercase hyphenated `UUID.toString()` form. + +The immutable result payload uses the same text frame and exact field order: `firemud/account/tenant-role/result/v1`, canonical `requestId`, exact `requestDigest`, canonical `tenantUuid`, `auditEventId`, `auditEventType`, the stored audit timestamp's `Instant.toString()` representation, and `auditPayloadDigest`, followed by `frameBytes(auditPayload)` and a UInt32BE member count. Here `frameBytes(b) = UInt32BE(length(b)) || b` preserves the exact bytes without re-encoding. Members are sorted by canonical `accountUuid`; each member encodes framed `accountUuid`, `tenantUuid`, positive decimal `membershipVersion`, positive decimal `membershipAuthorityGeneration`, positive decimal `eventSequence`, `eventRequestId`, `eventId`, and `eventDigest`, followed by one byte for `callerBoundAuthorityInvalidated` (`0` or `1`) and `frameBytes(eventPayload)` for the exact closed-V1 event bytes. `resultDigest` is `sha256:` plus lowercase hexadecimal SHA-256 of the complete result payload. The journal keeps the original request, audit, event, and result bytes immutable; a same-request exact retry verifies and returns that original committed evidence even after later role changes, while changed input conflicts and incomplete operations are not replayable. Such replay is historical result recovery only, not current authorization or reusable mutation authority. + +This unwired candidate does not establish an authenticated role writer, complete authorization-evidence producer, or runtime activation. Capability and executed versus unavailable proof remain in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Canonical UUID membership, scope, journal, receipt, audit and event components widen the existing Account-owned families without rewriting retained history or inventing numeric aliases. Their readback-only reconciliation is not a public JOIN producer or fresh caller authorization. Complete authenticated current-target/entitlement composition and positive JOIN proof remain required; runtime paths stay denied. The [canonical JOIN contract](./api-contracts.md#canonical-uuid-join-evidence) belongs to the API owner, and component capability, executed proof and remaining gaps belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). @@ -239,8 +251,8 @@ Membership freshness evidence contract: - Account reads the membership state, `membershipVersion`, the complete applicable `authorityTuple` (including the Account-owned membership authority generation), `evaluatedAt`, and the applicable committed `outboxCheckpoints` set from one authoritative snapshot/transaction or equivalent Account-owned fence. It returns those values together, or returns Account-authenticated evidence over exactly those values; callers must not assemble them from separate membership, generation, projection, or event reads. - The target membership response minimum therefore includes `accountId`, `tenantId`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`. Each checkpoint entry has exactly `{outboxStreamKey, outboxSequence}` and the set must contain the exact entry for `account:auth-authority:v1:membership//` that covers the returned membership and tuple snapshot. For every positive sequence, separate same-snapshot source evidence binds the event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). `membershipAuthorityGeneration` is the explicit membership member of that tuple; any separately carried value must authenticate the same value and is not an independent authority. -- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero has no event ID or digest in separate source evidence and cannot authorize admission. The first committed `JOIN` is sequence one, and a previously joined or left stream retains its positive sequence history even if no current membership row exists. -- Account persists one authority baseline for each verified account/tenant pair before returning a never-joined snapshot. That record carries positive generation and independent version while membership is absent; the same Account fence must bind it to the verified UUID association, no-row read, and no-committed-event/history proof. The first JOIN advances the version from this durable absence baseline and emits sequence one; it advances the generation only when the transition records caller-bound authority invalidation. Retained rows keep their provable version and stream history without a manufactured absence baseline. The current V36/JOIN candidate creates and consumes the pair baseline for a verified never-joined pair, but the runtime RPC remains denied until its authenticated response and Game Session consumer proof are complete. +- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero has no event ID or digest in separate source evidence and cannot authorize admission. A stream's first membership event is sequence one; when that event is the owner-proved tenant-creator bootstrap, a later explicit `JOIN` follows at the next sequence as defined by the [Account tenant-role owner contract](./api-contracts.md#account-owned-tenant-role-administration). A previously joined or left stream retains its positive sequence history even if no current membership row exists. +- Account persists one authority baseline for each verified account/tenant pair before returning a never-joined snapshot. That record carries positive generation and independent version while membership is absent; the same Account fence must bind it to the verified UUID association, no-row read, and no-committed-event/history proof. An ordinary first JOIN with no prior membership event advances the version from this durable absence baseline and emits sequence one; a later JOIN after creator bootstrap advances from its exact current baseline and positive checkpoint. Every transition advances the observed membership version once and advances the generation only when the committed transition records caller-bound authority invalidation. Retained rows keep their provable version and stream history without a manufactured absence baseline. The current V36/JOIN candidate creates and consumes the pair baseline for a verified never-joined pair, but the runtime RPC remains denied until its authenticated response and Game Session consumer proof are complete. - `evaluatedAt` is the UTC evaluation time of that complete authoritative snapshot and is not restamped when an older projection or cached row is read. A response is invalid when any required field or checkpoint is absent, when the checkpoint does not cover the tuple and membership version, or when the values cannot be proven to come from the same snapshot. Reachable contradictory, stale, regressed, or mismatched evidence is denied; an unavailable or timed-out Account evidence dependency remains retryable `AUTH_UNAVAILABLE`. A distinct authorization outcome may be defined only by the owning API contract for a different operation, not as an alternative code for this runtime membership dependency. Runtime caller contract: diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 31d88459ea..b6a5b177c9 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -54,6 +54,8 @@ For every private/playtest grant consequence, the exact Account target is `{acco ## Implementation Status +The accepted Account-owned tenant-role administration policy is target-only: Account has no tenant-role mutation, atomic administrator transfer, or commit-bound role-readback path. See the [Account owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration) and [implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status) for implementation status. + - **Current gameplay authentication and transport boundary:** Current gameplay authentication supports `LOGIN ` / `LOGON ` to request a verified-email login code and `LOGIN ` / `LOGON ` for an immediate password-or-code attempt on raw Telnet and other non-WebSocket text clients. Bare raw-text `LOGIN`/`LOGON` prompt exchange is target-only and currently returns `PROMPT_LOGIN_UNSUPPORTED`. Control-plane clients use `/auth/login`. First-party gameplay uses `POST /auth/player-bootstrap` to establish the `player-bootstrap` identity, then uses `/auth/bootstrap/*` discovery/action routes and `/auth/connect-token` before the gameplay socket. Clients are stateless; current Account-owned legacy authentication session records persist `tokenHash` and session metadata under the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key, while gameplay bindings remain in Redis. These records never persist the raw delegation JWT; their runtime/data ownership is defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#session-and-token-model). Target issued-token registry issuance, storage, and consumer enforcement in Coordination Redis are unimplemented. The Game Session Service restores gameplay session state from Redis, while the Account Service validates the supplied login secret and issues the exact `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT profile required by the destination. Raw Telnet gameplay command streams never carry JWT authorization. Target browser and mobile-browser gameplay uses a `player-bootstrap` JWT for HTTPS bootstrap calls and a cookie-carried one-use connect token for the `/ws/game/**` handshake; target first-party native-mobile clients that use a cookie jar remain cookie-only. Public non-browser issuance and the dedicated handshake-header carrier are target-only and unavailable until a dedicated route is fully registered and its issuance, registry, profile, and carrier proof is complete; the target design uses protected secure storage plus `X-Firemud-Connect-Token`. First-party admin/creator UIs and backend services use their own permitted token profiles. Provider-specific HTTPS sign-in remains unavailable until the provider-specific verification, collision, recovery, and end-to-end proof required by [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md) is complete. - **Current first-party endpoint and runtime boundary:** Dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces exist, but the complete first-party browser/mobile runtime remains fail-closed. Gateway rejects an otherwise valid connect token with `POLICY_DENY` before replay mutation or signed-context publication; Game Session's runtime connect-context parser is disabled, and Account rejects cached successful issuance rather than replaying its response. These surfaces do not prove live replay continuity, signed-context admission, or the complete Account exchange. Fresh `PLAY` remains contained by unavailable Account runtime authority and exact stable-namespace character proof before legacy gameplay binding. The retained downstream `{tenantId, gameInstanceId, characterId}` binding model is implementation drift, not proof of an available first-party path. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. See [Gateway API Contracts](./microservices/spring-cloud-gateway/api-contracts.md) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md). - **Bare first-party `LOGIN` candidate/test containment:** With an injected valid connect context, the candidate retains malformed-context and pointer-mismatch rejection, then returns retryable `AUTH_UNAVAILABLE` before command enqueue or authenticated Game Session state is saved. That conditional test path is not current end-to-end behavior: the runtime parser cannot supply the context. The unauthenticated bootstrap shell remains available for a later explicit retry. Gateway context or a connect-token `jti` alone does not authenticate Account; the Account-owned one-use exchange, committed issuance, private delegation, and recovery proof remain unimplemented. Credential-bearing `LOGIN` is unchanged. @@ -63,7 +65,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Target only/currently unavailable:** The independently enrolled TOTP-backed `privileged_control` elevation window for `platformAdmin` and cross-tenant `billingAdmin` is not implemented; current runtime must not claim those elevated paths are available. - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. -- **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. +- **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may add the durable caller-bound `player` membership or restore an `INACTIVE` one. The ordinary lifecycle is exact: missing -> `JOIN` creates `ACTIVE`; `INACTIVE` -> `JOIN` restores `ACTIVE`; an already admitting `ACTIVE` membership returns the exact idempotent current snapshot; every other lifecycle state rejects. The narrow owner-proved tenant-creator state is already `ACTIVE` with exactly the `tenantAdmin` role, no `player`, and `gameplayAdmissionAllowed=false`; an actual explicit `JOIN` from that exact current state may add `player` and enable admission only after the ordinary fresh public-join gates pass. Creator bootstrap is not `JOIN`, and neither `PLAY` nor tenant selection may convert it to an admitting membership. Each committed membership change advances the actual `membershipVersion` by exactly one; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`. `JOIN_REQUIRED` continues to describe missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing admitting `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. - **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping, does not validate the applicable private/playtest grant, and a cached-success replay may bypass fresh entitlement, membership, or pointer reads. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Public JOIN recovery status:** The Account JOIN worker reads exact locked, versioned COMMITTED audit/receipt evidence and cannot resubmit a bearer-bound request after its scope expires. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize it. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending. Terminal replay is bound to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Detailed local receiver and recovery status is tracked in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). @@ -86,8 +88,8 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. - **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; retained source evidence preserves each event's exact identity, digest, scope, and payload under its owning closed schema. When an event is used as recipient authority evidence, Account-authenticated readback separately binds its source checkpoint to the complete applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set from one Account snapshot. A duplicate at or below the watermark is accepted only when its source evidence matches exactly and, where recipient authority applies, the complete Account binding also matches. If retained source evidence is unavailable, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)`; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed, while reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. -- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is exactly `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. Separate same-snapshot source evidence binds event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint has no event ID or digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. -- **Never-joined pair baseline** – For each verified account/tenant pair, Account owns a durable pair-authority record with a positive membership generation and independent positive membership version even while membership is absent. A sequence-zero response requires one Account-fenced snapshot that proves this exact record, the verified pair identity, no current membership, and no committed membership event or retained contradictory history; absence of a row alone is never a generation, version, or checkpoint. The first explicit `JOIN` commits event sequence `1` and advances `membershipVersion` from that recorded absence baseline. It advances `membershipAuthorityGeneration` independently only if the transition records `callerBoundAuthorityInvalidated=true`. Existing retained membership versions and positive event sequences are preserved rather than assigned a synthetic absence baseline or renumbered. Unmapped or contradictory pairs remain denied, and sequence zero never authorizes admission. +- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is exactly `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. Separate same-snapshot source evidence binds event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint has no event ID or digest and grants no admission. An untouched never-joined pair's first explicit `JOIN` is event sequence `1`; when Account has first committed the separate owner-proved creator membership event at sequence `1`, a later explicit `JOIN` consumes that current checkpoint and is event sequence `2` under the [Account owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. +- **Never-joined pair baseline** – For each verified account/tenant pair, Account owns a durable pair-authority record with a positive membership generation and independent positive membership version even while membership is absent. A sequence-zero response requires one Account-fenced snapshot that proves this exact record, the verified pair identity, no current membership, and no committed membership event or retained contradictory history; absence of a row alone is never a generation, version, or checkpoint. An ordinary first explicit `JOIN` with no earlier membership event commits event sequence `1`; a separate owner-proved tenant-creator membership event occupies sequence `1` before any later explicit `JOIN`. Each operation advances `membershipVersion` exactly once from the actual current Account baseline and advances `membershipAuthorityGeneration` independently only if the committed transition records `callerBoundAuthorityInvalidated=true`; Account's [tenant-role owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration) owns creator source, commit, retry, and readback details. Existing retained membership versions and positive event sequences are preserved rather than assigned a synthetic absence baseline or renumbered. Unmapped or contradictory pairs remain denied, and sequence zero never authorizes admission. - **Membership event continuity** – Membership changes use only `account:auth-authority:v1:membership//`. Each event names `outboxStreamKey`, `sourceScope` (`membership//`), `outboxSequence`, `eventId`, the complete applicable `authorityTuple`/`issuanceFence`, and the Account snapshot's `accountId`, `tenantId`, `membershipVersion`, membership payload, admission flag, and `callerBoundAuthorityInvalidated` result. `sourceScope` must decode to `outboxStreamKey`; each consumer stores a `watermark` and event identity/digest per exact stream and marks delivery `contiguous` only when the next sequence is `watermark + 1` (with first-stream initialization from the Account checkpoint). A duplicate at or below the watermark is valid only when all evidence matches; a same-sequence conflict quarantines the affected scope. A higher sequence is a gap only within that same stream; unrelated streams do not advance or gap this watermark. Conflicts, non-contiguous delivery, missing or mismatched tuple/checkpoint evidence, or an unresolved membership-version/generation pair stop affected admission and reconnect/validation until exact Account reconciliation proves coverage; unavailable reconciliation returns retryable `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence is denied/revoked. - **Membership event digest** – `account-auth-authority-event/v1` is the closed wire/preimage schema for a committed Account membership-change event; other event types, including a deletion/tombstone, require their own declared schema before emission. Its required top-level fields are `schemaVersion` (exactly `account-auth-authority-event/v1`), `eventType` (exactly `MEMBERSHIP_CHANGED`), `eventId`, `requestId`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipExists` (exactly `true`), `membershipLifecycleState` (`ACTIVE` or `INACTIVE`), `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `issuanceFence`, `roles`, `gameplayAdmissionAllowed`, and `callerBoundAuthorityInvalidated`. The sole additional wire field is `eventDigest`; the digest preimage excludes **only** that field. No undeclared field may be emitted or accepted, and a changed declared field changes the digest. `accountId` and `tenantId` are canonical lowercase UUID strings; `sourceScope` and stream key encode those exact IDs. `gameplayAdmissionAllowed` is false for `INACTIVE`; a missing row is not an event. `roles` is a required, duplicate-free array of canonical role names sorted by Unicode code-point order; its empty value is `[]`, not omission. The complete applicable `authorityTuple` uses the field names and presence rules in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple): `issuerAuthGeneration`, `accountAuthorityGeneration`, `tenantAuthorityGeneration`, `membershipAuthorityGeneration`, and `privateRealmGrantVersions` are always present; `accountSecurityCutoff` and `tenantBillingCutoff` are omitted only when inapplicable. Both generation maps have exactly the event's `tenantId` key, and the membership-map value equals the separately carried `membershipAuthorityGeneration`; no unrelated tenant entry is applicable to this one-member event. The optional `tenantBillingCutoff` map, when present, likewise has exactly that tenant key, and every private-realm grant entry, when present, belongs to that tenant. Maps are keyed by exact canonical tenant UUID; private-realm grant entries contain all five canonical fields and are sorted lexicographically by `(tenantId, worldSlug, realmSlug, playtestLifecycleId)`, with duplicate identities rejected. All generations, versions, sequences, cutoffs, grant versions, and `issuanceFence` in this event are canonical unsigned decimal **strings** (`0` only where the owning field permits it; no sign, leading zero, exponent, whitespace, or JSON number), preserving values above JavaScript's exact-integer range. `null` never substitutes for omission or an empty list/map. The producer serializes this complete event without `eventDigest` as RFC 8785 canonical JSON UTF-8 and sets `eventDigest` to lowercase `sha256:` plus the SHA-256 hex of those bytes; receivers validate the closed shape, field types, scope coherence, canonical collection rules, and recomputed digest before applying or acknowledging it. This digest binds immutable source evidence; it does not substitute for Account authentication, source sequencing, or current-authority comparison. - **Authority validation outcomes** – A registry, lease, gameplay binding, token-identity fence, Account authority source, or authority-projection freshness fence that cannot be reached or times out is a retryable `AUTH_UNAVAILABLE` / HTTP 503 condition; this includes runtime membership-authority reads. It does not revoke the client's authentication and no cached authority may authorize the failed operation. Reachable missing, malformed, expired, revoked, stale, regressed, or mismatched evidence is an authentication failure (`AUTH_SESSION_REVOKED` or the specific invalid-token outcome) and requires reauthentication. Registry presence or absence never overrides this classification; membership-authority failures use these same availability-versus-denial rules and do not introduce a second canonical error. @@ -168,19 +170,23 @@ FireMUD standardizes a small, explicit role set so tenant authorization and cros Account is the sole authority for global-role grants, revocations, and current role evidence. Ordinary global-role changes are human operator actions entering through Gateway → Logging & Admin; the actor must have a live `platformAdmin` role and current `privileged_control` step-up evidence under [ADR 0045](./decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md). Account provides the currentness authorization and revalidates it at the owner commit, where durable audit evidence accompanies the role change. The operator ingress and owner execution follow [ADR 0047](./decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Unattended automation cannot grant or revoke global roles. The first `platformAdmin` requires a separate one-time protected deployment bootstrap; registration order, a legacy scalar, a token claim, or tenant authority never establishes it. See [ADR 0185](./decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md), [Account's owner contract](./microservices/account-service/api-contracts.md#account-owned-global-role-administration), and [Logging & Admin's ingress consequence](./microservices/logging-admin-service/api-contracts.md#global-role-administration-ingress). +**Tenant-role administration.** Account is also the sole authority for tenant-role assignments. A current `tenantAdmin` may grant or revoke only the `designer` role for an explicitly identified account in that same verified tenant; this does not establish generic role delegation. Initial `tenantAdmin` assignment belongs only to the authenticated initiator of the exact committed, owner-issued tenant-creation operation. It creates a control-only `ACTIVE` membership with exactly the `tenantAdmin` role, no `player`, and no gameplay admission; it is distinct from public `JOIN`, which may later add `player` only from that exact owner-proved state after the ordinary fresh JOIN gates pass. A tenant-admin handoff is one atomic transfer from an existing same-tenant `tenantAdmin` to an explicit same-tenant account and must leave at least one current `tenantAdmin`. The UI-selected tenant, billing or payment ownership, and global roles do not establish tenant target scope or initial-admin authority. + +Tenant-role changes advance the affected membership's independent `membershipVersion`. `membershipAuthorityGeneration` advances separately only when Account's committed change records `callerBoundAuthorityInvalidated=true`; granting a role does not imply a universal generation bump. Account owns commit, event, exact readback, and retry mechanics under its [tenant-role contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). Global roles, billing ownership, subscriptions, and hosted creator-party or terms authority remain independent. + Global-role mutation is target-only and unavailable until the Account commit-time authorization, independent role-source evidence, durable event/audit, exact same-snapshot readback, protected bootstrap, and focused proof are implemented. The global-account action scope is distinct from `tenant_scope`; a tenant ID or tenant-role branch cannot represent a global-role target. Exact API route, action schema, event schema, bootstrap artifact, and retry/recovery mechanics remain unselected by ADR 0185. Services must not introduce ad-hoc roles without updating this model and the Tenant Authorization Contract. Where finer-grained behavior is required, services should prefer additional capabilities/flags derived from these core roles rather than inventing new top-level roles. Official-hosted creator-party and signer authority under [ADR 0180](./decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) is Account-owned evidence, not a global or tenant role and must not be embedded as a broad JWT role. Account evaluates the party, authenticated signer authority, current terms acceptance, and requested legal action at the acceptance boundary. `tenantAdmin`, `designer`, organization administration, billing ownership, payment, or a company email domain do not establish signer authority. Game Design separately requires current tenant authorization and current party acceptance; neither substitutes for the other. -The tenant-role model is an accepted target decision, and tenantless control login with navigation-only tenant selection and reauthorization on each selected tenant is an accepted target decision under [ADR 0040](./decisions/adr-0040-account-global-control-login-and-explicit-tenant-selection.md). These decisions do not claim complete implementation or proof: tenant-scoped role persistence and `scopedRoles` issuance, switching controls, and the associated end-to-end evidence remain tracked gaps in the [Player Access and Session implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#capability-status), with focused evidence and missing proof listed under [Validation and Proof](../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). +The tenant-role model is an accepted target decision, and tenantless control login with navigation-only tenant selection and reauthorization on each selected tenant is an accepted target decision under [ADR 0040](./decisions/adr-0040-account-global-control-login-and-explicit-tenant-selection.md). Neither approval claims complete implementation or proof. Tenant-role mutation, first-admin initiator evidence, tenant-scoped role persistence and `scopedRoles` issuance, switching controls, and associated end-to-end evidence remain tracked gaps in the [Player Access and Session implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#capability-status), with focused evidence and missing proof listed under [Validation and Proof](../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ### Global Role to Route-Class Matrix (Normative) The canonical global-role-to-route-class mapping is [Authorization Route Matrix](./system-architecture-authz-route-matrix.md#classification-rules). Global roles must not be interpreted as broad tenant or gameplay shortcuts. -Authentication-local gameplay consequence: global roles never grant gameplay admission or switching. Character access, character creation, connect-token issuance, and `PLAY` require caller-bound `ACTIVE` membership plus any applicable realm grant; only explicit public-production `JOIN`/`Join & Play` may create or restore membership. Current implementation drift is recorded in Implementation Status. +Authentication-local gameplay consequence: global roles never grant gameplay admission or switching. Character access, character creation, connect-token issuance, and `PLAY` require caller-bound admitting `ACTIVE` membership that includes `player`, plus any applicable realm grant. Account's separately owner-proved tenant-creator bootstrap can establish only a control membership, never gameplay admission; only explicit public-production `JOIN`/`Join & Play` adds or restores `player` membership or admission. An explicit `JOIN` from the exact source-proved creator `ACTIVE`/no-`player`/non-admitting state remains subject to the ordinary fresh JOIN gates under [Account's owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). Current implementation drift is recorded in Implementation Status. Role assurance is route-specific and follows the [Authorization Route Matrix](./system-architecture-authz-route-matrix.md#privileged-role-assurance); a role name alone never supplies elevation. @@ -372,8 +378,8 @@ Normative semantic split: - `LOGIN` proves or restores account identity. - `LOGIN` establishes the authenticated socket/session account context only; it does not select a tenant or character and does not create a gameplay binding. Gameplay admission, binding, and finalization belong to `PLAY`. -- When the selected public-production tenant has missing or `INACTIVE` caller-bound membership, `JOIN ` explicitly establishes `ACTIVE` membership after authenticated `REALMS` discovery and before `CHARS` or character creation. Either create or restore advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when `callerBoundAuthorityInvalidated=true`. An `ACTIVE` membership returns the exact idempotent current snapshot. Any other lifecycle state rejects. A caller with existing `ACTIVE` membership omits `JOIN` and continues to character selection and `PLAY`. First-party browser/mobile clients use the equivalent Account bootstrap join endpoint. -- The direct-text `LOGIN` plus `PLAY` compatibility shortcut is limited to an existing `membershipLifecycleState=ACTIVE` member for the same target. It may omit `JOIN` only because membership is already active, and it may omit a separate `CHARS` round-trip only when fresh transport-local resolution supplies one valid current character; it never reuses a first-party WebSocket discovery snapshot. First-party/browser clients always use authenticated bootstrap, discovery, and lobby gates, including for returning members. +- When the selected public-production tenant has missing or `INACTIVE` caller-bound membership, `JOIN ` explicitly establishes or restores an admitting `ACTIVE` membership with `player` after authenticated `REALMS` discovery and before `CHARS` or character creation. An explicit JOIN may also add `player` from only the exact source-proved creator `ACTIVE`/no-`player`/non-admitting state described in [Account's owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration), and still passes the same fresh JOIN gates. Each committed change advances `membershipVersion` from the actual current value; `membershipAuthorityGeneration` advances independently only when `callerBoundAuthorityInvalidated=true`. An already admitting `ACTIVE` membership returns the exact idempotent current snapshot. Any other lifecycle or non-admitting source state rejects. A caller with existing admitting `ACTIVE` membership and `player` omits `JOIN` and continues to character selection and `PLAY`. First-party browser/mobile clients use the equivalent Account bootstrap join endpoint. +- The direct-text `LOGIN` plus `PLAY` compatibility shortcut is limited to an existing admitting `membershipLifecycleState=ACTIVE` membership with `player` for the same target. It may omit `JOIN` only because membership is already admitting; an `ACTIVE` control-only creator membership does not qualify and must first use explicit `JOIN` from its exact source-proved state under the ordinary fresh gates. It may omit a separate `CHARS` round-trip only when fresh transport-local resolution supplies one valid current character; it never reuses a first-party WebSocket discovery snapshot. First-party/browser clients always use authenticated bootstrap, discovery, and lobby gates, including for returning members. - `PLAY` binds the gameplay session to `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. ### In-Band `PLAY` Admission Boundary @@ -727,7 +733,7 @@ The canonical cross-surface `PLAY` outcome inventory and precedence are defined - Runtime control-plane and admission flows use the realm-routing contract from [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) as the source of truth for which concrete `gameInstanceId` is admissible for the selected realm. - After the canonical routing and connect-scope gates, consults the runtime entitlement contract `GetTenantEntitlementsForRuntime(tenantId, requestId)` to confirm that the tenant is currently available for gameplay (for example, subscription state is not `suspended` or `canceled` and hard quotas are not violated). For player admission, the returned evidence is caller-bound to `accountId`, the verified `connectScopeId`, and the exact resolved target; a tenant-only entitlement bundle cannot authorize a player binding. - Verifies that the account is authorized to play in that `tenantId` using caller-bound gameplay membership and any required realm grant. Global roles and public discoverability alone must not satisfy gameplay admission. -- If the public realm is visible but the account's durable membership is missing or `INACTIVE`, returns `JOIN_REQUIRED` with `JOIN `/`Join & Play` recovery guidance and does not create membership or other admission state. This classification occurs only after fresh Account entitlement says `allowPublicJoin=true` and fresh selected-target catalog/pointer evidence identifies the public-production realm; entitlement outage returns `ENTITLEMENT_UNAVAILABLE` and a public policy/target denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`. Explicit public-production `JOIN` establishes or restores `ACTIVE` membership as defined above; an `ACTIVE` membership is returned idempotently and all other states reject. Private/playtest admission requires existing `ACTIVE` membership plus its current grant and never invokes this writer. +- If the public realm is visible but the account's durable membership is missing or `INACTIVE`, returns `JOIN_REQUIRED` with `JOIN `/`Join & Play` recovery guidance and does not create membership or other admission state. This classification occurs only after fresh Account entitlement says `allowPublicJoin=true` and fresh selected-target catalog/pointer evidence identifies the public-production realm; entitlement outage returns `ENTITLEMENT_UNAVAILABLE` and a public policy/target denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`. This `PLAY` classifier remains limited to missing or `INACTIVE` membership: an `ACTIVE` but non-admitting state, including the creator's control membership, is not admission and does not itself receive JOIN advice. A separately invoked explicit public-production `JOIN` establishes or restores an admitting `ACTIVE` membership with `player`; it may begin from the exact source-proved creator control state under the ordinary fresh gates in [Account's owner contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). An already admitting `ACTIVE` membership is returned idempotently; other states reject. Private/playtest admission requires existing admitting `ACTIVE` membership with `player` plus its current grant and never invokes this writer. - **Target membership-writer contract:** Membership lifecycle writer authority remains Account Service. The accepted canonical API is `JoinPublicProductionMembership`; the obsolete differently named proto/client/service seam has been removed rather than retained as a compatibility operation. The text-protocol adapter passes only the Account-bound `{connectScopeId, requestId}` plus trusted caller context to `JoinPublicProductionMembership`; world and realm remain adapter-local selectors, and the adapter never passes client- or adapter-supplied `tenantId`, route, `gameInstanceId`, `catalogRevision`, `pointerVersion`, or route authority. Account resolves and revalidates the complete scope `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` and `connectScopeSnapshotDigest` from `connectScopeId` at the commit gate; a non-public target additionally carries exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. It does not accept those fields as independently authoritative player inputs. The operation is explicit `JOIN`/`Join & Play`; character creation, connect-token issuance, and `PLAY` never create or restore membership. Current writer and issuance gaps are recorded in [Implementation Status](#implementation-status). - Performs an authoritative internal membership read for `{accountId, tenantId}`, requires `membershipExists=true` and exact `membershipLifecycleState=ACTIVE`, and obtains both `membershipVersion` and `membershipAuthorityGeneration`. For connect-token-backed admission, these three values must exactly equal the issuance baseline captured from one Account snapshot; the baseline is carried unchanged through the Account lease, Game Session binding CAS, and Account finalization. The membership response must also assert `gameplayAdmissionAllowed=true`; gameplay admission must not source membership state, either membership field, or gameplay authority from JWT claims or local caches. Before the binding can become admissible, Account must issue an exact-binding admission lease containing a unique lease ID, monotonic lease fence, immutable authority tuple/cutoff checkpoint, the unchanged membership lifecycle/generation/version baseline, and a bounded absolute expiry no longer than the admission SLA; the lease cannot be renewed to extend an admission attempt. Game Session's binding CAS includes that fence and may publish only a provisional record. Account finalization, abort, and reconciliation are idempotent by lease ID and request ID and must reject any recomputed or changed baseline. A binding CAS failure, lease expiry, authority cutoff, membership lifecycle/generation/version change, or ambiguous outcome invokes the idempotent Account abort/reconcile path; when a token identity or matching issued-token record exists, Account must retire or revoke that exact orphan token through the same idempotent path, while no-token outcomes are recorded without fabricating an identity. Account emits durable orphan binding evidence and a cleanup request, Gateway performs fenced edge cleanup, and Game Session performs fenced binding/index cleanup. A provisional record is never admissible, resumable, or takeover-eligible; only a durably finalized `COMMITTED` lease can admit gameplay. - Resolves `[character]` to a canonical Entity-owned persisted `characterId` within the resolved first-party scope `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt}` according to the selected realm's published entry policy and its applicable versioned descriptor or template. A non-public target additionally carries exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. Entity first validates the trusted `accountId`-to-character association and caller visibility for that exact target; Game Session creates no binding until both ownership and visibility evidence complete. Server-derived `playableStateScope` is binding/routing/policy/authorization evidence rather than controller identity. It then binds the live session to target uniqueness `{tenantId, playableStateNamespaceId, characterId}` with active runtime/value evidence `{playableStateScope, gameInstanceId, sessionId, bindingGeneration}`. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index feef98bb7b..7442840272 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -30,6 +30,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. - Global-role grant/revoke administration is a target-only Account owner action, not a current route. Its human ingress must use Gateway → Logging & Admin, require live `platformAdmin` and `privileged_control`, and obtain Account currentness authorization that Account revalidates at commit with durable audit. The first administrator is a separate protected deployment bootstrap; automation, registration order, token claims, legacy scalar roles, and tenant scope cannot establish or mutate global roles. `operator_delegation.global_role_administration` records the target-only global-account action boundary separately from the closed authorization-reference branches; no action schema or route is published or routable. See [ADR 0185](./decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). +- Tenant-role mutation remains target-only and is not a route in the validated inventory. Any future mutation entry must use an explicit tenant and the `tenant_regular` live-membership branch for same-tenant `tenantAdmin` designer changes or atomic administrator transfer, with no `platformAdmin` alternative. The approved creator bootstrap is a separate Account membership-stream write, not public `JOIN` or gameplay admission; a later actual explicit `JOIN` from its exact owner-proved control-only state still passes the ordinary fresh JOIN gates. Existing Account membership, membership-version, tenant-generation, and evidence-bundle predicates apply; see [Account's tenant-role contract](./microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. - `LinkExternalAccount` is target-only and currently unavailable. The current tenant-scoped caller-asserted scaffold must not be exposed or advertised; the target global-account route is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md) and remains unavailable until server-verified provider authorization and recent ordinary reauthentication exist. - The current Account implementation of `ExportTenantData` remains account-targeted while the canonical target is a tenant-wide, tenant-owned export; this is recorded as known drift while the target route remains a distinct `billing_safe_tenant` exception. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 709ba78a52..6392704293 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -381,12 +381,15 @@ Packet 2 historical-alias rule: `MS-AA-TOKEN-REVOCATION` is a superseded service `AUTH-GLOBAL-ROLE-WRITER-01` is the sixth post-archive direct human decision recorded in this unmerged candidate. It records approval of the authority boundary only; it does not claim merged application, runtime implementation, or proof completion. +The `AUTH-GLOBAL-ROLE-WRITER-01` and `AUTH-TENANT-ROLE-OWNER-01` entries below are supplemental approval records in this unmerged candidate; they do not alter the historical archive, source-allocation, or audited decision totals above. + - [x] `COMMERCE-02` — `accepted` on 2026-08-25; initial human approval on 2026-08-23 and final refinement/application on 2026-08-25; [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) - [x] `HOSTED-TERMS-01` — `accepted` on 2026-08-25; initial human approval on 2026-08-24 and final refinement/application on 2026-08-25; [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) - [x] `HOSTED-TERMS-02` — `accepted` on 2026-08-25; initial human approval on 2026-08-24 and final refinement/application on 2026-08-25; [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) - [x] `OPS-07` — `revised` on 2026-09-06; [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) - [x] `EDGE-WITHDRAWAL-01` — `accepted` on 2026-09-24; human-approved emergency cutoff despite possible service interruption; [ADR 0184](../../architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md) - [x] `AUTH-GLOBAL-ROLE-WRITER-01` — `accepted` on 2026-10-04; Ben explicitly selected “Approve this boundary (Recommended),” relayed through Overseer inbox `0f5ec31e-db81-4b31-ab9c-7e94b257cd62`; [ADR 0185](../../architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md) +- [x] `AUTH-TENANT-ROLE-OWNER-01` — `accepted` on 2026-10-05; Ben approved same-tenant `tenantAdmin` management of `designer` roles, automatic first-`tenantAdmin` assignment to the verified tenant-creation initiator, and atomic same-tenant administrator transfer that preserves at least one current administrator. Approval was relayed through Overseer inbox `db1d32d5-e9ab-4726-bb5e-b720367aa8af` at `2026-10-05T04:01:52Z`; refined by Overseer approval `2eff595d-d41b-4e08-9b4b-919796e35190` on 2026-10-05 to distinguish the source-bound creator's first non-admitting membership event from a later explicit JOIN that passes the ordinary fresh JOIN gates; [canonical contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-tenant-role-administration); no ADR required ### Allocation Notes 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 f6f004b057..638c948b2a 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,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The tenant-role owner policy (`AUTH-TENANT-ROLE-OWNER-01`) was approved on 2026-10-05. The unwired existing-member candidate now implements designer grant/revoke and atomic administrator transfer for exactly proved, retained, admitting `EXPLICIT_JOIN` memberships. V56 adds an immutable request/result journal and member evidence; the Account transaction serializes canonical actor/target rows, checks current role/version sources, commits matching membership events, checkpoints and canonical audit evidence, and verifies exact readback. Exact committed retries preserve the original result after later role changes. These internal sources do not authenticate the supplied actor, implement public role ingress, or produce the complete Account authorization bundle; those required capabilities remain open and no route or RPC is enabled. + +The corrected Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m44s (72 tasks: 24 executed, 48 up-to-date). Parsed XML records 940 unit executions without failures, errors or skips, including eleven new digest/journal cases. All 344 integration cases compile and skip locally without Docker. The thirteen new PostgreSQL definitions cover the actual unwired mutation service and journal: current-role/version/tenant/membership denial without mutation, grant/revoke/transfer, immutable retry, event/audit/readback rollback, fence exhaustion and concurrent opposing transfers. Their retained administrator fixture stipulates coherent historical owner evidence rather than proving an authenticated enrollment producer. CI requires all thirteen exact methods without skips and captures raw XML; database execution, authenticated actor and creator producers, fresh-image composition and live delivery remain open. Constructor annotations are narrowly scoped to injected-collaborator validation and do not relax runtime guards; the eighteen discarded protobuf configuration-cache problems do not establish cache support. + +The established fresh verified absence baseline is `membershipVersion=1`, `membershipAuthorityGeneration=1`, and membership-stream sequence `0`; the canonical first-JOIN PostgreSQL case asserts baseline version `1`. Under the approved creator bootstrap, Account must write the first membership event at sequence `1`, then permit a later actual JOIN from that exact control-only state at sequence `2`; each write must advance from the actual current membership-version baseline by one, without resetting or hardcoding retained values. The creator-bootstrap writer and its authenticated ingress are not implemented; existing-member storage preparation does not prove them. `GameTenantCreationRepository.createCandidate` and `FreshTenantCreationEvidence` do not bind the authenticated initiating Account UUID or an authorization reference, so first-admin assignment still awaits the exact Game Design-to-Account creation-initiator handoff. The tenant identity receipt and retained-row manifest do not establish that actor. See [Authentication's role model](../../architecture/system-architecture-authentication.md#role-model) and the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-tenant-role-administration). + Exact cumulative `12d6cf5cfab437c0d69583566a6aa0738a644986` [CI37218116041](https://github.com/benhook1013/FireMUD/actions/runs/37218116041) is terminal `FAILURE`. Independently parsed raw XML proves four Account canonical reconciliation, ten Game Session source and five canonical catalog methods executed cleanly without skips. The Account scope suite executed four methods with one failure: its deliberate missing-source injection was blocked by the actual scope-reference foreign key, then its `finally` statement masked that rejection in an aborted transaction. The fixture correction separately proves the normal FK rejection without mutation and simulates corrupt retained storage only inside its private schema with transactional guard restoration. Game Session preparation executed three methods with one failure because the assertion guessed a source operation ID instead of reading the actual committed intake receipt; its correction uses the stored ID. These corrections preserve the production guards and original retry/rollback/concurrency obligations. Corrected-head PostgreSQL execution remains required; local compilation or Docker-free skips do not close either proof gap. The Game Design release identity/immutability and immediate raw-report capture corrections are recorded in the [publishing tracker](./game-authoring-publishing-and-activation.md); shared Python/TCP failures remain separately owned. None of this enables membership, credentials, launch or the response-envelope mount. The source-qualified launch-preparation candidate is an unwired Game Session consumer of the committed canonical catalog/source intake and exact Game Design descriptor. It resolves and independently reads back the descriptor outside an owner transaction, then locks/revalidates the catalog/source in a short writable READ COMMITTED transaction and independently recovers the immutable local result after commit. Its preparation binds the acting Account UUID as identity only; no creator/terms authorization, runtime instance allocation, World preparation, first OPEN or admission is implemented by this primitive. The corrected local Game Session full check, boot JAR, schema generation, formatting, analyzers, coverage and documentation gate passes in 2m1s (255 tasks: 41 executed, 214 up-to-date). All nine new unit cases execute cleanly; the module executes 1,895 unit, 18 integration and 26 cross-service cases with no failures/errors. Another 17 unit, 177 integration and 54 cross-service cases skip, including all three new PostgreSQL methods without Docker. Those three cases define V13→V14 preservation with no preparation backfill, retained-row isolation, exact committed retry, rollback/immutability, stored catalog-payload tamper rejection and concurrent recovery of one operation; Game Design responses are synthetic, so even their later database execution will not prove authenticated transport or complete release authority. The first gate failed on two test compilation defects and an unused production local; those were corrected without weakening guards before the passing run. CI requires the three exact PostgreSQL methods and uploads raw XML; corrected-head execution remains open. Complete authenticated source/descriptor composition, current Account authorization, full release attestation, canonical World lifecycle and positive JOIN/LOGIN remain open. The [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#source-qualified-launch-preparation-and-durable-readback) owns the binding, digest, transaction and retry rules; existing runtime and ring-mount activation gates remain closed. @@ -450,7 +456,7 @@ The canonical Account-signed selected-target `gameplay-connect` profile and Gate Separately, hosted CI run `36703863842` on committed #2881 `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are exact-parent storage/integration results, not validation of #2911's new context path or proof of the complete credential producer/consumer flow. -The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The historical #2881 V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. +The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The historical #2881 V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; on that ordinary no-history path, first JOIN advances version from the established baseline `1` by one and event sequence from zero to one without advancing generation. The approved creator bootstrap instead occupies event sequence one before a later explicit JOIN; its writer must advance the actual current version once and preserve any retained positive counters and stream history. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests failed on an earlier head because their helper still expected bare-LOGIN success. The corrected helper now asserts `AUTH_UNAVAILABLE` and no promotion for that attempt, then uses credential-bearing LOGIN for supported gameplay coverage; the dedicated negative fixture expects following `PLAY` to require login. Both affected Docker-backed classes skipped locally, so this is a corrected assertion, not executed WebSocket end-to-end proof or a working Account exchange. Positive first-party bare-LOGIN proof remains an explicit activation gate. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 55f6d2e9c0..d16fad325f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -92,6 +92,50 @@ public Optional findExactCanonicalTenantEnvelopeForUpdate( return found; } + /** + * Locks and verifies one exact committed tenant-role audit envelope from its immutable journal. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalTenantRoleEnvelopeForUpdate( + UUID auditEventId, + UUID canonicalTenantUuid, + Instant occurredAt, + String payloadDigest, + String payload) { + requireReadWriteOwnerTransaction(); + if (auditEventId == null + || canonicalTenantUuid == null + || occurredAt == null + || !AccountAuditDigest.isValid(payloadDigest) + || payload == null + || !payloadDigest.equals(AccountAuditDigest.ofPayload(payload))) { + throw new IllegalArgumentException("Exact tenant-role audit evidence is required"); + } + Optional found = + dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) + .forUpdate() + .fetchOptional(this::toEnvelope); + found.ifPresent( + actual -> { + if (!"tenant".equals(actual.scope()) + || actual.tenantIdentityVersion() != AccountAuditTenantIdentity.VERSION_2 + || actual.tenantId() != null + || !canonicalTenantUuid.equals(actual.tenantUuid()) + || !"account-service".equals(actual.producerService()) + || !"ACCOUNT_TENANT_ROLE_CHANGED".equals(actual.eventType()) + || !occurredAt.equals(actual.occurredAt()) + || actual.schemaVersion() != 1 + || actual.payloadDigestVersion() != 1 + || !payloadDigest.equals(actual.payloadDigest()) + || !payload.equals(actual.payload())) { + throw new IllegalStateException( + "Tenant-role audit envelope differs from its immutable operation evidence"); + } + }); + return found; + } + /** * Locks the existing JOIN audit identity and returns it only for its exact canonical UUID scope. * A present event with another scope, tenant representation, producer, or event type is diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index 3e30ad7734..4035e02a27 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -46,6 +46,17 @@ public Optional findByAccountUuid(UUID accountUuid) { .fetchOne(this::toEntity)); } + /** Locks one exact UUID-qualified Account owner row for ordered multi-member mutations. */ + public Optional findByAccountUuidForUpdate(UUID accountUuid) { + Objects.requireNonNull(accountUuid, "accountUuid must not be null"); + AccountsRecord row = + dsl.selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid)) + .forUpdate() + .fetchOne(); + return Optional.ofNullable(row).map(this::toEntity); + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigest.java new file mode 100644 index 0000000000..726338a8eb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Versioned, byte-length-framed identities for Account-owned tenant-role operations. */ +public final class AccountTenantRoleMutationDigest { + private static final String REQUEST_DOMAIN = "firemud/account/tenant-role/request/v1"; + private static final String RESULT_DOMAIN = "firemud/account/tenant-role/result/v1"; + + private AccountTenantRoleMutationDigest() {} + + public static byte[] requestBytes( + UUID requestId, + UUID actorAccountUuid, + UUID tenantUuid, + UUID targetAccountUuid, + String action, + long expectedActorMembershipVersion, + long expectedTargetMembershipVersion) { + if (requestId == null + || actorAccountUuid == null + || tenantUuid == null + || targetAccountUuid == null + || action == null + || expectedActorMembershipVersion <= 0 + || expectedTargetMembershipVersion <= 0) { + throw new IllegalArgumentException("Complete tenant-role request identity is required"); + } + return framed( + REQUEST_DOMAIN, + requestId.toString(), + actorAccountUuid.toString(), + tenantUuid.toString(), + targetAccountUuid.toString(), + action, + Long.toString(expectedActorMembershipVersion), + Long.toString(expectedTargetMembershipVersion)); + } + + public static byte[] resultBytes( + UUID requestId, + String requestDigest, + UUID tenantUuid, + UUID auditEventId, + String auditEventType, + String auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + java.util.List members) { + if (requestId == null + || requestDigest == null + || tenantUuid == null + || auditEventId == null + || auditEventType == null + || auditOccurredAt == null + || auditPayloadDigest == null + || auditPayload == null + || members == null + || members.isEmpty()) { + throw new IllegalArgumentException("Complete tenant-role operation result is required"); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream framed = new DataOutputStream(bytes)) { + writeField(framed, RESULT_DOMAIN.getBytes(StandardCharsets.UTF_8)); + writeField(framed, requestId.toString().getBytes(StandardCharsets.UTF_8)); + writeField(framed, requestDigest.getBytes(StandardCharsets.UTF_8)); + writeField(framed, tenantUuid.toString().getBytes(StandardCharsets.UTF_8)); + writeField(framed, auditEventId.toString().getBytes(StandardCharsets.UTF_8)); + writeField(framed, auditEventType.getBytes(StandardCharsets.UTF_8)); + writeField(framed, auditOccurredAt.getBytes(StandardCharsets.UTF_8)); + writeField(framed, auditPayloadDigest.getBytes(StandardCharsets.UTF_8)); + writeField(framed, auditPayload); + framed.writeInt(members.size()); + for (MemberResult member : members.stream().sorted().toList()) { + writeField(framed, member.accountUuid().toString().getBytes(StandardCharsets.UTF_8)); + writeField(framed, member.tenantUuid().toString().getBytes(StandardCharsets.UTF_8)); + writeField( + framed, Long.toString(member.membershipVersion()).getBytes(StandardCharsets.UTF_8)); + writeField( + framed, + Long.toString(member.membershipAuthorityGeneration()).getBytes(StandardCharsets.UTF_8)); + writeField(framed, Long.toString(member.eventSequence()).getBytes(StandardCharsets.UTF_8)); + writeField(framed, member.eventRequestId().getBytes(StandardCharsets.UTF_8)); + writeField(framed, member.eventId().getBytes(StandardCharsets.UTF_8)); + writeField(framed, member.eventDigest().getBytes(StandardCharsets.UTF_8)); + framed.writeBoolean(member.callerBoundAuthorityInvalidated()); + writeField(framed, member.eventPayload()); + } + framed.flush(); + return bytes.toByteArray(); + } catch (IOException impossibleForByteArray) { + throw new IllegalStateException("Tenant-role result framing failed", impossibleForByteArray); + } + } + + public static String sha256(byte[] exactBytes) { + if (exactBytes == null) { + throw new IllegalArgumentException("Exact digest input bytes are required"); + } + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(exactBytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static byte[] framed(String... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream framed = new DataOutputStream(bytes)) { + for (String field : fields) { + writeField(framed, field.getBytes(StandardCharsets.UTF_8)); + } + framed.flush(); + return bytes.toByteArray(); + } catch (IOException impossibleForByteArray) { + throw new IllegalStateException("Tenant-role request framing failed", impossibleForByteArray); + } + } + + private static void writeField(DataOutputStream output, byte[] field) throws IOException { + output.writeInt(field.length); + output.write(field); + } + + public record MemberResult( + UUID accountUuid, + UUID tenantUuid, + long membershipVersion, + long membershipAuthorityGeneration, + long eventSequence, + String eventRequestId, + String eventId, + String eventDigest, + boolean callerBoundAuthorityInvalidated, + byte[] eventPayload) + implements Comparable { + public MemberResult { + if (accountUuid == null + || tenantUuid == null + || membershipVersion <= 0 + || membershipAuthorityGeneration <= 0 + || eventSequence <= 0 + || eventRequestId == null + || eventRequestId.isBlank() + || eventId == null + || eventId.isBlank() + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || eventPayload == null) { + throw new IllegalArgumentException("Complete tenant-role member result is required"); + } + eventPayload = eventPayload.clone(); + } + + @Override + public byte[] eventPayload() { + return eventPayload.clone(); + } + + @Override + public int compareTo(MemberResult other) { + return accountUuid.toString().compareTo(other.accountUuid.toString()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java new file mode 100644 index 0000000000..24d79c4e60 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java @@ -0,0 +1,665 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable request, result, and current-event evidence for unregistered tenant-role mutations. */ +@Repository +public class AccountTenantRoleOperationRepository { + private static final String OPERATIONS = "account_tenant_role_operations"; + private static final String MEMBERS = "account_tenant_role_operation_members"; + private static final int SCHEMA_VERSION = 1; + private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_ROLE_CHANGED"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor validates injected internal collaborators; it neither publishes this " + + "nor invokes overridable methods.") + public AccountTenantRoleOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Claims a request in the caller's write transaction, or returns its exact committed result. */ + @Transactional(propagation = Propagation.MANDATORY) + public Claim claim(Request request) { + requireWriteOwnerTransaction(); + Objects.requireNonNull(request, "Tenant-role request is required"); + byte[] requestPayload = request.payload(); + String requestDigest = AccountTenantRoleMutationDigest.sha256(requestPayload); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (request_id, schema_version, actor_account_uuid, tenant_uuid, " + + "target_account_uuid, action, expected_actor_membership_version, " + + "expected_target_membership_version, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'IN_PROGRESS') ON CONFLICT DO NOTHING", + request.requestId(), + SCHEMA_VERSION, + request.actorAccountUuid(), + request.tenantUuid(), + request.targetAccountUuid(), + request.action().name(), + request.expectedActorMembershipVersion(), + request.expectedTargetMembershipVersion(), + requestPayload, + requestDigest); + if (inserted == 1) { + return new Claim(true, Optional.empty()); + } + if (inserted != 0) { + throw new IllegalStateException("Tenant-role request claim was not singular"); + } + + OperationEvidence existing = + readOperationForUpdate(request.requestId()) + .orElseThrow( + () -> new IllegalStateException("Conflicting tenant-role request disappeared")); + if (!existing.request().equals(request) + || !Arrays.equals(existing.requestPayload(), requestPayload) + || !existing.requestDigest().equals(requestDigest)) { + throw new OperationConflictException( + "Tenant-role request ID was reused with changed immutable input"); + } + if (!"COMMITTED".equals(existing.status())) { + throw new IllegalStateException("Incomplete tenant-role request is not replayable"); + } + return new Claim(false, Optional.of(existing)); + } + + /** Completes a claimed request only after all mutation, event, and audit writes read back. */ + @Transactional(propagation = Propagation.MANDATORY) + public OperationEvidence complete( + Request request, + AuditEvidence audit, + List members) { + requireWriteOwnerTransaction(); + Objects.requireNonNull(request, "Tenant-role request is required"); + Objects.requireNonNull(audit, "Tenant-role audit evidence is required"); + List orderedMembers = + members == null ? List.of() : members.stream().sorted().toList(); + requireResultShape(request, orderedMembers); + + String requestDigest = AccountTenantRoleMutationDigest.sha256(request.payload()); + byte[] resultPayload = + AccountTenantRoleMutationDigest.resultBytes( + request.requestId(), + requestDigest, + request.tenantUuid(), + audit.auditEventId(), + audit.eventType(), + audit.occurredAt().toString(), + audit.payloadDigest(), + audit.payload(), + orderedMembers); + String resultDigest = AccountTenantRoleMutationDigest.sha256(resultPayload); + int inserted = 0; + for (AccountTenantRoleMutationDigest.MemberResult member : orderedMembers) { + inserted += + dsl.execute( + "INSERT INTO " + + MEMBERS + + " (request_id, account_uuid, tenant_uuid, membership_version, " + + "membership_authority_generation, outbox_stream_key, event_request_id, " + + "event_sequence, event_id, event_digest, caller_bound_authority_invalidated, " + + "event_payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + request.requestId(), + member.accountUuid(), + member.tenantUuid(), + member.membershipVersion(), + member.membershipAuthorityGeneration(), + eventStreamKey(member.accountUuid(), member.tenantUuid()), + member.eventRequestId(), + member.eventSequence(), + member.eventId(), + member.eventDigest(), + member.callerBoundAuthorityInvalidated(), + member.eventPayload()); + } + if (inserted != orderedMembers.size()) { + throw new IllegalStateException("Tenant-role member evidence write count differs"); + } + + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET status = 'COMMITTED', audit_event_id = ?, audit_event_type = ?, " + + "audit_occurred_at = ?, audit_payload_digest = ?, audit_payload = ?, " + + "result_payload = ?, result_digest = ? " + + "WHERE request_id = ? AND status = 'IN_PROGRESS' AND request_digest = ?", + audit.auditEventId(), + audit.eventType(), + audit.occurredAt(), + audit.payloadDigest(), + audit.payload(), + resultPayload, + resultDigest, + request.requestId(), + requestDigest); + if (updated != 1) { + throw new IllegalStateException("Tenant-role operation completion was stale or ambiguous"); + } + + OperationEvidence exact = + readOperationForUpdate(request.requestId()) + .orElseThrow(() -> new IllegalStateException("Tenant-role result readback is absent")); + requireExactCompletedResult( + request, requestDigest, resultPayload, resultDigest, audit, orderedMembers, exact); + return exact; + } + + /** Resolves the exact immutable operation which emitted a current membership event. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCurrentMemberEvidenceForUpdate( + UUID accountUuid, UUID tenantUuid, String eventRequestId) { + requireWriteOwnerTransaction(); + if (accountUuid == null + || tenantUuid == null + || eventRequestId == null + || eventRequestId.isBlank()) { + throw new IllegalArgumentException("Exact current tenant-role event identity is required"); + } + Record row = + dsl.fetchOne( + "SELECT request_id FROM " + + MEMBERS + + " WHERE account_uuid = ? AND tenant_uuid = ? AND event_request_id = ? FOR UPDATE", + accountUuid, + tenantUuid, + eventRequestId); + if (row == null) { + return Optional.empty(); + } + UUID requestId = row.get("request_id", UUID.class); + OperationEvidence operation = + readOperationForUpdate(requestId) + .orElseThrow( + () -> new IllegalStateException("Tenant-role member row has no operation header")); + if (!"COMMITTED".equals(operation.status())) { + throw new IllegalStateException("Current tenant-role operation is not committed"); + } + AccountTenantRoleMutationDigest.MemberResult member = + operation.members().stream() + .filter( + candidate -> + candidate.accountUuid().equals(accountUuid) + && candidate.eventRequestId().equals(eventRequestId)) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "Current tenant-role event is absent from its exact operation result")); + return Optional.of(new CurrentMemberEvidence(operation, member)); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional findForUpdate(UUID requestId) { + requireWriteOwnerTransaction(); + Objects.requireNonNull(requestId, "Tenant-role request ID is required"); + return readOperationForUpdate(requestId); + } + + private Optional readOperationForUpdate(UUID requestId) { + Record row = + dsl.fetchOne( + "SELECT request_id, schema_version, actor_account_uuid, tenant_uuid, " + + "target_account_uuid, action, expected_actor_membership_version, " + + "expected_target_membership_version, request_payload, request_digest, status, " + + "audit_event_id, audit_event_type, audit_occurred_at, audit_payload_digest, " + + "audit_payload, result_payload, result_digest " + + "FROM " + + OPERATIONS + + " WHERE request_id = ? FOR UPDATE", + requestId); + if (row == null) { + return Optional.empty(); + } + Short schemaVersion = row.get("schema_version", Short.class); + if (schemaVersion == null || schemaVersion != SCHEMA_VERSION) { + throw new IllegalStateException("Tenant-role request schema version is unsupported"); + } + Request request = + new Request( + row.get("request_id", UUID.class), + row.get("actor_account_uuid", UUID.class), + row.get("tenant_uuid", UUID.class), + row.get("target_account_uuid", UUID.class), + Action.parse(row.get("action", String.class)), + requiredPositive(row, "expected_actor_membership_version"), + requiredPositive(row, "expected_target_membership_version")); + byte[] requestPayload = requiredBytes(row, "request_payload"); + String requestDigest = requiredText(row, "request_digest"); + if (!Arrays.equals(request.payload(), requestPayload) + || !AccountTenantRoleMutationDigest.sha256(requestPayload).equals(requestDigest)) { + throw new IllegalStateException("Tenant-role request bytes or digest are contradictory"); + } + + AuditEvidence audit = null; + byte[] resultPayload = null; + String resultDigest = null; + String status = requiredText(row, "status"); + if ("COMMITTED".equals(status)) { + audit = + new AuditEvidence( + row.get("audit_event_id", UUID.class), + requiredText(row, "audit_event_type"), + requiredInstant(row, "audit_occurred_at"), + requiredText(row, "audit_payload_digest"), + requiredBytes(row, "audit_payload")); + resultPayload = requiredBytes(row, "result_payload"); + resultDigest = requiredText(row, "result_digest"); + } else if (!"IN_PROGRESS".equals(status)) { + throw new IllegalStateException("Tenant-role request status is unsupported"); + } + + List members = readMembers(requestId); + if ("COMMITTED".equals(status)) { + requireResultShape(request, members); + byte[] expectedResult = + AccountTenantRoleMutationDigest.resultBytes( + request.requestId(), + requestDigest, + request.tenantUuid(), + audit.auditEventId(), + audit.eventType(), + audit.occurredAt().toString(), + audit.payloadDigest(), + audit.payload(), + members); + if (!Arrays.equals(expectedResult, resultPayload) + || !AccountTenantRoleMutationDigest.sha256(resultPayload).equals(resultDigest)) { + throw new IllegalStateException("Tenant-role immutable result bytes or digest differ"); + } + } else if (!members.isEmpty()) { + throw new IllegalStateException("Incomplete tenant-role operation has member results"); + } + + return Optional.of( + new OperationEvidence( + request, + requestPayload, + requestDigest, + status, + audit, + resultPayload, + resultDigest, + members)); + } + + private List readMembers(UUID requestId) { + List members = new ArrayList<>(); + for (Record row : + dsl.fetch( + "SELECT account_uuid, tenant_uuid, membership_version, membership_authority_generation, " + + "event_sequence, event_request_id, event_id, event_digest, " + + "caller_bound_authority_invalidated, event_payload FROM " + + MEMBERS + + " WHERE request_id = ? ORDER BY account_uuid", + requestId)) { + members.add( + new AccountTenantRoleMutationDigest.MemberResult( + row.get("account_uuid", UUID.class), + row.get("tenant_uuid", UUID.class), + requiredPositive(row, "membership_version"), + requiredPositive(row, "membership_authority_generation"), + requiredPositive(row, "event_sequence"), + requiredText(row, "event_request_id"), + requiredText(row, "event_id"), + requiredText(row, "event_digest"), + Boolean.TRUE.equals(row.get("caller_bound_authority_invalidated", Boolean.class)), + requiredBytes(row, "event_payload"))); + } + return List.copyOf(members); + } + + private static void requireResultShape( + Request request, List members) { + int expectedCount = request.action() == Action.TRANSFER_TENANT_ADMIN ? 2 : 1; + if (members.size() != expectedCount) { + throw new IllegalStateException("Tenant-role operation member result count differs"); + } + for (AccountTenantRoleMutationDigest.MemberResult member : members) { + if (!request.tenantUuid().equals(member.tenantUuid())) { + throw new IllegalStateException("Tenant-role member result belongs to another tenant"); + } + String expectedRequestId = eventRequestId(request.requestId(), member.accountUuid()); + if (!expectedRequestId.equals(member.eventRequestId())) { + throw new IllegalStateException("Tenant-role member event request ID differs"); + } + boolean actorMember = member.accountUuid().equals(request.actorAccountUuid()); + boolean targetMember = member.accountUuid().equals(request.targetAccountUuid()); + if ((!actorMember && !targetMember) + || (request.action() == Action.TRANSFER_TENANT_ADMIN + && (member.callerBoundAuthorityInvalidated() != actorMember)) + || (request.action() == Action.GRANT_DESIGNER && member.callerBoundAuthorityInvalidated()) + || (request.action() == Action.REVOKE_DESIGNER + && !member.callerBoundAuthorityInvalidated())) { + throw new IllegalStateException( + "Tenant-role member invalidation or identity differs from action"); + } + long expectedVersion = + increment( + actorMember + ? request.expectedActorMembershipVersion() + : request.expectedTargetMembershipVersion()); + if (member.membershipVersion() != expectedVersion) { + throw new IllegalStateException( + "Tenant-role membership version did not advance exactly once"); + } + requireExactEvent(request, member); + } + if (request.action() != Action.TRANSFER_TENANT_ADMIN + && !members.getFirst().accountUuid().equals(request.targetAccountUuid())) { + throw new IllegalStateException("Designer operation must change only its target membership"); + } + } + + private static void requireExactEvent( + Request request, AccountTenantRoleMutationDigest.MemberResult member) { + String expectedRequestId = eventRequestId(request.requestId(), member.accountUuid()); + String expectedEventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + expectedRequestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + MembershipAuthorityEventV1Codec.MembershipEvent event; + try { + event = + MembershipAuthorityEventV1Codec.verify( + new String(member.eventPayload(), StandardCharsets.UTF_8)); + } catch (RuntimeException malformed) { + throw new IllegalStateException("Tenant-role journal member event is malformed", malformed); + } + if (!expectedRequestId.equals(member.eventRequestId()) + || !expectedEventId.equals(member.eventId()) + || !eventStreamKey(member.accountUuid(), request.tenantUuid()) + .equals(event.outboxStreamKey()) + || !expectedRequestId.equals(event.requestId()) + || !expectedEventId.equals(event.eventId()) + || !member.eventDigest().equals(event.eventDigest()) + || !Long.toString(member.eventSequence()).equals(event.outboxSequence()) + || !member.accountUuid().toString().equals(event.accountId()) + || !request.tenantUuid().toString().equals(event.tenantId()) + || !Map.of(request.tenantUuid().toString(), Long.toString(member.membershipVersion())) + .equals(event.membershipVersion()) + || !Long.toString(member.membershipAuthorityGeneration()) + .equals(event.membershipAuthorityGeneration()) + || member.callerBoundAuthorityInvalidated() != event.callerBoundAuthorityInvalidated() + || !"ACTIVE".equals(event.membershipLifecycleState()) + || !event.gameplayAdmissionAllowed() + || !event.roles().contains("player")) { + throw new IllegalStateException( + "Tenant-role journal member event differs from result identity"); + } + } + + private static long increment(long value) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException( + "Tenant-role expected membership version is exhausted", overflow); + } + } + + private static void requireExactCompletedResult( + Request request, + String requestDigest, + byte[] resultPayload, + String resultDigest, + AuditEvidence audit, + List members, + OperationEvidence actual) { + if (!request.equals(actual.request()) + || !requestDigest.equals(actual.requestDigest()) + || !"COMMITTED".equals(actual.status()) + || !Arrays.equals(resultPayload, actual.resultPayload()) + || !resultDigest.equals(actual.resultDigest()) + || !auditEquals(audit, actual.audit()) + || !membersEqual(members, actual.members())) { + throw new IllegalStateException("Tenant-role result readback differs from its exact commit"); + } + } + + private static boolean auditEquals(AuditEvidence expected, AuditEvidence actual) { + return actual != null + && expected.auditEventId().equals(actual.auditEventId()) + && expected.eventType().equals(actual.eventType()) + && expected.occurredAt().equals(actual.occurredAt()) + && expected.payloadDigest().equals(actual.payloadDigest()) + && Arrays.equals(expected.payload(), actual.payload()); + } + + private static boolean membersEqual( + List expected, + List actual) { + if (expected.size() != actual.size()) { + return false; + } + for (int index = 0; index < expected.size(); index++) { + AccountTenantRoleMutationDigest.MemberResult left = expected.get(index); + AccountTenantRoleMutationDigest.MemberResult right = actual.get(index); + if (!left.accountUuid().equals(right.accountUuid()) + || !left.tenantUuid().equals(right.tenantUuid()) + || left.membershipVersion() != right.membershipVersion() + || left.membershipAuthorityGeneration() != right.membershipAuthorityGeneration() + || left.eventSequence() != right.eventSequence() + || !left.eventRequestId().equals(right.eventRequestId()) + || !left.eventId().equals(right.eventId()) + || !left.eventDigest().equals(right.eventDigest()) + || left.callerBoundAuthorityInvalidated() != right.callerBoundAuthorityInvalidated() + || !Arrays.equals(left.eventPayload(), right.eventPayload())) { + return false; + } + } + return true; + } + + private static long requiredPositive(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant-role " + name + " is malformed"); + } + return value; + } + + private static String requiredText(Record row, String name) { + String value = row.get(name, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Tenant-role " + name + " is missing"); + } + return value; + } + + private static byte[] requiredBytes(Record row, String name) { + byte[] value = row.get(name, byte[].class); + if (value == null) { + throw new IllegalStateException("Tenant-role " + name + " is missing"); + } + return value; + } + + private static Instant requiredInstant(Record row, String name) { + Object value = row.get(name); + if (value instanceof Instant instant) { + return instant; + } + if (value instanceof java.time.OffsetDateTime offsetDateTime) { + return offsetDateTime.toInstant(); + } + throw new IllegalStateException("Tenant-role " + name + " is malformed"); + } + + private void requireWriteOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Tenant-role operation access requires an active Account write transaction"); + } + } + + public static String eventRequestId(UUID requestId, UUID accountUuid) { + if (requestId == null || accountUuid == null) { + throw new IllegalArgumentException("Tenant-role event request identity is required"); + } + return "tenant-role:" + requestId + ":" + accountUuid; + } + + public static String eventStreamKey(UUID accountUuid, UUID tenantUuid) { + if (accountUuid == null || tenantUuid == null) { + throw new IllegalArgumentException("Tenant-role event stream identity is required"); + } + return "account:auth-authority:v1:membership/" + accountUuid + "/" + tenantUuid; + } + + public record Request( + UUID requestId, + UUID actorAccountUuid, + UUID tenantUuid, + UUID targetAccountUuid, + Action action, + long expectedActorMembershipVersion, + long expectedTargetMembershipVersion) { + public Request { + requireCanonical(requestId, "request ID"); + requireCanonical(actorAccountUuid, "actor Account UUID"); + requireCanonical(tenantUuid, "tenant UUID"); + requireCanonical(targetAccountUuid, "target Account UUID"); + Objects.requireNonNull(action, "tenant-role action is required"); + if (expectedActorMembershipVersion <= 0 || expectedTargetMembershipVersion <= 0) { + throw new IllegalArgumentException("Expected membership versions must be positive"); + } + if (action == Action.TRANSFER_TENANT_ADMIN && actorAccountUuid.equals(targetAccountUuid)) { + throw new IllegalArgumentException("Tenant-admin transfer requires distinct members"); + } + if (actorAccountUuid.equals(targetAccountUuid) + && expectedActorMembershipVersion != expectedTargetMembershipVersion) { + throw new IllegalArgumentException("Self-targeted role request versions must match"); + } + } + + public byte[] payload() { + return AccountTenantRoleMutationDigest.requestBytes( + requestId, + actorAccountUuid, + tenantUuid, + targetAccountUuid, + action.name(), + expectedActorMembershipVersion, + expectedTargetMembershipVersion); + } + + private static void requireCanonical(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + } + + public enum Action { + GRANT_DESIGNER, + REVOKE_DESIGNER, + TRANSFER_TENANT_ADMIN; + + private static Action parse(String value) { + try { + return Action.valueOf(value); + } catch (RuntimeException malformed) { + throw new IllegalStateException("Tenant-role action is unsupported", malformed); + } + } + } + + public record AuditEvidence( + UUID auditEventId, + String eventType, + Instant occurredAt, + String payloadDigest, + byte[] payload) { + public AuditEvidence { + Objects.requireNonNull(auditEventId, "audit event ID is required"); + Objects.requireNonNull(eventType, "audit event type is required"); + Objects.requireNonNull(occurredAt, "audit occurrence time is required"); + Objects.requireNonNull(payloadDigest, "audit payload digest is required"); + Objects.requireNonNull(payload, "audit payload is required"); + payload = payload.clone(); + if (!AUDIT_EVENT_TYPE.equals(eventType) + || !payloadDigest.matches("sha256:[0-9a-f]{64}") + || !payloadDigest.equals( + net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload( + new String(payload, StandardCharsets.UTF_8)))) { + throw new IllegalArgumentException("Tenant-role audit evidence digest or type is invalid"); + } + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + public record OperationEvidence( + Request request, + byte[] requestPayload, + String requestDigest, + String status, + AuditEvidence audit, + byte[] resultPayload, + String resultDigest, + List members) { + public OperationEvidence { + requestPayload = requestPayload.clone(); + resultPayload = resultPayload == null ? null : resultPayload.clone(); + members = List.copyOf(members); + } + + @Override + public byte[] requestPayload() { + return requestPayload.clone(); + } + + @Override + public byte[] resultPayload() { + return resultPayload == null ? null : resultPayload.clone(); + } + } + + public record Claim(boolean claimed, Optional replay) { + public Claim { + replay = Objects.requireNonNull(replay, "replay evidence presence is required"); + if (claimed == replay.isPresent()) { + throw new IllegalArgumentException("Tenant-role claim result has contradictory state"); + } + } + } + + public record CurrentMemberEvidence( + OperationEvidence operation, AccountTenantRoleMutationDigest.MemberResult member) {} + + public static final class OperationConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 74964db5bb..2df0e781c6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -13,6 +13,7 @@ import java.util.Optional; import java.util.UUID; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; @@ -22,6 +23,7 @@ import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; @@ -48,6 +50,12 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.AuditEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.CurrentMemberEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.OperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Request; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -88,6 +96,8 @@ public class AccountMembershipAuthorityEventProducer { private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; private final AccountTenantMembershipRepository membershipRepository; private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountTenantRoleOperationRepository tenantRoleOperationRepository; public AccountMembershipAuthorityEventProducer( AccountJoinOperationRepository joinOperationRepository, @@ -101,7 +111,9 @@ public AccountMembershipAuthorityEventProducer( AccountLogoutAllOperationRepository logoutAllOperationRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountTenantMembershipRepository membershipRepository, - AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository) { + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, + AccountAuditOutboxRepository auditOutboxRepository, + AccountTenantRoleOperationRepository tenantRoleOperationRepository) { this.joinOperationRepository = joinOperationRepository; this.pairAuthorityRepository = pairAuthorityRepository; this.accountRepository = accountRepository; @@ -117,6 +129,8 @@ public AccountMembershipAuthorityEventProducer( this.transitionReceiptRepository = transitionReceiptRepository; this.membershipRepository = membershipRepository; this.roleSnapshotRepository = roleSnapshotRepository; + this.auditOutboxRepository = auditOutboxRepository; + this.tenantRoleOperationRepository = tenantRoleOperationRepository; } /** @@ -233,10 +247,24 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( "Current Account membership checkpoint differs from its event"); } MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); + Optional tenantRoleEvidence = Optional.empty(); if (!transitionReceipt.requestId().equals(verified.requestId())) { - throw new IllegalStateException( - "Current Account membership receipt differs from its latest V33 event"); - } + tenantRoleEvidence = + Optional.of( + tenantRoleOperationRepository + .findCurrentMemberEvidenceForUpdate( + identity.accountUuid(), identity.tenantUuid(), verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership event lacks its exact tenant-role operation"))); + requireExactCurrentTenantRoleEvidence( + tenantRoleEvidence.orElseThrow(), membership, roles, event, verified, identity); + } + boolean currentTransitionInvalidated = + tenantRoleEvidence + .map(evidence -> evidence.member().callerBoundAuthorityInvalidated()) + .orElse("MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType())); requireCurrentMembershipEvent( identity, membership.membershipId(), @@ -246,8 +274,8 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( membership.membershipAuthorityGeneration(), membership.authorityProvenance(), roles, - transitionReceipt.requestId(), - "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()), + tenantRoleEvidence.isPresent() ? null : transitionReceipt.requestId(), + currentTransitionInvalidated, authoritySnapshot); List checkpoints = new ArrayList<>(currentSources.checkpoints()); @@ -275,7 +303,257 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( checkpoints, sourceEvidence, transitionReceipt, - verified); + verified, + tenantRoleEvidence.map(CurrentMemberEvidence::operation)); + } + + private void requireExactCurrentTenantRoleEvidence( + CurrentMemberEvidence evidence, + JoinMembershipProof membership, + RoleSnapshot roles, + Event event, + MembershipEvent verified, + Identity identity) { + OperationEvidence operation = evidence.operation(); + AccountTenantRoleMutationDigest.MemberResult member = evidence.member(); + Request request = operation.request(); + if (!"COMMITTED".equals(operation.status()) + || !identity.tenantUuid().equals(request.tenantUuid()) + || !identity.accountUuid().equals(member.accountUuid()) + || !identity.tenantUuid().equals(member.tenantUuid()) + || member.membershipVersion() != membership.membershipVersion() + || member.membershipAuthorityGeneration() != membership.membershipAuthorityGeneration() + || member.eventSequence() != event.outboxSequence() + || !member.eventRequestId().equals(event.requestId()) + || !member.eventId().equals(event.eventId()) + || !member.eventDigest().equals(event.eventDigest()) + || !Arrays.equals(member.eventPayload(), event.payload()) + || member.callerBoundAuthorityInvalidated() != verified.callerBoundAuthorityInvalidated() + || !List.of("GRANT_DESIGNER", "REVOKE_DESIGNER", "TRANSFER_TENANT_ADMIN") + .contains(request.action().name()) + || !"ACTIVE".equals(membership.lifecycleState()) + || !membership.gameplayAdmissionAllowed() + || !verified.roles().equals(roles.roles())) { + throw new IllegalStateException( + "Current Account membership differs from its exact tenant-role journal evidence"); + } + AuditEvidence audit = + Objects.requireNonNull( + operation.audit(), "Committed tenant-role audit evidence is required"); + String payload = new String(audit.payload(), StandardCharsets.UTF_8); + AccountAuditEnvelope envelope = + auditOutboxRepository + .findCanonicalTenantRoleEnvelopeForUpdate( + audit.auditEventId(), + identity.tenantUuid(), + audit.occurredAt(), + audit.payloadDigest(), + payload) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account tenant-role operation audit envelope is absent")); + if (!Arrays.equals(audit.payload(), envelope.payload().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException("Current tenant-role audit payload bytes differ"); + } + } + + /** + * Appends one exact role-only transition to an existing retained explicit-join membership. This + * is an owner-source primitive, not an authenticated ingress or an authorization API. + */ + @Transactional(propagation = Propagation.MANDATORY) + public TenantRoleEventEvidence appendTenantRoleEvent( + Request request, + AccountTenantMembership membership, + RoleSnapshot roles, + PairAuthority priorPair, + boolean callerBoundAuthorityInvalidated) { + requireWritableOwnerTransaction(); + if (request == null + || membership == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getAccount().getAccountUuid() == null + || membership.getId() == null + || roles == null + || priorPair == null + || !priorPair.membershipExists() + || priorPair.lastEventSequence() <= 0L + || !request.tenantUuid().equals(membership.getTenantUuid()) + || !request.tenantUuid().equals(priorPair.tenantUuid()) + || !membership.getAccount().getAccountUuid().equals(priorPair.accountUuid()) + || membership.getMembershipVersion() <= 0L + || membership.getMembershipAuthorityGeneration() <= 0L + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalArgumentException( + "Role mutation event requires an existing active explicit-join membership"); + } + VerifiedTenantProvenance provenance = membershipProvenance(membership); + if (provenance.kind() != TenantProvenanceKind.APPROVED_RETAINED + || !provenance.equals(priorPair.provenance()) + || roles.accountId() != membership.getAccount().getId() + || roles.membershipId() != membership.getId() + || roles.snapshotVersion() != membership.getMembershipVersion() + || !Objects.equals(roles.tenantId(), membership.getTenantId()) + || !request.tenantUuid().equals(roles.tenantUuid()) + || !provenance.equals(roles.tenantProvenance())) { + throw new IllegalStateException( + "Role mutation event source differs from its retained membership and pair"); + } + List exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + if (!exactRoles.contains("player")) { + throw new IllegalStateException( + "Role mutation cannot remove the explicit membership player role"); + } + + UUID accountUuid = membership.getAccount().getAccountUuid(); + Identity identity = + new Identity( + membership.getAccount().getId(), + membership.getTenantId(), + accountUuid, + request.tenantUuid(), + provenance); + CompositeSnapshot current = readSnapshot(identity); + ScopeState memberState = only(current.memberships(), "membership"); + requireMatchingFence(current, memberState, accountUuid); + if (memberState.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Role mutation member generation differs from its current Account source"); + } + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence(accountUuid, request.tenantUuid(), current); + String streamKey = membershipStreamKey(identity); + String eventRequestId = + AccountTenantRoleOperationRepository.eventRequestId(request.requestId(), accountUuid); + String eventId = eventIdForRequest(eventRequestId); + MembershipEvent[] candidate = new MembershipEvent[1]; + Event appended = + authorityOutboxRepository.append( + streamKey, + eventRequestId, + sequence -> { + MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + preimage( + identity, + eventRequestId, + eventId, + streamKey, + sequence, + current.issuer(), + current.account(), + only(current.tenants(), "tenant"), + memberState, + current.issuanceFence().value(), + currentSources.accountSecurityCutoff(), + membership, + exactRoles, + callerBoundAuthorityInvalidated)); + candidate[0] = event; + return new EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + MembershipEvent expected = candidate[0]; + long expectedSequence = + incrementCounter(priorPair.lastEventSequence(), "membership event sequence"); + if (expected == null + || appended.outboxSequence() != expectedSequence + || !appended.outboxStreamKey().equals(streamKey) + || !appended.requestId().equals(eventRequestId) + || !appended.eventId().equals(expected.eventId()) + || !appended.eventDigest().equals(expected.eventDigest()) + || !Arrays.equals(appended.payload(), expected.canonicalJsonUtf8())) { + throw new IllegalStateException("Tenant-role event append differs from its exact candidate"); + } + Event exactEvent = + authorityOutboxRepository + .findEvent(streamKey, eventRequestId) + .orElseThrow(() -> new IllegalStateException("Tenant-role event readback is absent")); + if (!appended.equals(exactEvent)) { + throw new IllegalStateException("Tenant-role event readback differs from its append"); + } + MembershipEvent verified = verifyStoredEvent(exactEvent, identity, eventRequestId); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow(() -> new IllegalStateException("Tenant-role event checkpoint is absent")); + if (!checkpointMatches(checkpoint, exactEvent) + || !verified.canonicalJson().equals(expected.canonicalJson()) + || !verified.roles().equals(exactRoles) + || !Long.toString(membership.getMembershipVersion()) + .equals( + membershipVersionValue( + verified.membershipVersion(), request.tenantUuid().toString())) + || verified.callerBoundAuthorityInvalidated() != callerBoundAuthorityInvalidated) { + throw new IllegalStateException("Tenant-role event codec or checkpoint readback differs"); + } + return new TenantRoleEventEvidence(checkpoint, exactEvent, verified); + } + + /** + * Verifies original event bytes for an immutable operation retry, even after later transitions. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Event readExactTenantRoleEvent( + Request request, AccountTenantRoleMutationDigest.MemberResult expected) { + requireActiveOwnerTransaction(); + Objects.requireNonNull(request, "Tenant-role request is required"); + Objects.requireNonNull(expected, "Tenant-role event result is required"); + String eventRequestId = + AccountTenantRoleOperationRepository.eventRequestId( + request.requestId(), expected.accountUuid()); + if (!request.tenantUuid().equals(expected.tenantUuid()) + || !eventRequestId.equals(expected.eventRequestId())) { + throw new IllegalStateException( + "Tenant-role immutable event identity differs from its request"); + } + String streamKey = + AccountTenantRoleOperationRepository.eventStreamKey( + expected.accountUuid(), expected.tenantUuid()); + Event exact = + authorityOutboxRepository + .findEvent(streamKey, eventRequestId) + .orElseThrow( + () -> + new IllegalStateException( + "Original tenant-role event is absent from Account outbox")); + MembershipEvent verified; + try { + verified = + MembershipAuthorityEventV1Codec.verify( + new String(exact.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException malformed) { + throw new IllegalStateException( + "Original tenant-role event bytes are not canonical", malformed); + } + if (!exact.outboxStreamKey().equals(streamKey) + || !exact.requestId().equals(eventRequestId) + || exact.outboxSequence() != expected.eventSequence() + || !exact.eventId().equals(expected.eventId()) + || !exact.eventDigest().equals(expected.eventDigest()) + || !Arrays.equals(exact.payload(), expected.eventPayload()) + || !verified.accountId().equals(expected.accountUuid().toString()) + || !verified.tenantId().equals(expected.tenantUuid().toString()) + || !verified.requestId().equals(eventRequestId) + || !verified + .membershipVersion() + .equals( + Map.of( + expected.tenantUuid().toString(), Long.toString(expected.membershipVersion()))) + || !verified + .membershipAuthorityGeneration() + .equals(Long.toString(expected.membershipAuthorityGeneration())) + || verified.callerBoundAuthorityInvalidated() + != expected.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Original tenant-role event differs from immutable result bytes"); + } + return exact; } /** @@ -2907,6 +3185,26 @@ private VerifiedTenantProvenance verifiedProvenance(Identity identity) { return identity.provenance(); } + private VerifiedTenantProvenance membershipProvenance(AccountTenantMembership membership) { + try { + return new VerifiedTenantProvenance( + membership.getTenantId(), + TenantProvenanceKind.valueOf(membership.getTenantProvenanceKind()), + membership.getTenantSourceOperationId(), + membership.getTenantProvenanceDigest()); + } catch (RuntimeException malformed) { + throw new IllegalStateException("Membership tenant provenance is malformed", malformed); + } + } + + private static long incrementCounter(long value, String label) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account " + label + " is exhausted", overflow); + } + } + private void requireRoleSnapshotIdentity( Identity identity, AccountTenantMembership membership, @@ -3112,6 +3410,22 @@ public record OutboxSourceEvidence( } } + /** Exact append result returned to the role-operation transaction before pair commit. */ + public record TenantRoleEventEvidence( + Checkpoint checkpoint, Event event, MembershipEvent verifiedEvent) { + public TenantRoleEventEvidence { + Objects.requireNonNull(checkpoint, "tenant-role event checkpoint is required"); + Objects.requireNonNull(event, "tenant-role event is required"); + Objects.requireNonNull(verifiedEvent, "verified tenant-role event is required"); + if (!checkpointMatches(checkpoint, event) + || !event.eventId().equals(verifiedEvent.eventId()) + || !event.eventDigest().equals(verifiedEvent.eventDigest()) + || !event.requestId().equals(verifiedEvent.requestId())) { + throw new IllegalArgumentException("Tenant-role event evidence is inconsistent"); + } + } + } + /** * Local V36 absence evidence with an exact one-tenant membership-version map. The sequence-zero * checkpoints carry no source event identity or digest and never authorize gameplay. @@ -3231,7 +3545,8 @@ public record PositiveMembershipSnapshot( List outboxCheckpoints, List outboxSourceEvidence, MembershipTransitionReceipt transitionReceipt, - MembershipEvent authorityEvent) { + MembershipEvent authorityEvent, + Optional tenantRoleOperationEvidence) { public PositiveMembershipSnapshot { accountId = requireCanonicalUuid(accountId, "canonical Account UUID"); tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID"); @@ -3252,6 +3567,35 @@ public record PositiveMembershipSnapshot( outboxSourceEvidence = List.copyOf(outboxSourceEvidence); Objects.requireNonNull(transitionReceipt, "membership transition receipt is required"); Objects.requireNonNull(authorityEvent, "canonical membership authority event is required"); + tenantRoleOperationEvidence = + Objects.requireNonNull( + tenantRoleOperationEvidence, "tenant-role operation evidence presence is required"); + boolean lifecycleEventMatches = + transitionReceipt.requestId().equals(authorityEvent.requestId()); + String canonicalAccountId = accountId; + String canonicalTenantId = tenantId; + String currentMembershipVersion = membershipVersion.get(tenantId); + String currentMembershipAuthorityGeneration = membershipAuthorityGeneration; + boolean roleEventMatches = + tenantRoleOperationEvidence + .map( + operation -> + operation.members().stream() + .anyMatch( + member -> + member.accountUuid().toString().equals(canonicalAccountId) + && member.tenantUuid().toString().equals(canonicalTenantId) + && member.eventRequestId().equals(authorityEvent.requestId()) + && Long.toString(member.membershipVersion()) + .equals(currentMembershipVersion) + && Long.toString(member.membershipAuthorityGeneration()) + .equals(currentMembershipAuthorityGeneration) + && member.eventId().equals(authorityEvent.eventId()) + && member.eventDigest().equals(authorityEvent.eventDigest()) + && Arrays.equals( + member.eventPayload(), + authorityEvent.canonicalJsonUtf8()))) + .orElse(false); if (!membershipExists || !"ACTIVE".equals(membershipLifecycleState) @@ -3268,7 +3612,8 @@ public record PositiveMembershipSnapshot( .equals(authorityTuple.membershipAuthorityGeneration()) || !authorityTuple.privateRealmGrantVersions().isEmpty() || authorityTuple.tenantBillingCutoff().isPresent() - || !transitionReceipt.requestId().equals(authorityEvent.requestId())) { + || lifecycleEventMatches == tenantRoleOperationEvidence.isPresent() + || (tenantRoleOperationEvidence.isPresent() && !roleEventMatches)) { throw new IllegalArgumentException( "Positive Account membership snapshot evidence is internally inconsistent"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java new file mode 100644 index 0000000000..ba68af972f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantRoleMutationService.java @@ -0,0 +1,522 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Action; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.AuditEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.OperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Request; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.TenantRoleEventEvidence; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicitly unwired Account owner-source writer for retained, currently admitting EXPLICIT_JOIN + * members. Its actor UUID selects an Account row; this service does not authenticate a caller. + */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and producer are internal transaction collaborators.") +public class AccountTenantRoleMutationService { + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); + + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountTenantRoleOperationRepository operationRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountMembershipAuthorityEventProducer eventProducer; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor validates injected internal collaborators; it neither publishes this " + + "nor invokes overridable methods.") + public AccountTenantRoleMutationService( + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, + AccountMembershipPairAuthorityRepository pairAuthorityRepository, + AccountTenantRoleOperationRepository operationRepository, + AccountAuditOutboxRepository auditOutboxRepository, + AccountMembershipAuthorityEventProducer eventProducer) { + this.accountRepository = Objects.requireNonNull(accountRepository); + this.tenantIdentityResolver = Objects.requireNonNull(tenantIdentityResolver); + this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); + this.membershipRepository = Objects.requireNonNull(membershipRepository); + this.roleSnapshotRepository = Objects.requireNonNull(roleSnapshotRepository); + this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); + this.operationRepository = Objects.requireNonNull(operationRepository); + this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository); + this.eventProducer = Objects.requireNonNull(eventProducer); + } + + /** + * Applies one role-source mutation inside a single Account write transaction. No transport or + * authenticated actor proof is accepted here; public Account/runtime ingress remains denied. + */ + @Transactional + public OperationEvidence mutate(Request request) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(request, "Tenant-role mutation request is required"); + + List orderedAccountUuids = + new LinkedHashSet<>(List.of(request.actorAccountUuid(), request.targetAccountUuid())) + .stream().sorted(Comparator.comparing(UUID::toString)).toList(); + Map lockedAccounts = new LinkedHashMap<>(); + for (UUID accountUuid : orderedAccountUuids) { + Account account = + accountRepository + .findByAccountUuidForUpdate(accountUuid) + .orElseThrow(() -> new IllegalStateException("Tenant-role Account row is absent")); + requireAccountIdentity(account, accountUuid); + lockedAccounts.put(accountUuid, account); + } + + AccountTenantRoleOperationRepository.Claim claim = operationRepository.claim(request); + if (!claim.claimed()) { + OperationEvidence replay = claim.replay().orElseThrow(); + verifyExactReplay(replay); + return replay; + } + + // The tenant generation row is the shared-source serialization point for same-tenant writes. + for (UUID accountUuid : orderedAccountUuids) { + authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + accountUuid, + List.of(request.tenantUuid()), + List.of()); + } + ApprovedAssociation association = tenantIdentityResolver.resolve(request.tenantUuid()); + VerifiedTenantProvenance expectedProvenance = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + + Map current = new LinkedHashMap<>(); + for (UUID accountUuid : orderedAccountUuids) { + Account account = lockedAccounts.get(accountUuid); + PositiveMembershipSnapshot snapshot = + eventProducer.readCurrentPairBoundPositiveMembershipSnapshot( + account.getId(), association.legacyTenantId()); + if (!accountUuid.toString().equals(snapshot.accountId()) + || !request.tenantUuid().toString().equals(snapshot.tenantId())) { + throw new IllegalStateException("Tenant-role current membership identity differs"); + } + current.put(accountUuid, snapshot); + } + PositiveMembershipSnapshot actorSnapshot = current.get(request.actorAccountUuid()); + PositiveMembershipSnapshot targetSnapshot = current.get(request.targetAccountUuid()); + requireExpectedVersion(request.expectedActorMembershipVersion(), actorSnapshot, "actor"); + requireExpectedVersion(request.expectedTargetMembershipVersion(), targetSnapshot, "target"); + if (!actorSnapshot.roles().contains("tenantAdmin")) { + throw new IllegalStateException( + "Current retained Account actor is not a tenant administrator"); + } + + Map changes = roleChanges(request, actorSnapshot, targetSnapshot); + List orderedChanges = + changes.values().stream() + .sorted(Comparator.comparing(change -> change.accountUuid().toString())) + .toList(); + + List memberResults = new ArrayList<>(); + for (RoleChange change : orderedChanges) { + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(change.accountUuid(), request.tenantUuid()) + .orElseThrow( + () -> + new IllegalStateException("Current canonical Account membership is absent")); + requireRetainedExplicitMembership(membership, expectedProvenance, change.current()); + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(change.accountUuid(), request.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Current membership pair authority is absent")); + requireCurrentPair(pair, membership, change.current(), expectedProvenance); + + RoleSnapshot priorRoles = + roleSnapshotRepository + .findForCanonicalUpdate( + change.accountUuid(), + request.tenantUuid(), + expectedProvenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Current canonical role snapshot is absent")); + if (!priorRoles.roles().equals(change.current().roles())) { + throw new IllegalStateException("Tenant-role current role source differs from its event"); + } + + CompositeSnapshot authority = + authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + change.accountUuid(), + List.of(request.tenantUuid()), + List.of(request.tenantUuid())); + ScopeState memberState = authority.memberships().getFirst(); + if (!AuthorityScope.membership(change.accountUuid(), request.tenantUuid()) + .equals(memberState.scope()) + || memberState.generation() != membership.getMembershipAuthorityGeneration() + || authority.issuanceFence() == null + || !authority.issuanceFence().accountId().equals(change.accountUuid()) + || authority.issuanceFence().value() + != Long.parseLong(change.current().issuanceFence())) { + throw new IllegalStateException( + "Tenant-role authority generation differs from current source"); + } + if (change.invalidated()) { + increment(authority.issuanceFence().value(), "issuance fence"); + memberState = authorityGenerationRepository.advance(memberState, authority.issuanceFence()); + } + + long nextVersion = increment(membership.getMembershipVersion(), "membership version"); + membership.setMembershipVersion(nextVersion); + membership.setMembershipAuthorityGeneration(memberState.generation()); + AccountTenantMembership persisted = + membershipRepository.saveCanonical( + membership, change.accountUuid(), request.tenantUuid(), expectedProvenance); + RoleSnapshot persistedRoles = + roleSnapshotRepository.replaceCanonical( + persisted, + change.accountUuid(), + request.tenantUuid(), + expectedProvenance, + nextVersion, + change.roles()); + + TenantRoleEventEvidence event = + eventProducer.appendTenantRoleEvent( + request, persisted, persistedRoles, pair, change.invalidated()); + PairAuthority advanced = + pairAuthorityRepository.commitTransition( + pair, + new PairTransition( + true, + event.checkpoint().outboxSequence(), + event.event().eventId(), + event.event().eventDigest(), + change.invalidated())); + if (advanced.membershipVersion() != nextVersion + || advanced.membershipAuthorityGeneration() != memberState.generation() + || advanced.lastEventSequence() != event.checkpoint().outboxSequence()) { + throw new IllegalStateException("Tenant-role pair transition readback differs"); + } + memberResults.add( + new AccountTenantRoleMutationDigest.MemberResult( + change.accountUuid(), + request.tenantUuid(), + persisted.getMembershipVersion(), + persisted.getMembershipAuthorityGeneration(), + event.checkpoint().outboxSequence(), + event.event().requestId(), + event.event().eventId(), + event.event().eventDigest(), + change.invalidated(), + event.event().payload())); + } + + AccountAuditEnvelope auditEnvelope = appendAudit(request, memberResults); + AuditEvidence auditEvidence = + new AuditEvidence( + auditEnvelope.auditEventId(), + auditEnvelope.eventType(), + auditEnvelope.occurredAt(), + auditEnvelope.payloadDigest(), + auditEnvelope.payload().getBytes(StandardCharsets.UTF_8)); + OperationEvidence completed = + operationRepository.complete(request, auditEvidence, memberResults); + + for (RoleChange change : orderedChanges) { + PositiveMembershipSnapshot exact = + eventProducer.readCurrentPairBoundPositiveMembershipSnapshot( + lockedAccounts.get(change.accountUuid()).getId(), association.legacyTenantId()); + AccountTenantRoleMutationDigest.MemberResult result = + memberResults.stream() + .filter(member -> member.accountUuid().equals(change.accountUuid())) + .findFirst() + .orElseThrow(); + long expectedFence = + change.invalidated() + ? increment(Long.parseLong(change.current().issuanceFence()), "issuance fence") + : Long.parseLong(change.current().issuanceFence()); + if (!Objects.equals( + exact.membershipVersion().get(request.tenantUuid().toString()), + Long.toString(result.membershipVersion())) + || !Objects.equals( + exact.membershipAuthorityGeneration(), + Long.toString(result.membershipAuthorityGeneration())) + || !exact.authorityEvent().outboxSequence().equals(Long.toString(result.eventSequence())) + || !exact.authorityEvent().requestId().equals(result.eventRequestId()) + || !exact.authorityEvent().eventId().equals(result.eventId()) + || !exact.authorityEvent().eventDigest().equals(result.eventDigest()) + || exact.authorityEvent().callerBoundAuthorityInvalidated() + != result.callerBoundAuthorityInvalidated() + || !exact.issuanceFence().equals(Long.toString(expectedFence)) + || !exact.roles().equals(change.roles())) { + throw new IllegalStateException("Tenant-role positive current-source readback differs"); + } + } + return completed; + } + + private Map roleChanges( + Request request, PositiveMembershipSnapshot actor, PositiveMembershipSnapshot target) { + Map changes = new LinkedHashMap<>(); + if (request.action() == Action.TRANSFER_TENANT_ADMIN) { + if (!actor.roles().contains("tenantAdmin") || target.roles().contains("tenantAdmin")) { + throw new IllegalStateException("Tenant-admin transfer source or target role is invalid"); + } + changes.put( + request.actorAccountUuid(), + new RoleChange( + request.actorAccountUuid(), actor, without(actor.roles(), "tenantAdmin"), true)); + changes.put( + request.targetAccountUuid(), + new RoleChange( + request.targetAccountUuid(), target, with(target.roles(), "tenantAdmin"), false)); + return changes; + } + + boolean grant = request.action() == Action.GRANT_DESIGNER; + if (target.roles().contains("designer") == grant) { + throw new IllegalStateException("Tenant designer role request does not change current roles"); + } + changes.put( + request.targetAccountUuid(), + new RoleChange( + request.targetAccountUuid(), + target, + grant ? with(target.roles(), "designer") : without(target.roles(), "designer"), + !grant)); + if (request.targetAccountUuid().equals(request.actorAccountUuid()) && !actor.equals(target)) { + throw new IllegalStateException("Self-targeted role source snapshots differ"); + } + return changes; + } + + private AccountAuditEnvelope appendAudit( + Request request, List members) { + List auditMembers = + members.stream() + .sorted() + .map( + member -> + new AuditMember( + member.accountUuid().toString(), + Long.toString(member.membershipVersion()), + Long.toString(member.membershipAuthorityGeneration()), + Long.toString(member.eventSequence()), + member.eventId(), + member.eventDigest(), + member.callerBoundAuthorityInvalidated())) + .toList(); + final String payload; + try { + payload = + AUDIT_JSON.writeValueAsString( + new AuditPayload( + "account-tenant-role-audit/v1", + request.requestId().toString(), + request.actorAccountUuid().toString(), + request.tenantUuid().toString(), + request.targetAccountUuid().toString(), + request.action().name(), + auditMembers)); + } catch (RuntimeException failure) { + throw new IllegalStateException("Tenant-role audit serialization failed", failure); + } + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-tenant-role-audit/v1:" + request.requestId()) + .getBytes(StandardCharsets.UTF_8)); + return auditOutboxRepository.appendCanonicalTenant( + auditEventId, request.tenantUuid().toString(), "ACCOUNT_TENANT_ROLE_CHANGED", payload); + } + + private void verifyExactReplay(OperationEvidence operation) { + if (!"COMMITTED".equals(operation.status()) || operation.audit() == null) { + throw new IllegalStateException("Tenant-role exact retry lacks committed immutable evidence"); + } + AuditEvidence audit = operation.audit(); + auditOutboxRepository + .findCanonicalTenantRoleEnvelopeForUpdate( + audit.auditEventId(), + operation.request().tenantUuid(), + audit.occurredAt(), + audit.payloadDigest(), + new String(audit.payload(), StandardCharsets.UTF_8)) + .orElseThrow(() -> new IllegalStateException("Tenant-role retry audit envelope is absent")); + for (AccountTenantRoleMutationDigest.MemberResult member : operation.members()) { + var exact = eventProducer.readExactTenantRoleEvent(operation.request(), member); + if (exact.outboxSequence() != member.eventSequence() + || !exact.eventId().equals(member.eventId()) + || !exact.eventDigest().equals(member.eventDigest()) + || !java.util.Arrays.equals(exact.payload(), member.eventPayload())) { + throw new IllegalStateException( + "Tenant-role retry event differs from original immutable bytes"); + } + } + } + + private void requireRetainedExplicitMembership( + AccountTenantMembership membership, + VerifiedTenantProvenance expectedProvenance, + PositiveMembershipSnapshot current) { + VerifiedTenantProvenance stored = + new VerifiedTenantProvenance( + membership.getTenantId(), + TenantProvenanceKind.valueOf(membership.getTenantProvenanceKind()), + membership.getTenantSourceOperationId(), + membership.getTenantProvenanceDigest()); + if (!stored.equals(expectedProvenance) + || stored.kind() != TenantProvenanceKind.APPROVED_RETAINED + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + || membership.getMembershipVersion() + != Long.parseLong( + current.membershipVersion().get(membership.getTenantUuid().toString())) + || membership.getMembershipAuthorityGeneration() + != Long.parseLong(current.membershipAuthorityGeneration())) { + throw new IllegalStateException( + "Tenant-role mutation requires the exact retained active explicit-join membership"); + } + } + + private static void requireCurrentPair( + PairAuthority pair, + AccountTenantMembership membership, + PositiveMembershipSnapshot current, + VerifiedTenantProvenance provenance) { + var event = current.authorityEvent(); + if (!pair.membershipExists() + || !pair.provenance().equals(provenance) + || pair.membershipVersion() != membership.getMembershipVersion() + || pair.membershipAuthorityGeneration() != membership.getMembershipAuthorityGeneration() + || pair.lastEventSequence() != Long.parseLong(event.outboxSequence()) + || !pair.lastEventId().equals(event.eventId()) + || !pair.lastEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException( + "Current tenant-role pair authority differs from membership evidence"); + } + } + + private static void requireExpectedVersion( + long expected, PositiveMembershipSnapshot current, String label) { + long actual = Long.parseLong(current.membershipVersion().get(current.tenantId())); + if (expected != actual) { + throw new AccountTenantRoleOperationRepository.OperationConflictException( + "Tenant-role expected " + label + " membership version is stale"); + } + } + + private static void requireAccountIdentity(Account account, UUID accountUuid) { + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException( + "Canonical tenant-role Account row identity is contradictory"); + } + } + + private static List with(List current, String role) { + Set result = new LinkedHashSet<>(current); + result.add(role); + return AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet(result); + } + + private static List without(List current, String role) { + Set result = new LinkedHashSet<>(current); + result.remove(role); + return AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet(result); + } + + private static long increment(long value, String label) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant-role " + label + " is exhausted", overflow); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Tenant-role mutation requires an active Account write transaction"); + } + } + + private record RoleChange( + UUID accountUuid, + PositiveMembershipSnapshot current, + List roles, + boolean invalidated) {} + + private record AuditPayload( + String schema, + String requestId, + String actorAccountUuid, + String tenantUuid, + String targetAccountUuid, + String action, + List members) {} + + private record AuditMember( + String accountUuid, + String membershipVersion, + String membershipAuthorityGeneration, + String eventSequence, + String eventId, + String eventDigest, + boolean callerBoundAuthorityInvalidated) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V56__account_tenant_role_operations.sql b/services/account-service/src/main/resources/db/migration/V56__account_tenant_role_operations.sql new file mode 100644 index 0000000000..c75a4e6b9b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V56__account_tenant_role_operations.sql @@ -0,0 +1,236 @@ +CREATE TABLE account_tenant_role_operations ( + request_id UUID PRIMARY KEY, + schema_version SMALLINT NOT NULL CHECK (schema_version = 1), + actor_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + tenant_uuid UUID NOT NULL, + target_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + action VARCHAR(32) NOT NULL CHECK ( + action IN ('GRANT_DESIGNER', 'REVOKE_DESIGNER', 'TRANSFER_TENANT_ADMIN')), + expected_actor_membership_version BIGINT NOT NULL CHECK (expected_actor_membership_version > 0), + expected_target_membership_version BIGINT NOT NULL CHECK (expected_target_membership_version > 0), + request_payload BYTEA NOT NULL, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('IN_PROGRESS', 'COMMITTED')), + audit_event_id UUID, + audit_event_type VARCHAR(80), + audit_occurred_at TIMESTAMPTZ, + audit_payload_digest VARCHAR(71), + audit_payload BYTEA, + result_payload BYTEA, + result_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + CONSTRAINT account_tenant_role_transfer_members_are_distinct CHECK ( + action <> 'TRANSFER_TENANT_ADMIN' OR actor_account_uuid <> target_account_uuid), + CONSTRAINT account_tenant_role_operation_completion_shape CHECK ( + (status = 'IN_PROGRESS' AND audit_event_id IS NULL AND audit_event_type IS NULL + AND audit_occurred_at IS NULL AND audit_payload_digest IS NULL + AND audit_payload IS NULL AND result_payload IS NULL AND result_digest IS NULL + AND committed_at IS NULL) + OR (status = 'COMMITTED' AND audit_event_id IS NOT NULL + AND audit_event_type IS NOT NULL + AND audit_event_type = 'ACCOUNT_TENANT_ROLE_CHANGED' + AND audit_occurred_at IS NOT NULL + AND audit_payload_digest IS NOT NULL + AND audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND audit_payload IS NOT NULL AND result_payload IS NOT NULL + AND result_digest IS NOT NULL + AND result_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL)) +); + +CREATE TABLE account_tenant_role_operation_members ( + request_id UUID NOT NULL REFERENCES account_tenant_role_operations (request_id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + tenant_uuid UUID NOT NULL, + membership_version BIGINT NOT NULL CHECK (membership_version > 0), + membership_authority_generation BIGINT NOT NULL CHECK (membership_authority_generation > 0), + outbox_stream_key VARCHAR(256) NOT NULL, + event_request_id VARCHAR(128) NOT NULL, + event_sequence BIGINT NOT NULL CHECK (event_sequence > 0), + event_id VARCHAR(512) NOT NULL CHECK (length(btrim(event_id)) > 0), + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + caller_bound_authority_invalidated BOOLEAN NOT NULL, + event_payload BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_tenant_role_operation_members_pk PRIMARY KEY (request_id, account_uuid), + CONSTRAINT account_tenant_role_operation_members_event_uq + UNIQUE (outbox_stream_key, event_request_id) +); + +CREATE INDEX account_tenant_role_operation_members_current_event_idx + ON account_tenant_role_operation_members (account_uuid, tenant_uuid, event_request_id); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_role_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.schema_version IS DISTINCT FROM OLD.schema_version + OR NEW.actor_account_uuid IS DISTINCT FROM OLD.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.target_account_uuid IS DISTINCT FROM OLD.target_account_uuid + OR NEW.action IS DISTINCT FROM OLD.action + OR NEW.expected_actor_membership_version IS DISTINCT FROM OLD.expected_actor_membership_version + OR NEW.expected_target_membership_version IS DISTINCT FROM OLD.expected_target_membership_version + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR OLD.status <> 'IN_PROGRESS' + OR NEW.status <> 'COMMITTED' THEN + RAISE EXCEPTION 'Account tenant-role operation request is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_identity_immutable'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_role_operation_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.status <> 'IN_PROGRESS' + OR NEW.audit_event_id IS NOT NULL + OR NEW.audit_event_type IS NOT NULL + OR NEW.audit_occurred_at IS NOT NULL + OR NEW.audit_payload_digest IS NOT NULL + OR NEW.audit_payload IS NOT NULL + OR NEW.result_payload IS NOT NULL + OR NEW.result_digest IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account tenant-role operation must begin with an empty immutable result' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_initial_state'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_role_operation_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account tenant-role operation history cannot be deleted' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_tenant_role_operation_member_no_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account tenant-role member evidence is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_member_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_tenant_role_operation_complete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_operation account_tenant_role_operations%ROWTYPE; + member_count BIGINT; +BEGIN + SELECT * INTO current_operation + FROM account_tenant_role_operations + WHERE request_id = NEW.request_id; + IF current_operation.status <> 'COMMITTED' THEN + RAISE EXCEPTION 'Incomplete Account tenant-role operation cannot commit' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_must_complete'; + END IF; + + SELECT count(*) INTO member_count + FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id; + IF (current_operation.action = 'TRANSFER_TENANT_ADMIN' AND member_count <> 2) + OR (current_operation.action <> 'TRANSFER_TENANT_ADMIN' AND member_count <> 1) THEN + RAISE EXCEPTION 'Account tenant-role operation has an incomplete member result' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_member_result_count'; + END IF; + + IF current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND (NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.actor_account_uuid + AND tenant_uuid = current_operation.tenant_uuid) + OR NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid)) + OR current_operation.action IN ('GRANT_DESIGNER', 'REVOKE_DESIGNER') + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid) THEN + RAISE EXCEPTION 'Account tenant-role operation member identities differ from its request' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_member_identity'; + END IF; + + IF (current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.actor_account_uuid + AND tenant_uuid = current_operation.tenant_uuid + AND caller_bound_authority_invalidated) + OR current_operation.action = 'TRANSFER_TENANT_ADMIN' + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid + AND NOT caller_bound_authority_invalidated) + OR current_operation.action IN ('GRANT_DESIGNER', 'REVOKE_DESIGNER') + AND NOT EXISTS ( + SELECT 1 FROM account_tenant_role_operation_members + WHERE request_id = NEW.request_id + AND account_uuid = current_operation.target_account_uuid + AND tenant_uuid = current_operation.tenant_uuid + AND caller_bound_authority_invalidated = + (current_operation.action = 'REVOKE_DESIGNER'))) THEN + RAISE EXCEPTION 'Account tenant-role operation invalidation evidence differs from action' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_role_operation_invalidation_shape'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_tenant_role_operation_update + BEFORE UPDATE ON account_tenant_role_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_update_guard(); +CREATE TRIGGER account_tenant_role_operation_insert + BEFORE INSERT ON account_tenant_role_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_insert_guard(); +CREATE TRIGGER account_tenant_role_operation_delete + BEFORE DELETE ON account_tenant_role_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_no_delete(); +CREATE TRIGGER account_tenant_role_operation_member_update + BEFORE UPDATE OR DELETE ON account_tenant_role_operation_members + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_member_no_mutation(); +CREATE CONSTRAINT TRIGGER account_tenant_role_operation_complete + AFTER INSERT OR UPDATE ON account_tenant_role_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_complete_guard(); +CREATE CONSTRAINT TRIGGER account_tenant_role_operation_member_complete + AFTER INSERT ON account_tenant_role_operation_members + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_tenant_role_operation_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 d1604078fc..da434d3d57 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 @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -25,6 +27,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; @@ -38,20 +41,42 @@ import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.ProvenPositiveCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Action; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.OperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Request; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot; import net.firedevops.firemud.accountservice.service.AccountMembershipLifecycleService; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantRoleMutationService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.v1.GameplayRealm; @@ -112,11 +137,18 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; - @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @MockitoSpyBean private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; @Autowired private AccountMembershipLifecycleService membershipLifecycleService; - @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private AccountTenantRoleMutationService tenantRoleMutationService; + @MockitoSpyBean private AccountAuthorityOutboxRepository authorityOutboxRepository; @MockitoSpyBean private AccountAuditOutboxRepository auditOutboxRepository; @Autowired private PlatformTransactionManager transactionManager; + @Autowired private AccountRepository accountRepository; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private AccountMembershipPairAuthorityRepository pairAuthorityRepository; + @Autowired private AccountTenantIdentityResolver tenantIdentityResolver; + @Autowired private AccountTenantMembershipRepository membershipRepository; + @Autowired private AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; @Autowired private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; @@ -1459,6 +1491,495 @@ void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { snapshot.authorityEvent().canonicalJson())); } + @Test + void tenantRoleMutationDeniesNonAdminWithoutChangingAnyAccountSource() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + Map sourceBefore = membershipAuthorityReadEvidenceSnapshot(fixture); + long auditCountBefore = countAuditOutboxRows(fixture); + long operationCountBefore = + Objects.requireNonNull( + Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + UUID.nameUUIDFromBytes( + ("tenant-role-denied:" + fixture.requestId()) + .getBytes(StandardCharsets.UTF_8))) + .fetchOne(), + "Expected tenant-role operation count row") + .get(0, Long.class), + "Expected tenant-role operation count value"); + + UUID requestId = + UUID.nameUUIDFromBytes( + ("tenant-role-denied:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new AccountTenantRoleOperationRepository.Request( + requestId, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, + joined.membershipVersion(), + joined.membershipVersion()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a tenant administrator"); + + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); + assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isEqualTo(operationCountBefore); + assertThat(committedRoles(fixture)).containsExactly("player"); + } + + @Test + void tenantRoleMutationRejectsStaleMembershipWithoutChangingAnyAccountSource() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + Map sourceBefore = membershipAuthorityReadEvidenceSnapshot(fixture); + long auditCountBefore = countAuditOutboxRows(fixture); + UUID requestId = + UUID.nameUUIDFromBytes( + ("tenant-role-stale:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new AccountTenantRoleOperationRepository.Request( + requestId, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, + joined.membershipVersion() + 1, + joined.membershipVersion() + 1))) + .isInstanceOf(AccountTenantRoleOperationRepository.OperationConflictException.class) + .hasMessageContaining("membership version is stale"); + + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); + assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isZero(); + assertThat(committedRoles(fixture)).containsExactly("player"); + } + + @Test + void tenantRoleMutationRejectsMissingCurrentMembershipWithoutCreatingEvidence() { + JoinFixture fixture = fixture("active"); + UUID requestId = + UUID.nameUUIDFromBytes( + ("tenant-role-no-current:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + long auditCountBefore = countAuditOutboxRows(fixture); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new AccountTenantRoleOperationRepository.Request( + requestId, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, + 1L, + 1L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account membership row is absent"); + + assertThat(countMemberships(fixture)).isZero(); + assertThat(countMembershipPairAuthorities(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void tenantRoleMutationCommitsGrantRevokeTransferAndReplaysOriginalGrantAfterLaterChange() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + PositiveMembershipSnapshot initialAdmin = + readExistingPairBoundPositiveMembershipSnapshot(fixture.admin()); + PositiveMembershipSnapshot initialTarget = + readExistingPairBoundPositiveMembershipSnapshot(fixture.target()); + assertThat(initialAdmin.roles()).containsExactly("player", "tenantAdmin"); + assertThat(initialTarget.roles()).containsExactly("player"); + assertThat(initialAdmin.membershipVersion().get(fixture.admin().tenantUuid().toString())) + .isEqualTo("2"); + assertThat(initialTarget.membershipVersion().get(fixture.target().tenantUuid().toString())) + .isEqualTo("2"); + + UUID grantRequestId = UUID.randomUUID(); + Request grantRequest = + new Request( + grantRequestId, + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L); + OperationEvidence grant = tenantRoleMutationService.mutate(grantRequest); + assertThat(grant.status()).isEqualTo("COMMITTED"); + assertThat(grant.members()).hasSize(1); + assertCurrentRoleMutationState( + fixture.target(), 3L, 1L, 2L, 1L, List.of("designer", "player"), false); + assertCurrentRoleMutationState( + fixture.admin(), 2L, 1L, 1L, 1L, List.of("player", "tenantAdmin"), false); + + UUID revokeRequestId = UUID.randomUUID(); + OperationEvidence revoke = + tenantRoleMutationService.mutate( + new Request( + revokeRequestId, + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.REVOKE_DESIGNER, + 2L, + 3L)); + assertThat(revoke.status()).isEqualTo("COMMITTED"); + assertCurrentRoleMutationState(fixture.target(), 4L, 2L, 3L, 2L, List.of("player"), true); + assertCurrentRoleMutationState( + fixture.admin(), 2L, 1L, 1L, 1L, List.of("player", "tenantAdmin"), false); + + Map adminBeforeRetry = membershipAuthorityReadEvidenceSnapshot(fixture.admin()); + Map targetBeforeRetry = + membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditCountBeforeRetry = countAuditOutboxRows(fixture.admin()); + OperationEvidence replay = tenantRoleMutationService.mutate(grantRequest); + assertExactTenantRoleOperation(grant, replay); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())) + .isEqualTo(adminBeforeRetry); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())) + .isEqualTo(targetBeforeRetry); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditCountBeforeRetry); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new Request( + grantRequestId, + grantRequest.actorAccountUuid(), + grantRequest.tenantUuid(), + grantRequest.targetAccountUuid(), + Action.REVOKE_DESIGNER, + grantRequest.expectedActorMembershipVersion(), + grantRequest.expectedTargetMembershipVersion()))) + .isInstanceOf(AccountTenantRoleOperationRepository.OperationConflictException.class) + .hasMessageContaining("changed immutable input"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())) + .isEqualTo(adminBeforeRetry); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())) + .isEqualTo(targetBeforeRetry); + + OperationEvidence transfer = + tenantRoleMutationService.mutate( + new Request( + UUID.randomUUID(), + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.TRANSFER_TENANT_ADMIN, + 2L, + 4L)); + assertThat(transfer.status()).isEqualTo("COMMITTED"); + assertThat(transfer.members()).hasSize(2); + assertCurrentRoleMutationState(fixture.admin(), 3L, 2L, 2L, 2L, List.of("player"), true); + assertCurrentRoleMutationState( + fixture.target(), 5L, 2L, 4L, 2L, List.of("player", "tenantAdmin"), false); + assertThat(countTenantRoleOperations(fixture.admin())).isEqualTo(3L); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(3L); + assertThat(authorityGeneration("TENANT", null, null, fixture.admin().tenantUuid())) + .isEqualTo(1L); + } + + @Test + void tenantRoleMutationRollsBackAllSourcesWhenEventAppendFailsAfterWriting() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Map adminBefore = membershipAuthorityReadEvidenceSnapshot(fixture.admin()); + Map targetBefore = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditCountBefore = countAuditOutboxRows(fixture.admin()); + UUID requestId = UUID.randomUUID(); + Request request = + new Request( + requestId, + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L); + + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("injected failure after role event append"); + }) + .when(membershipAuthorityEventProducer) + .appendTenantRoleEvent( + any(Request.class), + any(AccountTenantMembership.class), + any(RoleSnapshot.class), + any(PairAuthority.class), + anyBoolean()); + + assertThatThrownBy(() -> tenantRoleMutationService.mutate(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected failure after role event append"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())).isEqualTo(adminBefore); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(targetBefore); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditCountBefore); + assertThat(countAuthorityMembershipEvents(fixture.target())).isEqualTo(1L); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void tenantRoleMutationRollsBackAllSourcesWhenAuditAppendFailsAfterWriting() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Map adminBefore = membershipAuthorityReadEvidenceSnapshot(fixture.admin()); + Map targetBefore = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditCountBefore = countAuditOutboxRows(fixture.admin()); + UUID requestId = UUID.randomUUID(); + Request request = + new Request( + requestId, + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L); + + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("injected failure after role audit append"); + }) + .when(auditOutboxRepository) + .appendCanonicalTenant(any(UUID.class), anyString(), anyString(), anyString()); + + assertThatThrownBy(() -> tenantRoleMutationService.mutate(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected failure after role audit append"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())).isEqualTo(adminBefore); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(targetBefore); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditCountBefore); + assertThat(countAuthorityMembershipEvents(fixture.target())).isEqualTo(1L); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void tenantRoleMutationRollsBackAllSourcesWhenFinalCurrentReadbackFails() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Map adminBefore = membershipAuthorityReadEvidenceSnapshot(fixture.admin()); + Map targetBefore = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditCountBefore = countAuditOutboxRows(fixture.admin()); + UUID requestId = UUID.randomUUID(); + Request request = + new Request( + requestId, + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L); + AtomicInteger readbackCalls = new AtomicInteger(); + + doAnswer( + invocation -> { + PositiveMembershipSnapshot result = + (PositiveMembershipSnapshot) invocation.callRealMethod(); + if (readbackCalls.incrementAndGet() == 3) { + throw new IllegalStateException("injected failure after role current readback"); + } + return result; + }) + .when(membershipAuthorityEventProducer) + .readCurrentPairBoundPositiveMembershipSnapshot(anyLong(), anyLong()); + + assertThatThrownBy(() -> tenantRoleMutationService.mutate(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected failure after role current readback"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())).isEqualTo(adminBefore); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(targetBefore); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditCountBefore); + assertThat(countAuthorityMembershipEvents(fixture.target())).isEqualTo(1L); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void tenantRoleMutationRejectsWrongTenantWithoutChangingAnyAccountSource() { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Map adminBefore = membershipAuthorityReadEvidenceSnapshot(fixture.admin()); + Map targetBefore = membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditCountBefore = countAuditOutboxRows(fixture.admin()); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new Request( + requestId, + fixture.admin().accountUuid(), + UUID.randomUUID(), + fixture.target().accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L))) + .isInstanceOf(IllegalStateException.class); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.admin())).isEqualTo(adminBefore); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())).isEqualTo(targetBefore); + assertThat(countAuditOutboxRows(fixture.admin())).isEqualTo(auditCountBefore); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSource() { + JoinFixture fixture = fixture("active"); + new TransactionTemplate(transactionManager) + .execute( + status -> { + seedSyntheticRetainedActiveMembership( + fixture, List.of("player", "tenantAdmin"), "SEEDED_DEMO"); + return null; + }); + Map sourceBefore = membershipAuthorityReadEvidenceSnapshot(fixture); + long auditCountBefore = countAuditOutboxRows(fixture); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new Request( + requestId, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + Action.GRANT_DESIGNER, + 2L, + 2L))) + .isInstanceOf(IllegalStateException.class); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); + assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void invalidatingTenantRoleMutationDeniesFenceOverflowWithoutChangingAnyAccountSource() { + JoinFixture fixture = fixture("active"); + new TransactionTemplate(transactionManager) + .execute( + status -> { + seedSyntheticRetainedActiveMembership( + fixture, List.of("designer", "player", "tenantAdmin"), "EXPLICIT_JOIN", true); + return null; + }); + PositiveMembershipSnapshot current = readExistingPairBoundPositiveMembershipSnapshot(fixture); + assertThat(current.issuanceFence()).isEqualTo(Long.toString(Long.MAX_VALUE)); + Map sourceBefore = membershipAuthorityReadEvidenceSnapshot(fixture); + long auditCountBefore = countAuditOutboxRows(fixture); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + tenantRoleMutationService.mutate( + new Request( + requestId, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + Action.REVOKE_DESIGNER, + 2L, + 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("issuance fence is exhausted"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); + assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); + assertTenantRoleOperationAbsent(requestId); + } + + @Test + void concurrentOpposingTenantAdminTransfersLeaveOneCurrentAdministrator() throws Exception { + TenantRoleFixture fixture = syntheticRetainedAdminFixture(); + Request currentAdminTransfer = + new Request( + UUID.randomUUID(), + fixture.admin().accountUuid(), + fixture.admin().tenantUuid(), + fixture.target().accountUuid(), + Action.TRANSFER_TENANT_ADMIN, + 2L, + 2L); + Request nonAdminOpposition = + new Request( + UUID.randomUUID(), + fixture.target().accountUuid(), + fixture.admin().tenantUuid(), + fixture.admin().accountUuid(), + Action.TRANSFER_TENANT_ADMIN, + 2L, + 2L); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future transfer = + executor.submit( + () -> { + start.await(); + return tenantRoleMutationService.mutate(currentAdminTransfer); + }); + Future opposition = + executor.submit( + () -> { + start.await(); + return tenantRoleMutationService.mutate(nonAdminOpposition); + }); + start.countDown(); + + int committed = 0; + int denied = 0; + for (Future result : List.of(transfer, opposition)) { + try { + assertThat(result.get(20, TimeUnit.SECONDS).status()).isEqualTo("COMMITTED"); + committed++; + } catch (ExecutionException failure) { + assertThat(failure.getCause()).isInstanceOf(IllegalStateException.class); + denied++; + } + } + assertThat(committed).isEqualTo(1); + assertThat(denied).isEqualTo(1); + } finally { + executor.shutdownNow(); + } + + PositiveMembershipSnapshot finalAdmin = + readExistingPairBoundPositiveMembershipSnapshot(fixture.target()); + PositiveMembershipSnapshot formerAdmin = + readExistingPairBoundPositiveMembershipSnapshot(fixture.admin()); + assertThat(finalAdmin.roles()).contains("tenantAdmin", "player"); + assertThat(formerAdmin.roles()).containsExactly("player"); + assertThat(finalAdmin.gameplayAdmissionAllowed()).isTrue(); + assertThat(finalAdmin.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(countTenantRoleOperations(fixture.admin())).isEqualTo(1L); + } + @Test void canonicalExistingPairBoundPositiveMembershipSnapshotRepeatsWithoutMutation() { JoinFixture fixture = fixture("active"); @@ -2443,6 +2964,324 @@ private JoinFixture fixtureForMembership(JoinFixture existing) { UUID.randomUUID().toString()); } + private JoinFixture fixtureForSecondAccountInTenant(JoinFixture existing) { + String suffix = UUID.randomUUID().toString(); + String requestId = "join-proof-" + suffix; + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "join-proof-" + suffix, + "join-proof-" + suffix + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) " + + "VALUES (?, ?, 'join-proof', 'active', 1)", + accountId, + existing.tenantId()); + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + existing.tenantId(), + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "join-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + existing.tenantId(), + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture( + accountId, + accountUuid, + existing.tenantId(), + existing.tenantUuid(), + requestId, + caller, + scope.connectScopeId()); + } + + /** + * Creates a test-only historical retained current source, not an authorization or bootstrap + * producer proof. It preserves the ordinary JOIN writer and event history; the test installs a + * coherent preexisting V1 receipt, V1-sealed membership event, role source, generation, and pair. + */ + private TenantRoleFixture syntheticRetainedAdminFixture() { + JoinFixture admin = fixture("active"); + JoinFixture target = fixtureForSecondAccountInTenant(admin); + new TransactionTemplate(transactionManager) + .execute( + status -> { + seedSyntheticRetainedActiveMembership(admin, List.of("player", "tenantAdmin")); + seedSyntheticRetainedActiveMembership(target, List.of("player")); + PositiveMembershipSnapshot adminSnapshot = + membershipAuthorityEventProducer.readExistingPairBoundPositiveMembershipSnapshot( + admin.accountUuid(), admin.tenantUuid()); + PositiveMembershipSnapshot targetSnapshot = + membershipAuthorityEventProducer.readExistingPairBoundPositiveMembershipSnapshot( + target.accountUuid(), target.tenantUuid()); + assertThat(adminSnapshot.roles()).containsExactly("player", "tenantAdmin"); + assertThat(targetSnapshot.roles()).containsExactly("player"); + return null; + }); + return new TenantRoleFixture(admin, target); + } + + private void seedSyntheticRetainedActiveMembership(JoinFixture fixture, List roles) { + seedSyntheticRetainedActiveMembership(fixture, roles, "EXPLICIT_JOIN"); + } + + private void seedSyntheticRetainedActiveMembership( + JoinFixture fixture, List roles, String authorityProvenance) { + seedSyntheticRetainedActiveMembership(fixture, roles, authorityProvenance, false); + } + + private void seedSyntheticRetainedActiveMembership( + JoinFixture fixture, + List roles, + String authorityProvenance, + boolean exhaustedIssuanceFence) { + Account account = + accountRepository.findByAccountUuidForUpdate(fixture.accountUuid()).orElseThrow(); + ApprovedAssociation association = tenantIdentityResolver.resolve(fixture.tenantUuid()); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + + authorityGenerationRepository.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + authorityGenerationRepository.initialize( + AuthorityScope.membership(fixture.accountUuid(), fixture.tenantUuid())); + + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(association.legacyTenantId()); + membership.setTenantUuid(fixture.tenantUuid()); + membership.setTenantProvenanceKind(TenantProvenanceKind.APPROVED_RETAINED.name()); + membership.setTenantSourceOperationId(association.operationId()); + membership.setTenantProvenanceDigest(association.manifestDigest()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(2L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance(authorityProvenance); + AccountTenantMembership persisted = + membershipRepository.saveCanonical( + membership, fixture.accountUuid(), fixture.tenantUuid(), provenance); + RoleSnapshot roleSnapshot = + roleSnapshotRepository.replaceCanonical( + persisted, fixture.accountUuid(), fixture.tenantUuid(), provenance, 2L, roles); + + String historicalRequestId = "synthetic-retained-membership-join-" + UUID.randomUUID(); + MembershipTransitionReceipt receipt = + membershipTransitionReceiptRepository.appendTransition( + persisted, "MEMBERSHIP_JOINED", historicalRequestId); + assertThat(receipt.requestId()).isEqualTo(historicalRequestId); + + if (exhaustedIssuanceFence) { + assertThat( + dsl.execute( + "UPDATE account_authority_issuance_fences SET issuance_fence = ? " + + "WHERE account_uuid = ?", + Long.MAX_VALUE, + fixture.accountUuid())) + .isEqualTo(1); + } + + var authority = + authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + fixture.accountUuid(), + List.of(fixture.tenantUuid()), + List.of(fixture.tenantUuid())); + String streamKey = authorityStreamKey(fixture); + UUID eventUuid = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + historicalRequestId) + .getBytes(StandardCharsets.UTF_8)); + MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventUuid.toString()), + Map.entry("requestId", historicalRequestId), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry( + "sourceScope", + streamKey.substring( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX.length())), + Map.entry("accountId", fixture.accountUuid().toString()), + Map.entry("tenantId", fixture.tenantUuid().toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(fixture.tenantUuid().toString(), "2")), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", Long.toString(authority.issuer().generation()), + "accountAuthorityGeneration", + Long.toString(authority.account().generation()), + "tenantAuthorityGeneration", + Map.of( + fixture.tenantUuid().toString(), + Long.toString(authority.tenants().getFirst().generation())), + "membershipAuthorityGeneration", + Map.of(fixture.tenantUuid().toString(), "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", Long.toString(authority.issuanceFence().value())), + Map.entry("roles", roleSnapshot.roles()), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + AccountAuthorityOutboxRepository.Event appended = + authorityOutboxRepository.append( + streamKey, + historicalRequestId, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + pairAuthorityRepository.enrollProvenPositive( + fixture.accountUuid(), + fixture.tenantUuid(), + provenance, + new ProvenPositiveCheckpoint( + 2L, 1L, 1L, appended.eventId(), appended.eventDigest(), false)); + } + + private void assertCurrentRoleMutationState( + JoinFixture fixture, + long version, + long generation, + long sequence, + long fence, + List roles, + boolean invalidated) { + PositiveMembershipSnapshot snapshot = readExistingPairBoundPositiveMembershipSnapshot(fixture); + assertThat(snapshot.membershipExists()).isTrue(); + assertThat(snapshot.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(snapshot.gameplayAdmissionAllowed()).isTrue(); + assertThat(snapshot.membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), Long.toString(version))); + assertThat(snapshot.membershipAuthorityGeneration()).isEqualTo(Long.toString(generation)); + assertThat(snapshot.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), Long.toString(generation))); + assertThat(snapshot.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(snapshot.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(snapshot.authorityEvent().outboxSequence()).isEqualTo(Long.toString(sequence)); + assertThat(snapshot.authorityEvent().callerBoundAuthorityInvalidated()).isEqualTo(invalidated); + assertThat(snapshot.issuanceFence()).isEqualTo(Long.toString(fence)); + assertThat(snapshot.roles()).containsExactlyElementsOf(roles); + assertThat(snapshot.authorityEvent().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), Long.toString(version))); + assertThat(snapshot.authorityEvent().roles()).containsExactlyElementsOf(roles); + assertThat(snapshot.outboxCheckpoints()) + .contains(new OutboxCheckpointEntry(authorityStreamKey(fixture), Long.toString(sequence))); + assertThat(snapshot.outboxSourceEvidence()) + .anySatisfy( + evidence -> { + assertThat(evidence.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); + assertThat(evidence.outboxSequence()).isEqualTo(Long.toString(sequence)); + assertThat(evidence.eventId()).isEqualTo(snapshot.authorityEvent().eventId()); + assertThat(evidence.eventDigest()).isEqualTo(snapshot.authorityEvent().eventDigest()); + assertThat(evidence.canonicalEventJson()) + .isEqualTo(snapshot.authorityEvent().canonicalJson()); + }); + + var pair = + dsl.resultQuery( + "SELECT membership_version, membership_authority_generation, last_event_sequence, " + + "last_transition_invalidated FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(); + assertThat(pair).isNotNull(); + assertThat(pair.get("membership_version", Long.class)).isEqualTo(version); + assertThat(pair.get("membership_authority_generation", Long.class)).isEqualTo(generation); + assertThat(pair.get("last_event_sequence", Long.class)).isEqualTo(sequence); + assertThat(pair.get("last_transition_invalidated", Boolean.class)).isEqualTo(invalidated); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fence); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(generation); + } + + private static void assertExactTenantRoleOperation( + OperationEvidence expected, OperationEvidence actual) { + assertThat(actual.request()).isEqualTo(expected.request()); + assertThat(actual.requestPayload()).containsExactly(expected.requestPayload()); + assertThat(actual.requestDigest()).isEqualTo(expected.requestDigest()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.audit().auditEventId()).isEqualTo(expected.audit().auditEventId()); + assertThat(actual.audit().eventType()).isEqualTo(expected.audit().eventType()); + assertThat(actual.audit().occurredAt()).isEqualTo(expected.audit().occurredAt()); + assertThat(actual.audit().payloadDigest()).isEqualTo(expected.audit().payloadDigest()); + assertThat(actual.audit().payload()).containsExactly(expected.audit().payload()); + assertThat(actual.resultPayload()).containsExactly(expected.resultPayload()); + assertThat(actual.resultDigest()).isEqualTo(expected.resultDigest()); + assertThat(actual.members()).hasSize(expected.members().size()); + for (int index = 0; index < expected.members().size(); index++) { + var expectedMember = expected.members().get(index); + var actualMember = actual.members().get(index); + assertThat(actualMember.accountUuid()).isEqualTo(expectedMember.accountUuid()); + assertThat(actualMember.tenantUuid()).isEqualTo(expectedMember.tenantUuid()); + assertThat(actualMember.membershipVersion()).isEqualTo(expectedMember.membershipVersion()); + assertThat(actualMember.membershipAuthorityGeneration()) + .isEqualTo(expectedMember.membershipAuthorityGeneration()); + assertThat(actualMember.eventSequence()).isEqualTo(expectedMember.eventSequence()); + assertThat(actualMember.eventRequestId()).isEqualTo(expectedMember.eventRequestId()); + assertThat(actualMember.eventId()).isEqualTo(expectedMember.eventId()); + assertThat(actualMember.eventDigest()).isEqualTo(expectedMember.eventDigest()); + assertThat(actualMember.callerBoundAuthorityInvalidated()) + .isEqualTo(expectedMember.callerBoundAuthorityInvalidated()); + assertThat(actualMember.eventPayload()).containsExactly(expectedMember.eventPayload()); + } + } + + private long countTenantRoleOperations(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE tenant_uuid = ?", + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + + private void assertTenantRoleOperationAbsent(UUID requestId) { + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_role_operation_members WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isZero(); + } + private JoinFixture fixture( long accountId, UUID accountUuid, long tenantId, UUID tenantUuid, String suffix) { String requestId = "join-proof-" + suffix; @@ -2766,6 +3605,15 @@ private long countLeftAuditEvents(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long countAuditOutboxRows(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE scope = 'tenant' " + + "AND tenant_uuid = ?", + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + private Map leftAuditEnvelopeSnapshot(JoinFixture fixture, String requestId) { var row = dsl.resultQuery( @@ -3533,6 +4381,8 @@ private record JoinFixture( DirectTextCallerContext caller, String connectScopeId) {} + private record TenantRoleFixture(JoinFixture admin, JoinFixture target) {} + private record MembershipScopeSnapshot( Map membership, Map pairAuthority, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..59707eb6d0 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java @@ -0,0 +1,333 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest.MemberResult; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Action; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.AuditEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Claim; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.OperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.OperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository.Request; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountTenantRoleOperationRepositoryPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "tenant_role_operation_proof_"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void immutableJournalRetriesOriginalBytesAfterLaterRoleOperationAndRejectsChangedIntent() { + TestContext context = newTestContext(); + UUID actor = insertAccount(context.setupDsl()); + UUID target = insertAccount(context.setupDsl()); + UUID tenant = UUID.randomUUID(); + Request original = + request(UUID.randomUUID(), actor, tenant, target, Action.GRANT_DESIGNER, 4, 7); + MemberResult originalMember = + member(original, target, 8, 1, 1, List.of("designer", "player"), false); + AuditEvidence originalAudit = audit(UUID.randomUUID(), "{\"request\":\"first\"}"); + + OperationEvidence committed = + inTransaction( + context.transaction(), + () -> { + Claim claim = context.repository().claim(original); + assertThat(claim.claimed()).isTrue(); + return context + .repository() + .complete(original, originalAudit, List.of(originalMember)); + }); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.members()).hasSize(1); + MemberResult committedMember = committed.members().getFirst(); + assertThat(committedMember.accountUuid()).isEqualTo(originalMember.accountUuid()); + assertThat(committedMember.tenantUuid()).isEqualTo(originalMember.tenantUuid()); + assertThat(committedMember.membershipVersion()).isEqualTo(originalMember.membershipVersion()); + assertThat(committedMember.membershipAuthorityGeneration()) + .isEqualTo(originalMember.membershipAuthorityGeneration()); + assertThat(committedMember.eventSequence()).isEqualTo(originalMember.eventSequence()); + assertThat(committedMember.eventRequestId()).isEqualTo(originalMember.eventRequestId()); + assertThat(committedMember.eventId()).isEqualTo(originalMember.eventId()); + assertThat(committedMember.eventDigest()).isEqualTo(originalMember.eventDigest()); + assertThat(committedMember.callerBoundAuthorityInvalidated()) + .isEqualTo(originalMember.callerBoundAuthorityInvalidated()); + assertThat(committedMember.eventPayload()).containsExactly(originalMember.eventPayload()); + + Request later = request(UUID.randomUUID(), actor, tenant, target, Action.REVOKE_DESIGNER, 4, 8); + MemberResult laterMember = member(later, target, 9, 2, 2, List.of("player"), true); + inTransaction( + context.transaction(), + () -> { + assertThat(context.repository().claim(later).claimed()).isTrue(); + return context + .repository() + .complete( + later, audit(UUID.randomUUID(), "{\"request\":\"later\"}"), List.of(laterMember)); + }); + + OperationEvidence retry = + inTransaction( + context.transaction(), + () -> { + Claim claim = context.repository().claim(original); + assertThat(claim.claimed()).isFalse(); + return claim.replay().orElseThrow(); + }); + assertExactOperation(committed, retry); + + Request changedIntent = + request( + original.requestId(), + actor, + tenant, + target, + Action.REVOKE_DESIGNER, + original.expectedActorMembershipVersion(), + original.expectedTargetMembershipVersion()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().claim(changedIntent))) + .isInstanceOf(OperationConflictException.class) + .hasMessageContaining("changed immutable input"); + + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "UPDATE account_tenant_role_operations SET action = 'REVOKE_DESIGNER' " + + "WHERE request_id = ?", + original.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "DELETE FROM account_tenant_role_operations WHERE request_id = ?", + original.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void operationJournalAndMemberEvidenceRollBackTogether() { + TestContext context = newTestContext(); + UUID actor = insertAccount(context.setupDsl()); + UUID target = insertAccount(context.setupDsl()); + UUID tenant = UUID.randomUUID(); + Request request = + request(UUID.randomUUID(), actor, tenant, target, Action.GRANT_DESIGNER, 4, 7); + MemberResult member = member(request, target, 8, 1, 1, List.of("designer", "player"), false); + + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> { + context.repository().claim(request); + context + .repository() + .complete( + request, + audit(UUID.randomUUID(), "{\"rollback\":true}"), + List.of(member)); + throw new IllegalStateException("injected after operation readback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected after operation readback"); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_tenant_role_operations WHERE request_id = ?", + request.requestId()), + "Expected tenant-role operation count row") + .get(0, Long.class), + "Expected tenant-role operation count value")) + .isZero(); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_tenant_role_operation_members WHERE request_id = ?", + request.requestId()), + "Expected tenant-role member count row") + .get(0, Long.class), + "Expected tenant-role member count value")) + .isZero(); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dataSource, + setupDsl, + new AccountTenantRoleOperationRepository(transactionDsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private UUID insertAccount(DSLContext dsl) { + String unique = UUID.randomUUID().toString().replace("-", ""); + return dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING account_uuid", + "tenant_role_" + unique.substring(0, 12), + unique + "@example.test", + "test-hash") + .fetchOne(0, UUID.class); + } + + private Request request( + UUID request, + UUID actor, + UUID tenant, + UUID target, + Action action, + long actorVersion, + long targetVersion) { + return new Request(request, actor, tenant, target, action, actorVersion, targetVersion); + } + + private MemberResult member( + Request request, + UUID account, + long membershipVersion, + long generation, + long sequence, + List roles, + boolean invalidated) { + String eventRequestId = + AccountTenantRoleOperationRepository.eventRequestId(request.requestId(), account); + String eventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + eventRequestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + String streamKey = + AccountTenantRoleOperationRepository.eventStreamKey(account, request.tenantUuid()); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of(request.tenantUuid().toString(), "1")); + tuple.put( + "membershipAuthorityGeneration", + Map.of(request.tenantUuid().toString(), Long.toString(generation))); + tuple.put("privateRealmGrantVersions", List.of()); + Map preimage = new LinkedHashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", eventId); + preimage.put("requestId", eventRequestId); + preimage.put("outboxStreamKey", streamKey); + preimage.put("outboxSequence", Long.toString(sequence)); + preimage.put("sourceScope", "membership/" + account + "/" + request.tenantUuid()); + preimage.put("accountId", account.toString()); + preimage.put("tenantId", request.tenantUuid().toString()); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", "ACTIVE"); + preimage.put( + "membershipVersion", + Map.of(request.tenantUuid().toString(), Long.toString(membershipVersion))); + preimage.put("membershipAuthorityGeneration", Long.toString(generation)); + preimage.put("authorityTuple", tuple); + preimage.put("issuanceFence", "1"); + preimage.put("roles", roles); + preimage.put("gameplayAdmissionAllowed", true); + preimage.put("callerBoundAuthorityInvalidated", invalidated); + var event = MembershipAuthorityEventV1Codec.seal(preimage); + return new MemberResult( + account, + request.tenantUuid(), + membershipVersion, + generation, + sequence, + eventRequestId, + eventId, + event.eventDigest(), + invalidated, + event.canonicalJsonUtf8()); + } + + private AuditEvidence audit(UUID eventId, String payload) { + return new AuditEvidence( + eventId, + "ACCOUNT_TENANT_ROLE_CHANGED", + java.time.Instant.parse("2026-10-05T01:02:03Z"), + AccountAuditDigest.ofPayload(payload), + payload.getBytes(StandardCharsets.UTF_8)); + } + + private void assertExactOperation(OperationEvidence expected, OperationEvidence actual) { + assertThat(actual.request()).isEqualTo(expected.request()); + assertThat(actual.requestPayload()).containsExactly(expected.requestPayload()); + assertThat(actual.requestDigest()).isEqualTo(expected.requestDigest()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.resultPayload()).containsExactly(expected.resultPayload()); + assertThat(actual.resultDigest()).isEqualTo(expected.resultDigest()); + assertThat(actual.audit()).isNotNull(); + assertThat(actual.audit().payload()).containsExactly(expected.audit().payload()); + assertThat(actual.members()).hasSize(expected.members().size()); + for (int index = 0; index < actual.members().size(); index++) { + assertThat(actual.members().get(index).eventPayload()) + .containsExactly(expected.members().get(index).eventPayload()); + } + } + + private T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record TestContext( + DataSource dataSource, + DSLContext setupDsl, + AccountTenantRoleOperationRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigestTest.java new file mode 100644 index 0000000000..f006ea80b6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleMutationDigestTest.java @@ -0,0 +1,897 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleMutationDigest.MemberResult; +import org.junit.jupiter.api.Test; + +class AccountTenantRoleMutationDigestTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACTOR_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TARGET_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String ACTION = "GRANT_DESIGNER_雪"; + private static final long ACTOR_VERSION = 9_007_199_254_740_993L; + private static final long TARGET_VERSION = 9_223_372_036_854_775_806L; + + @Test + void requestUsesUtf8ByteLengthFramingAndMatchesIndependentFixedSha256Vector() { + assertThat(List.of(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID)).doesNotHaveDuplicates(); + + byte[] independentPreimage = + independentFrame( + "firemud/account/tenant-role/request/v1", + REQUEST_ID.toString(), + ACTOR_ID.toString(), + TENANT_ID.toString(), + TARGET_ID.toString(), + ACTION, + "9007199254740993", + "9223372036854775806"); + + assertThat(ACTION.getBytes(StandardCharsets.UTF_8)).hasSize(18); + assertThat( + AccountTenantRoleMutationDigest.requestBytes( + REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, ACTOR_VERSION, TARGET_VERSION)) + .containsExactly(independentPreimage); + assertThat(independentSha256(independentPreimage)) + .isEqualTo("sha256:9d43eb2da0eabcfb264a547d60f9b0c8cdf2b10bcef9d1253c0559d404b7f1ba"); + assertThat(AccountTenantRoleMutationDigest.sha256(independentPreimage)) + .isEqualTo(independentSha256(independentPreimage)); + } + + @Test + void everyRequestFieldChangesTheDigest() { + String original = requestDigest(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 7L, 11L); + + assertThat( + requestDigest( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + ACTOR_ID, + TENANT_ID, + TARGET_ID, + ACTION, + 7L, + 11L)) + .isNotEqualTo(original); + assertThat( + requestDigest( + REQUEST_ID, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + TENANT_ID, + TARGET_ID, + ACTION, + 7L, + 11L)) + .isNotEqualTo(original); + assertThat( + requestDigest( + REQUEST_ID, + ACTOR_ID, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + TARGET_ID, + ACTION, + 7L, + 11L)) + .isNotEqualTo(original); + assertThat( + requestDigest( + REQUEST_ID, + ACTOR_ID, + TENANT_ID, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + ACTION, + 7L, + 11L)) + .isNotEqualTo(original); + assertThat( + requestDigest(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, "REVOKE_DESIGNER", 7L, 11L)) + .isNotEqualTo(original); + assertThat(requestDigest(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 8L, 11L)) + .isNotEqualTo(original); + assertThat(requestDigest(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 7L, 12L)) + .isNotEqualTo(original); + } + + @Test + void rejectsMissingRequestFieldsAndNonpositiveExpectedVersions() { + assertThatThrownBy(() -> request(null, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, null, TENANT_ID, TARGET_ID, ACTION, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, ACTOR_ID, null, TARGET_ID, ACTION, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, ACTOR_ID, TENANT_ID, null, ACTION, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, null, 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 0L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST_ID, ACTOR_ID, TENANT_ID, TARGET_ID, ACTION, 1L, -1L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void resultFramesEveryOperationAuditAndMemberFieldAndSortsMembersDeterministically() { + MemberResult first = + member( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}); + MemberResult second = + member( + uuid("55555555-5555-4555-8555-555555555555"), + TENANT_ID, + 2, + 3, + 4, + "event-request-2", + "event-id-2", + "sha256:" + "e".repeat(64), + true, + new byte[] {2, 3, 4}); + List members = List.of(first, second); + byte[] auditPayload = new byte[] {0, (byte) 0xff, 3, 0}; + byte[] framed = + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members); + + assertThat(framed) + .containsExactly( + independentResultFrame( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + List.of(second, first))); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + List.of(second, first))) + .containsExactly(framed); + + assertThat( + resultBytes( + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "c".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + uuid("99999999-9999-4999-8999-999999999999"), + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_REVOKED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-06T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "c".repeat(64), + auditPayload, + members)) + .isNotEqualTo(framed); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + new byte[] {0, 1}, + members)) + .isNotEqualTo(framed); + + MemberResult baselineMember = first; + List changedMembers = + List.of( + member( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + uuid("99999999-9999-4999-8999-999999999999"), + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 4, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 4, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 4, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 3, + "event-request-changed", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id-changed", + "sha256:" + "d".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "e".repeat(64), + false, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + true, + new byte[] {1, 2, 3}), + member( + baselineMember.accountUuid(), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {3, 2, 1})); + for (MemberResult changed : changedMembers) { + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + auditPayload, + List.of(changed, second))) + .isNotEqualTo(framed); + } + } + + @Test + void memberEventPayloadIsDefensivelyCopiedOnConstructionAndAccess() { + byte[] original = new byte[] {1, 2, 3}; + MemberResult member = + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + true, + original); + original[0] = 99; + byte[] accessed = member.eventPayload(); + accessed[1] = 99; + + assertThat(member.eventPayload()).containsExactly(1, 2, 3); + assertThat( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + new byte[] {0}, + List.of(member))) + .containsExactly( + resultBytes( + REQUEST_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + uuid("77777777-7777-4777-8777-777777777777"), + "TENANT_ROLE_CHANGED", + "2026-10-05T12:34:56Z", + "sha256:" + "b".repeat(64), + new byte[] {0}, + List.of( + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 2, + 3, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + true, + new byte[] {1, 2, 3})))); + } + + @Test + void rejectsIncompleteResultsAndNonpositiveMemberCounters() { + assertThatThrownBy( + () -> + new MemberResult( + null, + TENANT_ID, + 1, + 1, + 1, + "r", + "i", + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + null, + 1, + 1, + 1, + "r", + "i", + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + null, + "i", + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + "r", + null, + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + "r", + "i", + null, + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + "r", + "i", + "sha256:" + "d".repeat(64), + false, + null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> memberWithCounters(0, 1, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> memberWithCounters(1, 0, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> memberWithCounters(1, 1, 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + " ", + "i", + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + "r", + " ", + "sha256:" + "d".repeat(64), + false, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingTopLevelResultFieldsAndMissingMembers() { + MemberResult member = + member( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + 1, + 1, + 1, + "event-request", + "event-id", + "sha256:" + "d".repeat(64), + false, + new byte[] {1}); + assertResultBytesRejected( + null, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + null, + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + null, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + null, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + null, + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + null, + "payload-digest", + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + null, + new byte[] {1}, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + null, + List.of(member)); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + null); + assertResultBytesRejected( + REQUEST_ID, + "request-digest", + TENANT_ID, + TARGET_ID, + "event-type", + "occurred-at", + "payload-digest", + new byte[] {1}, + List.of()); + } + + private static String requestDigest( + UUID requestId, + UUID actorId, + UUID tenantId, + UUID targetId, + String action, + long actorVersion, + long targetVersion) { + return AccountTenantRoleMutationDigest.sha256( + request(requestId, actorId, tenantId, targetId, action, actorVersion, targetVersion)); + } + + private static byte[] request( + UUID requestId, + UUID actorId, + UUID tenantId, + UUID targetId, + String action, + long actorVersion, + long targetVersion) { + return AccountTenantRoleMutationDigest.requestBytes( + requestId, actorId, tenantId, targetId, action, actorVersion, targetVersion); + } + + private static byte[] resultBytes( + UUID requestId, + String requestDigest, + UUID tenantId, + UUID auditEventId, + String auditEventType, + String auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + List members) { + return AccountTenantRoleMutationDigest.resultBytes( + requestId, + requestDigest, + tenantId, + auditEventId, + auditEventType, + auditOccurredAt, + auditPayloadDigest, + auditPayload, + members); + } + + private static void assertResultBytesRejected( + UUID requestId, + String requestDigest, + UUID tenantId, + UUID auditEventId, + String auditEventType, + String auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + List members) { + assertThatThrownBy( + () -> + resultBytes( + requestId, + requestDigest, + tenantId, + auditEventId, + auditEventType, + auditOccurredAt, + auditPayloadDigest, + auditPayload, + members)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static MemberResult member( + UUID accountId, + UUID tenantId, + long version, + long generation, + long sequence, + String eventRequestId, + String eventId, + String eventDigest, + boolean invalidated, + byte[] payload) { + return new MemberResult( + accountId, + tenantId, + version, + generation, + sequence, + eventRequestId, + eventId, + eventDigest, + invalidated, + payload); + } + + private static MemberResult memberWithCounters(long version, long generation, long sequence) { + return new MemberResult( + uuid("66666666-6666-4666-8666-666666666666"), + TENANT_ID, + version, + generation, + sequence, + "r", + "i", + "sha256:" + "d".repeat(64), + false, + new byte[0]); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static byte[] independentResultFrame( + UUID requestId, + String requestDigest, + UUID tenantId, + UUID auditEventId, + String auditEventType, + String auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + List members) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (DataOutputStream framed = new DataOutputStream(output)) { + writeIndependentField( + framed, "firemud/account/tenant-role/result/v1".getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, requestId.toString().getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, requestDigest.getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, tenantId.toString().getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, auditEventId.toString().getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, auditEventType.getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, auditOccurredAt.getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, auditPayloadDigest.getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, auditPayload); + framed.writeInt(members.size()); + for (MemberResult member : members.stream().sorted().toList()) { + writeIndependentField( + framed, member.accountUuid().toString().getBytes(StandardCharsets.UTF_8)); + writeIndependentField( + framed, member.tenantUuid().toString().getBytes(StandardCharsets.UTF_8)); + writeIndependentField( + framed, Long.toString(member.membershipVersion()).getBytes(StandardCharsets.UTF_8)); + writeIndependentField( + framed, + Long.toString(member.membershipAuthorityGeneration()).getBytes(StandardCharsets.UTF_8)); + writeIndependentField( + framed, Long.toString(member.eventSequence()).getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, member.eventRequestId().getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, member.eventId().getBytes(StandardCharsets.UTF_8)); + writeIndependentField(framed, member.eventDigest().getBytes(StandardCharsets.UTF_8)); + framed.writeBoolean(member.callerBoundAuthorityInvalidated()); + writeIndependentField(framed, member.eventPayload()); + } + framed.flush(); + return output.toByteArray(); + } catch (IOException impossibleForByteArray) { + throw new IllegalStateException(impossibleForByteArray); + } + } + + private static byte[] independentFrame(String... values) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (DataOutputStream framed = new DataOutputStream(output)) { + for (String value : values) { + writeIndependentField(framed, value.getBytes(StandardCharsets.UTF_8)); + } + framed.flush(); + return output.toByteArray(); + } catch (IOException impossibleForByteArray) { + throw new IllegalStateException(impossibleForByteArray); + } + } + + private static void writeIndependentField(DataOutputStream output, byte[] bytes) + throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } + + private static String independentSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossibleOnStandardJdk) { + throw new IllegalStateException(impossibleOnStandardJdk); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryTest.java new file mode 100644 index 0000000000..f72d20a681 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Instant; +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantRoleOperationRepositoryTest { + private static final UUID ACTOR = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TARGET = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void requestsBindEveryIdentityActionAndExpectedVersion() { + var grant = request(AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, 7L, 9L); + var changedAction = + request(AccountTenantRoleOperationRepository.Action.REVOKE_DESIGNER, 7L, 9L); + var changedActorVersion = + request(AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, 8L, 9L); + var changedTargetVersion = + request(AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, 7L, 10L); + + assertThat(grant.payload()).isNotEqualTo(changedAction.payload()); + assertThat(grant.payload()).isNotEqualTo(changedActorVersion.payload()); + assertThat(grant.payload()).isNotEqualTo(changedTargetVersion.payload()); + assertThat(grant.payload()) + .isEqualTo( + request(AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, 7L, 9L).payload()); + } + + @Test + void transferMustBeDistinctAndExpectedVersionsPositive() { + assertThatThrownBy( + () -> + new AccountTenantRoleOperationRepository.Request( + REQUEST, + ACTOR, + TENANT, + ACTOR, + AccountTenantRoleOperationRepository.Action.TRANSFER_TENANT_ADMIN, + 7L, + 7L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct members"); + assertThatThrownBy( + () -> + new AccountTenantRoleOperationRepository.Request( + REQUEST, + ACTOR, + TENANT, + TARGET, + AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, + 0L, + 9L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + } + + @Test + void repositoryRequiresAnAccountWriteTransactionBeforeAnySql() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountTenantRoleOperationRepository(dsl); + var request = request(AccountTenantRoleOperationRepository.Action.GRANT_DESIGNER, 7L, 9L); + boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean wasReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + assertThatThrownBy(() -> repository.claim(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account write transaction"); + assertThatThrownBy(() -> repository.findForUpdate(REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account write transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasActive); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(wasReadOnly); + } + verifyNoInteractions(dsl); + } + + @Test + void auditEvidenceRequiresTheCanonicalRoleEventAndPayloadDigest() { + byte[] payload = "{\"schema\":\"account-tenant-role-audit/v1\"}".getBytes(); + String digest = + net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload( + new String(payload, java.nio.charset.StandardCharsets.UTF_8)); + assertThat( + new AccountTenantRoleOperationRepository.AuditEvidence( + UUID.randomUUID(), + "ACCOUNT_TENANT_ROLE_CHANGED", + Instant.parse("2026-10-05T01:02:03Z"), + digest, + payload) + .payload()) + .containsExactly(payload); + assertThatThrownBy( + () -> + new AccountTenantRoleOperationRepository.AuditEvidence( + UUID.randomUUID(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + Instant.parse("2026-10-05T01:02:03Z"), + digest, + payload)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest or type"); + } + + private AccountTenantRoleOperationRepository.Request request( + AccountTenantRoleOperationRepository.Action action, + long expectedActorVersion, + long expectedTargetVersion) { + return new AccountTenantRoleOperationRepository.Request( + REQUEST, ACTOR, TENANT, TARGET, action, expectedActorVersion, expectedTargetVersion); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index a1376c7f88..1766245dc6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -92,7 +92,11 @@ private AccountMembershipAuthorityEventProducer producer() { mock(AccountLogoutAllOperationRepository.class), transitionReceipts, memberships, - roleSnapshots); + roleSnapshots, + mock(net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository + .class)); } private void verifyNoReads() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java index 66f4a71ec8..8cdeff464f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -55,7 +55,13 @@ void inactiveMembershipSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { mock(AccountLogoutAllOperationRepository.class), receiptRepository, membershipRepository, - rolesRepository); + rolesRepository, + mock( + net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantRoleOperationRepository.class)); boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); TransactionSynchronizationManager.setActualTransactionActive(false); @@ -102,7 +108,13 @@ void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { mock(AccountLogoutAllOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), - mock(AccountTenantMembershipRoleSnapshotRepository.class)); + mock(AccountTenantMembershipRoleSnapshotRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantRoleOperationRepository.class)); assertThatThrownBy( () -> @@ -135,7 +147,13 @@ void canonicalRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { mock(AccountLogoutAllOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), - mock(AccountTenantMembershipRoleSnapshotRepository.class)); + mock(AccountTenantMembershipRoleSnapshotRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantRoleOperationRepository.class)); assertThatThrownBy( () -> producer.readRuntimeMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) @@ -182,7 +200,13 @@ void existingPositiveSnapshotRequiresOwnerTransactionBeforeIdentityReads() { mock(AccountLogoutAllOperationRepository.class), transitionReceiptRepository, membershipRepository, - roleSnapshotRepository); + roleSnapshotRepository, + mock( + net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantRoleOperationRepository.class)); assertThatThrownBy( () -> @@ -237,7 +261,13 @@ void existingRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { mock(AccountLogoutAllOperationRepository.class), transitionReceiptRepository, membershipRepository, - roleSnapshotRepository); + roleSnapshotRepository, + mock( + net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantRoleOperationRepository.class)); assertThatThrownBy( () -> From 214c6c9a875ce8f37f71891f89a95c1ac8cb85da Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:18:32 +1300 Subject: [PATCH 2/6] Prove fresh membership source readback and repair Account PostgreSQL fixtures --- .github/workflows/ci.yml | 5 + .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 6 + .../dto/AccountMembershipCaptureSources.java | 64 ++- ...MembershipTransitionReceiptRepository.java | 28 + .../AccountTenantRoleOperationRepository.java | 5 +- ...countMembershipAuthorityEventProducer.java | 494 +++++++++++++++--- ...icalJoinReconciliationIntegrationTest.java | 285 ++++++++++ ...ershipSnapshotPostgresIntegrationTest.java | 6 +- .../AccountJoinPostgresIntegrationTest.java | 122 +++-- .../AccountMembershipCaptureSourcesTest.java | 271 +++++++++- ...thorityEventProducerCanonicalJoinTest.java | 23 + 12 files changed, 1179 insertions(+), 132 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 13210f5294..992957532e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1786,6 +1786,11 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#eventReadbackRejectsStalePendingDtoAfterJournalHasTerminalized()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#absentOrContradictoryOwnerEvidenceRemainsPendingWithoutReconciliationSideEffects()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#committedFreshUuidJoinReturnsExactPositiveSnapshotAndCaptureWithoutChangingSources()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#existingOnlyFreshUuidReadPreservesProvedAbsenceAndPendingOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#pendingCanonicalJoinCannotAuthorizePositiveReadbackOrCauseMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#freshUuidReadRejectsContradictoryReceiptEventRolesPairAndAuditWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#existingOnlyFreshUuidReadRejectsWrongAccountAndTenantSources()' \ account-service - name: Upload Account canonical JOIN scope and intent PostgreSQL proof results diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5c43c95e1a..2078076aa7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -14,6 +14,8 @@ Global-role grant/revoke production and the protected first-administrator bootst The in-progress `AccountTenantRoleMutationService`, `AccountTenantRoleOperationRepository`, and V56 draft form an unwired Account-local storage candidate for existing `APPROVED_RETAINED` memberships only. The candidate requires a same-snapshot current membership that is `ACTIVE`, gameplay-admitting, and sourced from `EXPLICIT_JOIN`, together with matching retained tenant provenance, role snapshot, pair authority, authority tuple, and issuance fence. It changes no missing, inactive, non-admitting, creator-bootstrap, unmapped, or ambiguous membership. It has no authenticated caller ingress or route/RPC, does not verify an authenticated actor at the commit boundary, does not implement creator bootstrap, and does not produce the complete Account authorization-evidence bundle; none of those capabilities is enabled. Mutation authority and policy remain owned by [Account API Contracts](./api-contracts.md#account-owned-tenant-role-administration). +Role changes advance the current membership evidence without rewriting the original lifecycle receipt. The retained positive reader first proves the exact current role journal, event, audit and source snapshot before reading that immutable historical lifecycle receipt; historical counters are not current authority. Ordinary JOIN receipt reads retain their strict current-state comparison. The separate fresh-UUID reader accepts only a completely read-back committed first canonical JOIN, including its V2 operation, receipt, audit, event, pair and current sources. Missing, contradictory, pending or unsupported later state remains denied and cannot be reset to a never-joined checkpoint. Both readers remain internal prerequisites, not authenticated runtime RPCs or credential authorization; execution and activation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + The draft's closed persisted actions are `GRANT_DESIGNER`, `REVOKE_DESIGNER`, and `TRANSFER_TENANT_ADMIN`. Within one Account write transaction it locks the distinct actor and target Account rows in canonical UUID order; claims the operation journal; reads the existing tenant association and current caller-bound source; checks the positive expected actor and target `membershipVersion` values; then updates the existing membership and role snapshot, advances each affected membership version once from its observed value, advances authority generation only according to that membership's recorded invalidation result, and appends the existing closed `account-auth-authority-event/v1` membership event and pair-authority checkpoint to the canonical per-account/tenant stream. It appends the Account tenant audit envelope and persists the immutable operation/member result in the same transaction. For a newly claimed operation, before returning it re-reads the committed request/result, audit envelope, event bytes, pair authority, role snapshot, and current membership source and requires exact equality; a stale source, incomplete readback, or any mismatch fails the transaction rather than leaving partial role, membership, event, audit, or journal state. Designer changes persist one member result; administrator transfer persists both affected member results in canonical Account UUID order. V56 adds an immutable-request, one-way-commit `account_tenant_role_operations` request/result journal and immutable `account_tenant_role_operation_members` event-evidence rows; it does not rewrite a published migration, backfill role state, reset membership versions or stream checkpoints, remap retained associations, or create a parallel membership event stream. The request payload is a v1 fixed-order byte frame. For each field, `frame(x) = UInt32BE(length(UTF8(x))) || UTF8(x)`. Concatenate frames for, in order: `firemud/account/tenant-role/request/v1`, the canonical non-nil UUIDs `requestId`, `actorAccountUuid`, `tenantUuid`, and `targetAccountUuid`, the exact action name above, positive `expectedActorMembershipVersion` as a base-10 decimal string, and positive `expectedTargetMembershipVersion` as a base-10 decimal string. `requestDigest` is `sha256:` plus lowercase hexadecimal SHA-256 of those exact bytes. Canonical UUID fields use lowercase hyphenated `UUID.toString()` form. 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 638c948b2a..ca9a2d5f07 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,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact `b9e06f435a9832d5d520e1626f33e1fd5848f0d7` [CI37270614224](https://github.com/benhook1013/FireMUD/actions/runs/37270614224) supplies actual PostgreSQL execution, not passing proof: all thirteen required retained-role and journal methods executed with zero skips, three passed and ten failed. The JOIN suite executed 51 methods with nine failures, including one additional denial-message regression; the journal suite executed two methods with two failures. Six role tests failed while constructing entitlement-backed fixture state, the non-explicit and overflow setups violated unchanged owner guards, and the journal SQL bound `audit_occurred_at` as varchar instead of TIMESTAMPTZ. The Account job is terminal failure; the aggregate was still running at the observer handoff. Root independently parsed and hashed both raw suites (`82be9d4539a5c710a3fe1763c7616e85537c22be9bdb8df86b0291f21800a368` and `c45a5b48f208fc84abfedb47edd668703ec7af02227ce7a0c1b74f349550dbc0`). Corrected execution remains required; fixture repairs must preserve the production guards and no-mutation assertions. + +The Account reader correction adds exact positive readback for an already committed fresh-UUID first JOIN, rather than routing every fresh association through never-joined absence. It requires the committed V2 operation and policy, exact receipt and canonical audit, current role/event/pair evidence and complete source checkpoints; it performs no enrollment or mutation and rejects pending, contradictory or unsupported state. Retained role readback now proves its current immutable role journal/event/audit before using a historical lifecycle receipt. The ordinary JOIN receipt reader still rejects stale counters; role revocation may independently advance generation without rewriting that historical receipt. These are unwired component prerequisites, not authenticated JOIN, creator bootstrap or RPC activation. + +The complete corrected Account full check, boot JAR, formatting, analyzers, coverage, links and Markdown pass in 1m14s (72 tasks: 19 executed, 53 up-to-date). Parsed XML records 943 clean unit executions and 349 integration cases, all locally skipped without Docker. The batch repairs the executed fixture failures without bypassing entitlement, receipt or monotonic-fence guards, and binds the original journal timestamp explicitly as TIMESTAMPTZ. The existing-only capture carries exactly one fresh or retained tenant source together with the exact role header and same-snapshot authority vector; neither the carrier nor the immutable identity receipt authenticates a caller. Five new canonical-JOIN PostgreSQL methods define positive snapshot/source-capture readback without mutation, preserved proved absence, pending denial, contradictory receipt/event/roles/pair/audit and wrong-identity denial. The existing real retained grant/revoke/transfer case now checks strict receipt denial, exact historical receipt recovery and current role-state readback without mutation. CI requires the five new methods as well as the thirteen retained-role/journal methods; corrected-state PostgreSQL execution is still required. Upstream authenticated caller/policy and live delivery are not proved by the fixtures. The known earlier role-reader ordering defect is corrected in source, not declared database-proved by the Docker-free gate. The first combined local check failed on a fresh-source fixture's invalid UUID substring; that fixture was corrected before the passing check, with no production guard or negative assertion weakened. + The tenant-role owner policy (`AUTH-TENANT-ROLE-OWNER-01`) was approved on 2026-10-05. The unwired existing-member candidate now implements designer grant/revoke and atomic administrator transfer for exactly proved, retained, admitting `EXPLICIT_JOIN` memberships. V56 adds an immutable request/result journal and member evidence; the Account transaction serializes canonical actor/target rows, checks current role/version sources, commits matching membership events, checkpoints and canonical audit evidence, and verifies exact readback. Exact committed retries preserve the original result after later role changes. These internal sources do not authenticate the supplied actor, implement public role ingress, or produce the complete Account authorization bundle; those required capabilities remain open and no route or RPC is enabled. The corrected Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m44s (72 tasks: 24 executed, 48 up-to-date). Parsed XML records 940 unit executions without failures, errors or skips, including eleven new digest/journal cases. All 344 integration cases compile and skip locally without Docker. The thirteen new PostgreSQL definitions cover the actual unwired mutation service and journal: current-role/version/tenant/membership denial without mutation, grant/revoke/transfer, immutable retry, event/audit/readback rollback, fence exhaustion and concurrent opposing transfers. Their retained administrator fixture stipulates coherent historical owner evidence rather than proving an authenticated enrollment producer. CI requires all thirteen exact methods without skips and captures raw XML; database execution, authenticated actor and creator producers, fresh-image composition and live delivery remain open. Constructor annotations are narrowly scoped to injected-collaborator validation and do not relax runtime guards; the eighteen discarded protobuf configuration-cache problems do not establish cache support. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java index 27556073a2..e8714e6a26 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java @@ -22,14 +22,15 @@ import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; /** * Immutable source material retained from one owner-local existing-membership read. * *

This value is not authorization. It preserves the exact locked authority rows, their * independent source versions and Account fence, alongside the membership projection that carries - * the corresponding source checkpoints and events. A raw retained role header remains unchanged; - * its audited tenant association is carried separately for identity binding. + * the corresponding source checkpoints and events. The applicable retained or fresh tenant identity + * receipt is carried separately from the raw role header for exact source binding. */ public record AccountMembershipCaptureSources( UUID requestedAccountUuid, @@ -37,7 +38,8 @@ public record AccountMembershipCaptureSources( CompositeSnapshot authoritySnapshot, RuntimeMembershipSnapshotDto membershipSnapshot, Optional roleSource, - Optional retainedTenantAssociation) { + Optional retainedTenantAssociation, + Optional freshTenantAssociation) { private static final String AUTHORITY_STREAM_PREFIX = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; @@ -50,6 +52,13 @@ public record AccountMembershipCaptureSources( retainedTenantAssociation = Objects.requireNonNull( retainedTenantAssociation, "retained tenant association presence is required"); + freshTenantAssociation = + Objects.requireNonNull( + freshTenantAssociation, "fresh tenant association presence is required"); + if (retainedTenantAssociation.isPresent() == freshTenantAssociation.isPresent()) { + throw new IllegalArgumentException( + "Exactly one retained or fresh tenant association must identify the source"); + } String accountId = requestedAccountUuid.toString(); String tenantId = requestedTenantUuid.toString(); @@ -115,12 +124,17 @@ public record AccountMembershipCaptureSources( retainedTenantAssociation .map(association -> requireRetainedAssociation(requestedTenantUuid, association)) .orElse(null); + VerifiedTenantProvenance freshProvenance = + freshTenantAssociation + .map(association -> requireFreshAssociation(requestedTenantUuid, association)) + .orElse(null); requireRoleSource( requestedAccountUuid, requestedTenantUuid, membershipSnapshot, roleSource.orElse(null), retainedProvenance, + freshProvenance, version); } @@ -271,6 +285,7 @@ private static void requireRoleSource( RuntimeMembershipSnapshotDto snapshot, RoleSnapshot roleSource, VerifiedTenantProvenance retainedProvenance, + VerifiedTenantProvenance freshProvenance, String membershipVersion) { if (!snapshot.membershipExists()) { if (roleSource != null || !snapshot.roles().isEmpty()) { @@ -280,24 +295,37 @@ private static void requireRoleSource( return; } - boolean canonicalTenantUuidPresent = roleSource != null && roleSource.tenantUuid() != null; - boolean canonicalProvenancePresent = - roleSource != null && roleSource.tenantProvenance() != null; if (roleSource == null - || retainedProvenance == null || roleSource.accountUuid() == null || !accountUuid.equals(roleSource.accountUuid()) || roleSource.accountId() <= 0L - || !Objects.equals(roleSource.tenantId(), retainedProvenance.legacyTenantId()) || roleSource.membershipId() <= 0L - || roleSource.snapshotVersion() != Long.parseLong(membershipVersion) - || !roleSource.roles().equals(snapshot.roles()) + || !Long.toString(roleSource.snapshotVersion()).equals(membershipVersion) + || !roleSource.roles().equals(snapshot.roles())) { + throw new IllegalArgumentException( + "Current membership roles lack the exact existing role header and identity"); + } + + if (freshProvenance != null) { + if (roleSource.tenantId() != null + || !tenantUuid.equals(roleSource.tenantUuid()) + || !freshProvenance.equals(roleSource.tenantProvenance())) { + throw new IllegalArgumentException( + "Fresh membership role header differs from its exact UUID source receipt"); + } + return; + } + + boolean canonicalTenantUuidPresent = roleSource.tenantUuid() != null; + boolean canonicalProvenancePresent = roleSource.tenantProvenance() != null; + if (retainedProvenance == null + || !Objects.equals(roleSource.tenantId(), retainedProvenance.legacyTenantId()) || canonicalTenantUuidPresent != canonicalProvenancePresent || (canonicalTenantUuidPresent && (!tenantUuid.equals(roleSource.tenantUuid()) || !retainedProvenance.equals(roleSource.tenantProvenance())))) { throw new IllegalArgumentException( - "Current membership roles lack the exact existing role header and identity"); + "Current membership roles lack the exact retained tenant association"); } } @@ -316,6 +344,20 @@ private static VerifiedTenantProvenance requireRetainedAssociation( association.manifestDigest()); } + private static VerifiedTenantProvenance requireFreshAssociation( + UUID tenantUuid, FreshTenantCreationEvidence association) { + if (association.canonicalTenantId() == null + || !tenantUuid.equals(association.canonicalTenantId())) { + throw new IllegalArgumentException( + "Fresh tenant association differs from the exact canonical request"); + } + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + association.operationId(), + association.evidenceDigest()); + } + private static String membershipSequence(RuntimeMembershipSnapshotDto snapshot) { UUID accountUuid = requireCanonicalSnapshotUuid(snapshot.accountUuid(), "Account UUID"); UUID tenantUuid = requireCanonicalSnapshotUuid(snapshot.tenantUuid(), "tenant UUID"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java index b7fa1409df..fe337c3528 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -1265,6 +1265,34 @@ public Optional findLatestReceipt(long accountId, l return Optional.of(receipt); } + /** + * Reads the latest immutable lifecycle receipt without treating its historical counters as + * current authority. A later role event may advance those counters without a lifecycle + * transition. Callers must independently prove the current role operation, event and audit before + * using this historical evidence; ordinary JOIN readers retain {@link #findLatestReceipt}. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional findLatestHistoricalReceipt( + long accountId, long tenantId) { + requireOwnerTransaction(); + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null || snapshot.receipt() == null) { + return Optional.empty(); + } + TransitionReceiptEvidence evidence = + findByRequestId(snapshot.receipt().requestId()) + .orElseThrow( + () -> new IllegalStateException("Account lifecycle receipt readback is missing")); + if (evidence.accountId() != accountId + || evidence.tenantId() != tenantId + || !evidence.receipt().equals(snapshot.receipt()) + || evidence.membershipVersion() != snapshot.receiptMembershipVersion() + || evidence.membershipAuthorityGeneration() != snapshot.receiptAuthorityGeneration()) { + throw new IllegalStateException("Account lifecycle receipt readback is inconsistent"); + } + return Optional.of(evidence); + } + /** * Reads one immutable transition receipt by its globally unique request ID without requiring it * to remain the current receipt. This supports exact, non-authorizing replay after a later diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java index 24d79c4e60..9850fcd43e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java @@ -143,12 +143,13 @@ public OperationEvidence complete( "UPDATE " + OPERATIONS + " SET status = 'COMMITTED', audit_event_id = ?, audit_event_type = ?, " - + "audit_occurred_at = ?, audit_payload_digest = ?, audit_payload = ?, " + + "audit_occurred_at = CAST(? AS TIMESTAMPTZ), audit_payload_digest = ?, " + + "audit_payload = ?, " + "result_payload = ?, result_digest = ? " + "WHERE request_id = ? AND status = 'IN_PROGRESS' AND request_digest = ?", audit.auditEventId(), audit.eventType(), - audit.occurredAt(), + audit.occurredAt().toString(), audit.payloadDigest(), audit.payload(), resultPayload, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 2df0e781c6..6454766381 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -13,11 +13,13 @@ import java.util.Optional; import java.util.UUID; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; @@ -43,6 +45,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository.TransitionReceiptEvidence; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; @@ -193,29 +196,6 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( "Current Account role snapshot differs from its exact active membership"); } - MembershipTransitionReceipt transitionReceipt = - transitionReceiptRepository - .findLatestReceipt(accountId, legacyTenantId) - .orElseThrow( - () -> - new IllegalStateException( - "Current Account membership has no positive transition receipt")); - if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, legacyTenantId) - .equals(transitionReceipt.receiptStreamKey()) - || transitionReceipt.receiptSequence() <= 0L - || transitionReceipt.receiptId() == null - || transitionReceipt.receiptDigest() == null - || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals( - transitionReceipt.evidenceStatus()) - || (!"MEMBERSHIP_JOINED".equals(transitionReceipt.transitionType()) - && !"MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType())) - || transitionReceipt.requestId() == null - || transitionReceipt.requestId().isBlank() - || transitionReceipt.membershipId() != membership.membershipId()) { - throw new IllegalStateException( - "Current Account membership transition receipt is incomplete or mismatched"); - } - CompositeSnapshot authoritySnapshot = readSnapshot(identity); ScopeState membershipAuthority = only(authoritySnapshot.memberships(), "membership"); requireMatchingFence(authoritySnapshot, membershipAuthority, identity.accountUuid()); @@ -247,36 +227,77 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( "Current Account membership checkpoint differs from its event"); } MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); - Optional tenantRoleEvidence = Optional.empty(); - if (!transitionReceipt.requestId().equals(verified.requestId())) { - tenantRoleEvidence = - Optional.of( - tenantRoleOperationRepository - .findCurrentMemberEvidenceForUpdate( - identity.accountUuid(), identity.tenantUuid(), verified.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Current Account membership event lacks its exact tenant-role operation"))); + Optional tenantRoleEvidence = + tenantRoleOperationRepository.findCurrentMemberEvidenceForUpdate( + identity.accountUuid(), identity.tenantUuid(), verified.requestId()); + MembershipTransitionReceipt transitionReceipt; + boolean currentTransitionInvalidated; + if (tenantRoleEvidence.isPresent()) { + CurrentMemberEvidence exactRoleEvidence = tenantRoleEvidence.orElseThrow(); requireExactCurrentTenantRoleEvidence( - tenantRoleEvidence.orElseThrow(), membership, roles, event, verified, identity); + exactRoleEvidence, membership, roles, event, verified, identity); + currentTransitionInvalidated = exactRoleEvidence.member().callerBoundAuthorityInvalidated(); + requireCurrentMembershipEvent( + identity, + membership.membershipId(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + roles, + verified.requestId(), + currentTransitionInvalidated, + authoritySnapshot); + + TransitionReceiptEvidence historicalReceipt = + transitionReceiptRepository + .findLatestHistoricalReceipt(accountId, legacyTenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership has no historical lifecycle receipt")); + requireHistoricalMembershipJoinReceipt(historicalReceipt, membership, event); + transitionReceipt = historicalReceipt.receipt(); + } else { + transitionReceipt = + transitionReceiptRepository + .findLatestReceipt(accountId, legacyTenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership has no positive transition receipt")); + if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, legacyTenantId) + .equals(transitionReceipt.receiptStreamKey()) + || transitionReceipt.receiptSequence() <= 0L + || transitionReceipt.receiptId() == null + || transitionReceipt.receiptDigest() == null + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals( + transitionReceipt.evidenceStatus()) + || (!"MEMBERSHIP_JOINED".equals(transitionReceipt.transitionType()) + && !"MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType())) + || transitionReceipt.requestId() == null + || transitionReceipt.requestId().isBlank() + || transitionReceipt.membershipId() != membership.membershipId() + || !transitionReceipt.requestId().equals(verified.requestId())) { + throw new IllegalStateException( + "Current Account membership transition receipt is incomplete or mismatched"); + } + currentTransitionInvalidated = + "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()); + requireCurrentMembershipEvent( + identity, + membership.membershipId(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + roles, + transitionReceipt.requestId(), + currentTransitionInvalidated, + authoritySnapshot); } - boolean currentTransitionInvalidated = - tenantRoleEvidence - .map(evidence -> evidence.member().callerBoundAuthorityInvalidated()) - .orElse("MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType())); - requireCurrentMembershipEvent( - identity, - membership.membershipId(), - membership.lifecycleState(), - membership.gameplayAdmissionAllowed(), - membership.membershipVersion(), - membership.membershipAuthorityGeneration(), - membership.authorityProvenance(), - roles, - tenantRoleEvidence.isPresent() ? null : transitionReceipt.requestId(), - currentTransitionInvalidated, - authoritySnapshot); List checkpoints = new ArrayList<>(currentSources.checkpoints()); checkpoints.add( @@ -307,6 +328,40 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( tenantRoleEvidence.map(CurrentMemberEvidence::operation)); } + private void requireHistoricalMembershipJoinReceipt( + TransitionReceiptEvidence evidence, JoinMembershipProof membership, Event currentRoleEvent) { + MembershipTransitionReceipt receipt = evidence.receipt(); + if (evidence.accountId() != membership.accountId() + || evidence.tenantId() != membership.tenantId() + || !MembershipTransitionReceiptDigest.receiptStreamKey( + membership.accountId(), membership.tenantId()) + .equals(receipt.receiptStreamKey()) + || receipt.receiptSequence() <= 0L + || receipt.receiptId() == null + || receipt.receiptDigest() == null + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + || (!"MEMBERSHIP_JOINED".equals(receipt.transitionType()) + && !"MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())) + || receipt.requestId() == null + || receipt.requestId().isBlank() + || receipt.requestId().equals(currentRoleEvent.requestId()) + || currentRoleEvent.outboxSequence() <= 1L + || receipt.membershipId() != membership.membershipId() + || !"ACTIVE".equals(evidence.lifecycleState()) + || !evidence.gameplayAdmissionAllowed() + || evidence.membershipVersion() <= 0L + || evidence.membershipVersion() >= membership.membershipVersion() + || evidence.membershipAuthorityGeneration() <= 0L + || evidence.membershipAuthorityGeneration() > membership.membershipAuthorityGeneration() + || !"EXPLICIT_JOIN".equals(evidence.authorityProvenance()) + || !"ACTIVE".equals(membership.lifecycleState()) + || !membership.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.authorityProvenance())) { + throw new IllegalStateException( + "Current Account role event has no exact prior explicit-membership lifecycle receipt"); + } + } + private void requireExactCurrentTenantRoleEvidence( CurrentMemberEvidence evidence, JoinMembershipProof membership, @@ -785,7 +840,7 @@ public RuntimeMembershipSnapshotDto readCurrentPairBoundInactiveMembershipSnapsh * *

This is membership evidence, not complete current authorization or terminal-recovery * eligibility. It never prepares, enrolls, initializes, or transitions membership authority. - * Fresh tenant associations currently have only non-admitting membership state and are denied; + * Fresh associations use the separate canonical first-JOIN path in the runtime snapshot reader; * retained membership must have complete exact current row, role, receipt, event, pair, and * generation/fence readback. Missing, inactive, incomplete, or contradictory state fails closed. */ @@ -1047,19 +1102,60 @@ public AccountMembershipCaptureSources readExistingRuntimeMembershipCaptureSourc Optional finalFreshAssociation = freshTenantIdentityAssociationRepository.read(tenantUuid); if (freshAssociation.isPresent()) { + FreshTenantCreationEvidence freshEvidence = freshAssociation.orElseThrow(); if (!freshAssociation.equals(finalFreshAssociation)) { throw new IllegalStateException( "Fresh Game Design tenant association changed during membership readback"); } - if (membershipSnapshot.membershipExists() - || !membershipSnapshot.roles().isEmpty() - || membershipRepository - .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) - .isPresent()) { - throw new IllegalStateException( - "Fresh tenant membership source contradicts its non-admitting baseline"); + Identity freshIdentity = + new Identity( + fencedAccount.getId(), + null, + accountUuid, + tenantUuid, + freshTenantProvenance(freshEvidence)); + Optional currentFreshMembership = + membershipRepository.findCanonicalMembershipForUpdate(accountUuid, tenantUuid); + if (membershipSnapshot.membershipExists()) { + AccountTenantMembership membership = + currentFreshMembership.orElseThrow( + () -> + new IllegalStateException( + "Fresh positive membership disappeared from its canonical UUID source")); + requireCanonicalMembershipIdentity(freshIdentity, membership); + if (!Objects.equals(membership.getAccount().getId(), fencedAccount.getId())) { + throw new IllegalStateException( + "Fresh membership Account row differs from its locked private Account identity"); + } + RoleSnapshot exactFreshRoles = + roleSnapshotRepository + .findForCanonicalUpdate( + accountUuid, + tenantUuid, + freshIdentity.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow( + () -> + new IllegalStateException( + "Fresh positive membership role source is absent")); + requireCanonicalFirstJoinRoles(freshIdentity, membership, exactFreshRoles); + if (!List.of("player").equals(exactFreshRoles.roles())) { + throw new IllegalStateException( + "Fresh first-JOIN role source differs from its exact player-only authority"); + } + if (!exactFreshRoles.roles().equals(membershipSnapshot.roles())) { + throw new IllegalStateException( + "Fresh role source differs from its exact membership snapshot"); + } + roleSource = Optional.of(exactFreshRoles); + } else { + if (currentFreshMembership.isPresent() || !membershipSnapshot.roles().isEmpty()) { + throw new IllegalStateException( + "Fresh non-admitting absence contradicts its canonical membership source"); + } + roleSource = Optional.empty(); } - roleSource = Optional.empty(); } else { if (finalFreshAssociation.isPresent() || !retainedAssociation.equals(tenantIdentityResolver.resolve(tenantUuid))) { @@ -1081,7 +1177,8 @@ public AccountMembershipCaptureSources readExistingRuntimeMembershipCaptureSourc authoritySnapshot, membershipSnapshot, roleSource, - Optional.ofNullable(retainedAssociation)); + Optional.ofNullable(retainedAssociation), + freshAssociation); } private Optional readExactExistingRoleSource( @@ -1205,15 +1302,40 @@ private RuntimeMembershipSnapshotDto readUuidRuntimeMembershipSnapshot( freshTenantIdentityAssociationRepository.read(tenantUuid); if (freshAssociation.isPresent()) { FreshTenantCreationEvidence evidence = freshAssociation.orElseThrow(); + if (!tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its canonical UUID scope"); + } + + Optional currentMembership = + membershipRepository.findCanonicalMembershipForUpdate(accountUuid, tenantUuid); + if (currentMembership.isPresent()) { + RuntimeMembershipSnapshotDto positive = + readCurrentFreshCanonicalPositiveMembershipSnapshot( + new Identity( + accountId, null, accountUuid, tenantUuid, freshTenantProvenance(evidence)), + currentMembership.orElseThrow()); + verifyExistingRuntimeSnapshotIdentity(positive, accountUuid, tenantUuid); + requireUnchangedAccountIdentity(initialAccount, accountUuid); + FreshTenantCreationEvidence finalAssociation = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Fresh Game Design tenant association disappeared during membership readback")); + if (!evidence.equals(finalAssociation)) { + throw new IllegalStateException( + "Fresh Game Design tenant association changed during membership readback"); + } + return positive; + } + if (readMode == MembershipSnapshotReadMode.ENROLL_IF_NEEDED) { NeverJoinedMembershipSnapshot absent = readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid); return toRuntimeMembershipSnapshot(absent); } - if (!tenantUuid.equals(evidence.canonicalTenantId())) { - throw new IllegalStateException( - "Fresh Game Design tenant association differs from its canonical UUID scope"); - } RuntimeMembershipSnapshotDto existing = readExistingFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, evidence); @@ -1282,6 +1404,13 @@ private RuntimeMembershipSnapshotDto readExistingFreshNeverJoinedMembershipSnaps UUID accountUuid, UUID tenantUuid, FreshTenantCreationEvidence evidence) { VerifiedTenantProvenance provenance = freshTenantProvenance(evidence); + if (membershipRepository + .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .isPresent()) { + throw new IllegalStateException( + "Fresh Account membership is not absent from its canonical UUID scope"); + } + // Preserve the source reader's canonical upstream lock order before inspecting the existing // pair. This path performs no initializer or enrollment call. CompositeSnapshot upstream = lockUpstreamAuthorityScopes(accountUuid, tenantUuid); @@ -1295,6 +1424,235 @@ private RuntimeMembershipSnapshotDto readExistingFreshNeverJoinedMembershipSnaps assembleNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, provenance)); } + /** + * Reads a committed first canonical JOIN from its exact V2 receipt, terminal operation, audit, + * current event/checkpoint, pair, roles, and authority sources. No source is inferred from the + * membership row or used to repair a missing pair. + */ + private RuntimeMembershipSnapshotDto readCurrentFreshCanonicalPositiveMembershipSnapshot( + Identity identity, AccountTenantMembership membership) { + requireWritableOwnerTransaction(); + requireCanonicalMembershipIdentity(identity, membership); + if (membership.getMembershipVersion() != 2L + || membership.getMembershipAuthorityGeneration() != 1L) { + throw new IllegalStateException( + "Fresh Account membership is not the exact first canonical JOIN state"); + } + + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + identity.accountUuid(), + identity.tenantUuid(), + identity.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN role snapshot is absent")); + requireCanonicalFirstJoinRoles(identity, membership, roles); + List exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + + CanonicalMembershipTransitionReceipt receipt = + transitionReceiptRepository + .findLatestCanonicalReceipt(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN V2 receipt is absent")); + requireFreshCanonicalJoinReceipt(identity, membership, receipt); + + CanonicalJoinOperationEvidence operation = + joinOperationRepository + .findCanonicalEvidenceByRequestId(receipt.requestId()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN V2 operation is absent")); + requireFreshCanonicalJoinOperation(identity, membership, receipt, operation); + requireFreshCanonicalJoinAudit(identity, operation); + + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN pair authority is absent")); + String streamKey = membershipStreamKey(identity); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN event checkpoint is absent")); + Event event = + authorityOutboxRepository + .findEvent(streamKey, checkpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN checkpoint has no event")); + if (checkpoint.outboxSequence() != 1L + || !checkpointMatches(checkpoint, event) + || !receipt.requestId().equals(event.requestId())) { + throw new IllegalStateException( + "Fresh canonical JOIN checkpoint is not its exact first membership event"); + } + MembershipEvent verified = verifyStoredEvent(event, identity, receipt.requestId()); + Map exactMembershipVersion = + Map.of(identity.tenantUuid().toString(), Long.toString(membership.getMembershipVersion())); + if (!"ACTIVE".equals(verified.membershipLifecycleState()) + || !verified.gameplayAdmissionAllowed() + || !exactMembershipVersion.equals(verified.membershipVersion()) + || !"1".equals(verified.membershipAuthorityGeneration()) + || !exactRoles.equals(verified.roles()) + || verified.callerBoundAuthorityInvalidated() + || !pair.equals( + new PairAuthority( + identity.accountUuid(), + identity.tenantUuid(), + identity.provenance(), + true, + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + 1L, + event.eventId(), + event.eventDigest(), + false))) { + throw new IllegalStateException( + "Fresh canonical JOIN event or pair differs from its exact positive membership"); + } + + CompositeSnapshot authority = readSnapshot(identity); + ScopeState membershipAuthority = only(authority.memberships(), "membership"); + requireMatchingFence(authority, membershipAuthority, identity.accountUuid()); + if (membershipAuthority.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Fresh canonical JOIN differs from its current membership authority generation"); + } + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence(identity.accountUuid(), identity.tenantUuid(), authority); + requireCurrentMembershipEvent( + identity, + membership.getId(), + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance(), + roles, + receipt.requestId(), + false, + authority); + + List checkpoints = new ArrayList<>(currentSources.checkpoints()); + checkpoints.add( + new OutboxCheckpointEntry(streamKey, Long.toString(checkpoint.outboxSequence()))); + List sourceEvidence = new ArrayList<>(currentSources.sourceEvidence()); + sourceEvidence.add(sourceEvidence(checkpoint, event)); + return new RuntimeMembershipSnapshotDto( + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + true, + true, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + membership.getLifecycleState(), + exactMembershipVersion, + Long.toString(membership.getMembershipAuthorityGeneration())), + exactRoles, + currentAuthorityTuple(identity.tenantUuid(), authority, currentSources), + decimal(authority.issuanceFence().value()), + Instant.now(), + orderedCheckpoints(checkpoints), + orderedSourceEvidence(sourceEvidence), + verified); + } + + private void requireFreshCanonicalJoinReceipt( + Identity identity, + AccountTenantMembership membership, + CanonicalMembershipTransitionReceipt receipt) { + if (receipt.receiptSequence() != 1L + || !identity.accountUuid().equals(receipt.accountId()) + || !identity.tenantUuid().equals(receipt.tenantId()) + || !"MEMBERSHIP_JOINED".equals(receipt.transitionType()) + || !"ACTIVE".equals(receipt.membershipLifecycleState()) + || !receipt.gameplayAdmissionAllowed() + || !Map.of(identity.tenantUuid().toString(), "2").equals(receipt.membershipVersion()) + || receipt.membershipAuthorityGeneration() != 1L + || !"EXPLICIT_JOIN".equals(receipt.authorityProvenance()) + || !TenantProvenanceKind.FRESH_GAME_DESIGN.name().equals(receipt.tenantProvenanceKind()) + || !identity.provenance().sourceOperationId().equals(receipt.tenantSourceOperationId()) + || !identity.provenance().digest().equals(receipt.tenantProvenanceDigest()) + || membership.getMembershipVersion() != 2L) { + throw new IllegalStateException( + "Fresh canonical JOIN V2 receipt differs from its exact current membership"); + } + } + + private void requireFreshCanonicalJoinOperation( + Identity identity, + AccountTenantMembership membership, + CanonicalMembershipTransitionReceipt receipt, + CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + if (!receipt.requestId().equals(operation.requestId()) + || operation.privateAccountId() != identity.accountId() + || operation.operationRepresentationVersion() != 2 + || operation.scopeDigestVersion() != 2 + || operation.intentDigestVersion() != 2 + || !"COMMITTED".equals(operation.status()) + || !"JOINED".equals(operation.outcome()) + || !Objects.equals(operation.membershipId(), membership.getId()) + || !Objects.equals(operation.membershipVersion(), membership.getMembershipVersion()) + || !Objects.equals( + operation.membershipAuthorityGeneration(), + membership.getMembershipAuthorityGeneration()) + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0L + || !Integer.valueOf(2).equals(operation.requestDigestVersion()) + || operation.requestDigest() == null + || operation.requestDigest().isBlank() + || !"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || !identity.accountUuid().equals(scope.accountUuid()) + || !identity.tenantUuid().equals(scope.tenantUuid()) + || scope.privateAccountId() != identity.accountId() + || !identity.provenance().equals(scope.tenantProvenance())) { + throw new IllegalStateException( + "Fresh canonical JOIN operation or available policy differs from its exact receipt"); + } + } + + private void requireFreshCanonicalJoinAudit( + Identity identity, CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + UUID expectedAuditId = joinAuditEventId(operation.requestId()); + AccountAuditEnvelope envelope = + auditOutboxRepository + .findCanonicalJoinEnvelopeForUpdate(expectedAuditId, identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Fresh canonical JOIN audit envelope is absent")); + String expectedPayload = + AccountAuditOutboxRepository.canonicalJoinPayload( + identity.accountUuid(), + identity.tenantUuid(), + scope.worldSlug(), + scope.realmSlug(), + Map.of(identity.tenantUuid().toString(), "2"), + operation.requestId()); + if (envelope.payload() == null + || envelope.schemaVersion() != 1 + || envelope.payloadDigestVersion() != 1 + || !AccountAuditDigest.isValid(envelope.payloadDigest()) + || !envelope.payloadDigest().equals(AccountAuditDigest.ofPayload(envelope.payload())) + || !expectedAuditId.equals(envelope.auditEventId()) + || !expectedPayload.equals(envelope.payload())) { + throw new IllegalStateException( + "Fresh canonical JOIN audit envelope differs from its exact operation"); + } + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + private RuntimeMembershipSnapshotDto readExistingRetainedRuntimeMembershipSnapshot( long accountId, long legacyTenantId) { Optional currentMembership = @@ -1467,6 +1825,12 @@ public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot( throw new IllegalStateException( "Fresh Game Design tenant association differs from its canonical UUID scope"); } + if (membershipRepository + .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .isPresent()) { + throw new IllegalStateException( + "Fresh Account membership is not absent from its canonical UUID scope"); + } VerifiedTenantProvenance provenance = new VerifiedTenantProvenance( null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java index 3ea5238f1b..3acce1e3db 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java @@ -20,14 +20,22 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; @@ -99,6 +107,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private AccountCanonicalJoinReconciliationService reconciliationService; @Autowired private AccountMembershipAuthorityEventProducer membershipEventProducer; @Autowired private AccountAuthorityGenerationRepository generations; + @Autowired private AccountAuthorityOutboxRepository authorityOutbox; + @Autowired private AccountMembershipPairAuthorityRepository pairAuthorities; @Autowired private AccountConnectScopeRepository connectScopes; @Autowired private AccountJoinOperationRepository joinOperations; @Autowired private AccountRepository accounts; @@ -138,6 +148,183 @@ void completeHistoricalReadbackCommitsAfterExpiryAndLaterUnavailablePolicyAttemp assertThat(issuanceFence(fixture.account().accountUuid())).isEqualTo(fenceBefore); } + @Test + void committedFreshUuidJoinReturnsExactPositiveSnapshotAndCaptureWithoutChangingSources() { + // This fixture proves persisted Account-owner composition only. Its caller binding is synthetic + // and does not exercise or claim an authenticated JOIN producer. + JoinFixture fixture = committedFreshJoinFixture(); + EvidenceCounts before = evidenceCounts(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + long fenceBefore = issuanceFence(fixture.account().accountUuid()); + FreshTenantCreationEvidence freshSource = + inTransaction(() -> freshAssociations.read(fixture.tenantUuid()).orElseThrow()); + + RuntimeMembershipSnapshotDto existingOnly = + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid())); + RuntimeMembershipSnapshotDto enrollMode = + inTransaction( + () -> + membershipEventProducer.readRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid())); + AccountMembershipCaptureSources capturedSources = + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipCaptureSources( + fixture.account().accountUuid(), fixture.tenantUuid())); + + assertThat(existingOnly.membershipExists()).isTrue(); + assertThat(existingOnly.gameplayAdmissionAllowed()).isTrue(); + assertThat(existingOnly.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(existingOnly.membershipBaseline().membershipVersion()) + .containsExactly(Map.entry(fixture.tenantUuid().toString(), "2")); + assertThat(existingOnly.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(existingOnly.roles()).contains("player"); + assertThat(existingOnly.requireConsistentSourceEvent().outboxSequence()).isEqualTo("1"); + assertThat(enrollMode.membershipBaseline()).isEqualTo(existingOnly.membershipBaseline()); + assertThat(enrollMode.roles()).isEqualTo(existingOnly.roles()); + assertThat(enrollMode.sourceEvent().canonicalJson()) + .isEqualTo(existingOnly.sourceEvent().canonicalJson()); + assertThat(capturedSources.membershipSnapshot().membershipExists()).isTrue(); + assertThat(capturedSources.membershipSnapshot().sourceEvent().canonicalJson()) + .isEqualTo(existingOnly.sourceEvent().canonicalJson()); + assertThat(capturedSources.freshTenantAssociation()).contains(freshSource); + assertThat(capturedSources.retainedTenantAssociation()).isEmpty(); + var capturedRole = capturedSources.roleSource().orElseThrow(); + assertThat(capturedRole.accountId()).isEqualTo(fixture.account().accountId()); + assertThat(capturedRole.accountUuid()).isEqualTo(fixture.account().accountUuid()); + assertThat(capturedRole.membershipId()).isEqualTo(readOperation(fixture).membershipId()); + assertThat(capturedRole.tenantId()).isNull(); + assertThat(capturedRole.tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(capturedRole.tenantProvenance()) + .isEqualTo( + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + freshSource.operationId(), + freshSource.evidenceDigest())); + assertThat(capturedRole.snapshotVersion()).isEqualTo(2L); + assertThat(capturedRole.roles()).isEqualTo(existingOnly.roles()); + assertThat(capturedSources.authoritySnapshot().memberships().getFirst().generation()) + .isEqualTo(1L); + assertThat(capturedSources.authoritySnapshot().memberships().getFirst().sourceVersion()) + .isEqualTo(1L); + assertThat(capturedSources.membershipSnapshot().outboxCheckpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(eventStreamKey(fixture)); + assertThat(checkpoint.outboxSequence()).isEqualTo("1"); + }); + assertThat(capturedSources.membershipSnapshot().outboxSourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.outboxStreamKey()).isEqualTo(eventStreamKey(fixture)); + assertThat(source.outboxSequence()).isEqualTo("1"); + }); + assertThat(evidenceCounts(fixture)).isEqualTo(before); + assertThat(pairAuthority(fixture)).isEqualTo(pairBefore); + assertThat(issuanceFence(fixture.account().accountUuid())).isEqualTo(fenceBefore); + } + + @Test + void existingOnlyFreshUuidReadPreservesProvedAbsenceAndPendingOperation() { + JoinFixture fixture = fixture(true); + EvidenceCounts before = evidenceCounts(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + + RuntimeMembershipSnapshotDto absent = + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid())); + + assertThat(absent.membershipExists()).isFalse(); + assertThat(absent.membershipBaseline().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(absent.membershipBaseline().membershipVersion()) + .containsExactly(Map.entry(fixture.tenantUuid().toString(), "1")); + assertThat(readOperation(fixture).status()).isEqualTo("PENDING"); + assertThat(evidenceCounts(fixture)).isEqualTo(before); + assertThat(pairAuthority(fixture)).isEqualTo(pairBefore); + } + + @Test + void pendingCanonicalJoinCannotAuthorizePositiveReadbackOrCauseMutation() { + JoinFixture fixture = fixture(true); + persistEvidence(fixture, EvidenceShape.COMPLETE); + EvidenceCounts before = evidenceCounts(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + + assertThatThrownBy( + () -> + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid()))) + .isInstanceOf(IllegalStateException.class); + + assertThat(readOperation(fixture).status()).isEqualTo("PENDING"); + assertThat(evidenceCounts(fixture)).isEqualTo(before); + assertThat(pairAuthority(fixture)).isEqualTo(pairBefore); + } + + @Test + void freshUuidReadRejectsContradictoryReceiptEventRolesPairAndAuditWithoutMutation() { + for (Contradiction contradiction : Contradiction.values()) { + JoinFixture fixture = committedFreshJoinFixture(); + introduceContradiction(fixture, contradiction); + EvidenceCounts before = evidenceCounts(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + + assertThatThrownBy( + () -> + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid()))) + .as(contradiction.name()) + .isInstanceOf(IllegalStateException.class); + + assertThat(evidenceCounts(fixture)).as(contradiction.name()).isEqualTo(before); + assertThat(pairAuthority(fixture)).as(contradiction.name()).isEqualTo(pairBefore); + } + } + + @Test + void existingOnlyFreshUuidReadRejectsWrongAccountAndTenantSources() { + JoinFixture fixture = committedFreshJoinFixture(); + PairAuthority pairBefore = pairAuthority(fixture); + AccountFixture otherAccount = accountFixture(); + UUID otherTenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence otherTenantSource = freshTenantEvidence(otherTenantUuid); + inTransaction( + () -> { + freshAssociations.importVerified(otherTenantSource); + generations.initializeTenantIfAbsent(otherTenantUuid); + return null; + }); + + // Neither different scope has its own durable absence baseline. Existing-only readback must + // deny rather than fabricate MISSING authority from an absent row or borrow the joined pair. + assertThatThrownBy( + () -> + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + otherAccount.accountUuid(), fixture.tenantUuid()))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + membershipEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.account().accountUuid(), otherTenantUuid))) + .isInstanceOf(IllegalStateException.class); + assertThat(evidenceCounts(fixture)).isEqualTo(new EvidenceCounts(1L, 1L, 1L, 1L)); + assertThat(pairAuthority(fixture)).isEqualTo(pairBefore); + } + @Test void eventReadbackRejectsStalePendingDtoAfterJournalHasTerminalized() { JoinFixture fixture = fixture(true); @@ -317,6 +504,88 @@ private JoinFixture fixture(Boolean allowPublicJoin) { return new JoinFixture(account, tenantUuid, provenance, scope, requestId, callerBinding); } + private JoinFixture committedFreshJoinFixture() { + JoinFixture fixture = fixture(true); + persistEvidence(fixture, EvidenceShape.COMPLETE); + recordLaterUnavailableAttempt(fixture); + reconciliationService.reconcileDueOperations(reconciliationTime(fixture)); + assertThat(readOperation(fixture).status()).isEqualTo("COMMITTED"); + return fixture; + } + + private void introduceContradiction(JoinFixture fixture, Contradiction contradiction) { + switch (contradiction) { + case LATEST_RECEIPT -> + inTransactionWithoutResult( + () -> + receipts.appendCanonicalTransition( + fixture.account().accountUuid(), + fixture.tenantUuid(), + "MEMBERSHIP_JOINED", + UUID.randomUUID().toString())); + case LATEST_EVENT -> + inTransactionWithoutResult( + () -> { + String stream = eventStreamKey(fixture); + Event current = + authorityOutbox + .readCheckpoint(stream) + .flatMap( + checkpoint -> + authorityOutbox.findEvent(stream, checkpoint.outboxSequence())) + .orElseThrow(); + authorityOutbox.append( + stream, + "unmatched-current-event-" + UUID.randomUUID(), + ignoredSequence -> + new EventEvidence( + UUID.randomUUID().toString(), + "sha256:" + "0".repeat(64), + current.payload())); + }); + case CURRENT_ROLES -> + inTransactionWithoutResult( + () -> { + AccountTenantMembership membership = + memberships + .findCanonicalMembershipForUpdate( + fixture.account().accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + roleSnapshots.replaceCanonical( + membership, + fixture.account().accountUuid(), + fixture.tenantUuid(), + fixture.provenance(), + membership.getMembershipVersion(), + List.of("player", "moderator")); + }); + case PAIR -> + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = membership_version + 1, " + + "last_event_sequence = last_event_sequence + 1, last_event_id = ?, " + + "last_event_digest = ? WHERE account_uuid = ? AND tenant_uuid = ?", + "unmatched-pair-event-" + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + fixture.account().accountUuid(), + fixture.tenantUuid()); + case AUDIT -> { + String contradictoryPayload = + AccountAuditOutboxRepository.canonicalJoinPayload( + UUID.randomUUID(), + fixture.tenantUuid(), + fixture.scope().worldSlug(), + fixture.scope().realmSlug(), + Map.of(fixture.tenantUuid().toString(), "2"), + fixture.requestId()); + dsl.execute( + "UPDATE account_audit_outbox SET payload = ?, payload_digest = ? WHERE audit_event_id = ?", + contradictoryPayload, + AccountAuditDigest.ofPayload(contradictoryPayload), + auditEventId(fixture.requestId())); + } + } + } + private void persistEvidence(JoinFixture fixture, EvidenceShape shape) { inTransactionWithoutResult( () -> { @@ -466,6 +735,14 @@ private CanonicalJoinOperationEvidence readOperation(JoinFixture fixture) { () -> joinOperations.findCanonicalEvidenceByRequestId(fixture.requestId()).orElseThrow()); } + private PairAuthority pairAuthority(JoinFixture fixture) { + return inTransaction( + () -> + pairAuthorities + .readForUpdate(fixture.account().accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + } + private long membershipId(JoinFixture fixture) { return Objects.requireNonNull( dsl.resultQuery( @@ -565,6 +842,14 @@ private record JoinFixture( private record EvidenceCounts(long memberships, long events, long receipts, long audits) {} + private enum Contradiction { + LATEST_RECEIPT, + LATEST_EVENT, + CURRENT_ROLES, + PAIR, + AUDIT + } + private record Case(String description, Boolean allowPublicJoin, EvidenceShape evidenceShape) {} private enum EvidenceShape { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java index 03a9f135c7..6584998545 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java @@ -684,7 +684,8 @@ void existingCaptureSourcesAuthenticateAbsenceAndRejectMixedSourceOrRoleEvidence authority.issuanceFence()), absence.membershipSnapshot(), absence.roleSource(), - absence.retainedTenantAssociation())) + absence.retainedTenantAssociation(), + absence.freshTenantAssociation())) .isInstanceOf(IllegalArgumentException.class); JoinFixture active = fixture(); @@ -750,7 +751,8 @@ void existingCaptureSourcesAuthenticateAbsenceAndRejectMixedSourceOrRoleEvidence existing.authoritySnapshot(), existing.membershipSnapshot(), Optional.of(mixedRoleHeader), - existing.retainedTenantAssociation())) + existing.retainedTenantAssociation(), + existing.freshTenantAssociation())) .isInstanceOf(IllegalArgumentException.class); assertThat(membershipAuthoritySourceFingerprint(active)).isEqualTo(activeBeforeRead); } 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 da434d3d57..a71e05c953 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 @@ -704,7 +704,8 @@ void contradictoryLatestEventDeniesLeftWithoutMembershipOrOutboxMutation() { assertThatThrownBy(() -> leave(fixture, "leave-contradictory-" + UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("receipt differs from its latest V33 event"); + .hasMessageContaining( + "Current Account membership transition receipt is incomplete or mismatched"); assertThat(membershipSnapshot(fixture)).isEqualTo(membershipBefore); assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairBefore); @@ -1636,6 +1637,48 @@ void tenantRoleMutationCommitsGrantRevokeTransferAndReplaysOriginalGrantAfterLat OperationEvidence grant = tenantRoleMutationService.mutate(grantRequest); assertThat(grant.status()).isEqualTo("COMMITTED"); assertThat(grant.members()).hasSize(1); + + MembershipTransitionReceipt originalJoinReceipt = + membershipTransitionReceipt(fixture.target(), 1L); + Map targetBeforeHistoricalReceiptReads = + membershipAuthorityReadEvidenceSnapshot(fixture.target()); + long auditRowsBeforeHistoricalReceiptReads = countAuditOutboxRows(fixture.target()); + assertThatThrownBy( + () -> + membershipTransitionReceiptRepository.findLatestReceipt( + fixture.target().accountId(), fixture.target().tenantId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match its latest provisional receipt"); + + var historicalReceiptEvidence = + Objects.requireNonNull( + new TransactionTemplate(transactionManager) + .execute( + status -> + membershipTransitionReceiptRepository + .findLatestHistoricalReceipt( + fixture.target().accountId(), fixture.target().tenantId()) + .orElseThrow())); + assertThat(historicalReceiptEvidence.receipt()).isEqualTo(originalJoinReceipt); + assertThat(historicalReceiptEvidence.accountId()).isEqualTo(fixture.target().accountId()); + assertThat(historicalReceiptEvidence.tenantId()).isEqualTo(fixture.target().tenantId()); + assertThat(historicalReceiptEvidence.lifecycleState()).isEqualTo("ACTIVE"); + assertThat(historicalReceiptEvidence.gameplayAdmissionAllowed()).isTrue(); + assertThat(historicalReceiptEvidence.membershipVersion()).isEqualTo(2L); + assertThat(historicalReceiptEvidence.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(historicalReceiptEvidence.authorityProvenance()).isEqualTo("EXPLICIT_JOIN"); + + PositiveMembershipSnapshot afterRoleGrant = + readExistingPairBoundPositiveMembershipSnapshot(fixture.target()); + assertThat(afterRoleGrant.membershipVersion()) + .isEqualTo(Map.of(fixture.target().tenantUuid().toString(), "3")); + assertThat(afterRoleGrant.roles()).containsExactly("designer", "player"); + assertThat(afterRoleGrant.authorityEvent().outboxSequence()).isEqualTo("2"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture.target())) + .isEqualTo(targetBeforeHistoricalReceiptReads); + assertThat(countAuditOutboxRows(fixture.target())) + .isEqualTo(auditRowsBeforeHistoricalReceiptReads); + assertCurrentRoleMutationState( fixture.target(), 3L, 1L, 2L, 1L, List.of("designer", "player"), false); assertCurrentRoleMutationState( @@ -1855,8 +1898,24 @@ void tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSour new TransactionTemplate(transactionManager) .execute( status -> { - seedSyntheticRetainedActiveMembership( - fixture, List.of("player", "tenantAdmin"), "SEEDED_DEMO"); + seedSyntheticRetainedActiveMembership(fixture, List.of("player", "tenantAdmin")); + ApprovedAssociation association = + tenantIdentityResolver.resolve(fixture.tenantUuid()); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + // The transition-receipt contract accepts explicit joins, so install the unsupported + // source only after creating that valid historical receipt. + membership.setAuthorityProvenance("SEEDED_DEMO"); + membershipRepository.saveCanonical( + membership, fixture.accountUuid(), fixture.tenantUuid(), provenance); return null; }); Map sourceBefore = membershipAuthorityReadEvidenceSnapshot(fixture); @@ -1874,7 +1933,8 @@ void tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSour Action.GRANT_DESIGNER, 2L, 2L))) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match its latest V1 provisional receipt"); assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); assertTenantRoleOperationAbsent(requestId); @@ -1882,12 +1942,12 @@ void tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSour @Test void invalidatingTenantRoleMutationDeniesFenceOverflowWithoutChangingAnyAccountSource() { - JoinFixture fixture = fixture("active"); + JoinFixture fixture = fixture("active", TenantAssociationSetup.APPROVED, Long.MAX_VALUE); new TransactionTemplate(transactionManager) .execute( status -> { seedSyntheticRetainedActiveMembership( - fixture, List.of("designer", "player", "tenantAdmin"), "EXPLICIT_JOIN", true); + fixture, List.of("designer", "player", "tenantAdmin")); return null; }); PositiveMembershipSnapshot current = readExistingPairBoundPositiveMembershipSnapshot(fixture); @@ -2879,6 +2939,13 @@ private JoinFixture fixture(String subscriptionStatus) { } private JoinFixture fixture(String subscriptionStatus, TenantAssociationSetup associationSetup) { + return fixture(subscriptionStatus, associationSetup, 1L); + } + + private JoinFixture fixture( + String subscriptionStatus, + TenantAssociationSetup associationSetup, + long initialIssuanceFence) { String suffix = UUID.randomUUID().toString(); long accountId = Objects.requireNonNull( @@ -2893,7 +2960,7 @@ private JoinFixture fixture(String subscriptionStatus, TenantAssociationSetup as Objects.requireNonNull( dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) .fetchOne(0, UUID.class)); - seedAccountAuthorityState(accountUuid); + seedAccountAuthorityState(accountUuid, initialIssuanceFence); return fixture(subscriptionStatus, accountId, accountUuid, associationSetup, suffix); } @@ -2981,11 +3048,7 @@ private JoinFixture fixtureForSecondAccountInTenant(JoinFixture existing) { dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) .fetchOne(0, UUID.class)); seedAccountAuthorityState(accountUuid); - dsl.execute( - "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) " - + "VALUES (?, ?, 'join-proof', 'active', 1)", - accountId, - existing.tenantId()); + // Entitlements are tenant-scoped; the existing fixture already seeded the sole subscription. DirectTextCallerContext caller = new DirectTextCallerContext( accountId, @@ -3045,19 +3108,6 @@ private TenantRoleFixture syntheticRetainedAdminFixture() { } private void seedSyntheticRetainedActiveMembership(JoinFixture fixture, List roles) { - seedSyntheticRetainedActiveMembership(fixture, roles, "EXPLICIT_JOIN"); - } - - private void seedSyntheticRetainedActiveMembership( - JoinFixture fixture, List roles, String authorityProvenance) { - seedSyntheticRetainedActiveMembership(fixture, roles, authorityProvenance, false); - } - - private void seedSyntheticRetainedActiveMembership( - JoinFixture fixture, - List roles, - String authorityProvenance, - boolean exhaustedIssuanceFence) { Account account = accountRepository.findByAccountUuidForUpdate(fixture.accountUuid()).orElseThrow(); ApprovedAssociation association = tenantIdentityResolver.resolve(fixture.tenantUuid()); @@ -3083,7 +3133,7 @@ private void seedSyntheticRetainedActiveMembership( membership.setLifecycleState("ACTIVE"); membership.setMembershipVersion(2L); membership.setMembershipAuthorityGeneration(1L); - membership.setAuthorityProvenance(authorityProvenance); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); AccountTenantMembership persisted = membershipRepository.saveCanonical( membership, fixture.accountUuid(), fixture.tenantUuid(), provenance); @@ -3097,16 +3147,6 @@ private void seedSyntheticRetainedActiveMembership( persisted, "MEMBERSHIP_JOINED", historicalRequestId); assertThat(receipt.requestId()).isEqualTo(historicalRequestId); - if (exhaustedIssuanceFence) { - assertThat( - dsl.execute( - "UPDATE account_authority_issuance_fences SET issuance_fence = ? " - + "WHERE account_uuid = ?", - Long.MAX_VALUE, - fixture.accountUuid())) - .isEqualTo(1); - } - var authority = authorityGenerationRepository.readCompositeSnapshot( AccountServiceImpl.ACCOUNT_JWT_ISSUER, @@ -3393,6 +3433,10 @@ private void seedRetainedV26TenantEvidence(long tenantId, String suffix) { } private void seedAccountAuthorityState(UUID accountUuid) { + seedAccountAuthorityState(accountUuid, 1L); + } + + private void seedAccountAuthorityState(UUID accountUuid, long initialIssuanceFence) { dsl.execute( "INSERT INTO account_authority_generations " + "(scope_kind, account_uuid, generation, source_version) " @@ -3400,8 +3444,10 @@ private void seedAccountAuthorityState(UUID accountUuid) { accountUuid); dsl.execute( "INSERT INTO account_authority_issuance_fences " - + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", - accountUuid); + + "(account_uuid, issuance_fence, source_version) VALUES (?, ?, ?)", + accountUuid, + initialIssuanceFence, + initialIssuanceFence); } private void seedTenantAuthorityGeneration(UUID tenantUuid) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java index b06623c8bb..7402c90ac5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java @@ -22,6 +22,8 @@ import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; class AccountMembershipCaptureSourcesTest { @@ -51,6 +53,7 @@ void retainsExactLockedScopeVersionsRoleHeaderEventAndFenceImmutably() { assertThat(sources.roleSource().orElseThrow().tenantUuid()).isNull(); assertThat(sources.roleSource().orElseThrow().tenantProvenance()).isNull(); assertThat(sources.retainedTenantAssociation()).contains(fixture.tenantAssociation()); + assertThat(sources.freshTenantAssociation()).isEmpty(); assertThat(sources.roleSource().orElseThrow().snapshotVersion()).isEqualTo(2L); assertThatThrownBy(() -> sources.membershipSnapshot().outboxCheckpoints().clear()) @@ -89,6 +92,126 @@ void retainsOnlyAuthenticatedNonadmittingSequenceZeroAbsence() { .equals(membershipStream(fixture.accountUuid(), fixture.tenantUuid()))); assertThat(sources.membershipSnapshot().sourceEvent()).isNull(); assertThat(sources.roleSource()).isEmpty(); + assertThat(sources.retainedTenantAssociation()).isEmpty(); + assertThat(sources.freshTenantAssociation()).contains(fixture.freshTenantAssociation()); + } + + @Test + void retainsExactFreshSourceReceiptAndCanonicalRoleHeaderWithoutTreatingThemAsAuthorization() { + CaptureFixture fixture = freshActiveFixture(); + AccountMembershipCaptureSources sources = fixture.sources(); + RoleSnapshot role = sources.roleSource().orElseThrow(); + + assertThat(sources.freshTenantAssociation()).contains(fixture.freshTenantAssociation()); + assertThat(sources.retainedTenantAssociation()).isEmpty(); + assertThat(role.accountId()).isEqualTo(41L); + assertThat(role.accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(role.tenantId()).isNull(); + assertThat(role.tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(role.tenantProvenance()) + .isEqualTo( + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + fixture.freshTenantAssociation().operationId(), + fixture.freshTenantAssociation().evidenceDigest())); + assertThat(role.membershipId()).isEqualTo(33L); + assertThat(role.snapshotVersion()).isEqualTo(2L); + assertThat(role.roles()).containsExactly("player"); + assertThat(sources.membershipSnapshot().sourceEvent().canonicalJson()) + .isEqualTo(fixture.event().canonicalJson()); + } + + @Test + void rejectsFreshSourceReceiptAndRoleHeaderSubstitutionsOrMissingProvenance() { + CaptureFixture fixture = freshActiveFixture(); + FreshTenantCreationEvidence evidence = fixture.freshTenantAssociation(); + + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.empty(), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exactly one"); + + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(activeFixture().tenantAssociation()), + Optional.of(evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exactly one"); + + FreshTenantCreationEvidence wrongTenant = + copyFreshEvidence(evidence, UUID.randomUUID(), UUID.randomUUID()); + assertThatThrownBy(() -> freshSources(fixture, fixture.roleSource(), wrongTenant)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical request"); + + FreshTenantCreationEvidence wrongOperation = + copyFreshEvidence(evidence, evidence.canonicalTenantId(), UUID.randomUUID()); + assertThatThrownBy(() -> freshSources(fixture, fixture.roleSource(), wrongOperation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact UUID source receipt"); + + VerifiedTenantProvenance wrongDigestProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + "sha256:" + "9".repeat(64)); + RoleSnapshot wrongDigestHeader = + new RoleSnapshot( + fixture.roleSource().accountId(), + null, + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion(), + fixture.roleSource().roles(), + fixture.accountUuid(), + fixture.tenantUuid(), + wrongDigestProvenance); + assertThatThrownBy(() -> freshSources(fixture, wrongDigestHeader, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact UUID source receipt"); + + RoleSnapshot wrongHeaderVersion = + new RoleSnapshot( + fixture.roleSource().accountId(), + null, + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion() + 1L, + fixture.roleSource().roles(), + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.roleSource().tenantProvenance()); + assertThatThrownBy(() -> freshSources(fixture, wrongHeaderVersion, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("role header and identity"); + + RoleSnapshot wrongRoles = + new RoleSnapshot( + fixture.roleSource().accountId(), + null, + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion(), + List.of("moderator", "player"), + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.roleSource().tenantProvenance()); + assertThatThrownBy(() -> freshSources(fixture, wrongRoles, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("role header and identity"); } @Test @@ -104,7 +227,8 @@ void rejectsRequestScopeTupleSourceVersionCheckpointAndFenceMixes() { original, fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(fixture.tenantAssociation()))) + Optional.of(fixture.tenantAssociation()), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact canonical request"); @@ -129,7 +253,8 @@ void rejectsRequestScopeTupleSourceVersionCheckpointAndFenceMixes() { mixedTuple, fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(fixture.tenantAssociation()))) + Optional.of(fixture.tenantAssociation()), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authority generations or fence"); @@ -154,7 +279,8 @@ void rejectsRequestScopeTupleSourceVersionCheckpointAndFenceMixes() { mixedCheckpoint, fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(fixture.tenantAssociation()))) + Optional.of(fixture.tenantAssociation()), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("checkpoints differ"); @@ -175,7 +301,8 @@ void rejectsRequestScopeTupleSourceVersionCheckpointAndFenceMixes() { mixedFence, fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(fixture.tenantAssociation()))) + Optional.of(fixture.tenantAssociation()), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authority generations or fence"); } @@ -201,7 +328,8 @@ void rejectsMismatchedRoleHeaderAndMembershipEventCheckpoint() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(mixedRoleHeader), - Optional.of(fixture.tenantAssociation()))) + Optional.of(fixture.tenantAssociation()), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("role header and identity"); @@ -252,6 +380,7 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), + Optional.empty(), Optional.empty())) .isInstanceOf(IllegalArgumentException.class); @@ -270,7 +399,8 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(substitutedTenant))) + Optional.of(substitutedTenant), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); RoleSnapshot mismatchedAccountHeader = @@ -291,7 +421,8 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(mismatchedAccountHeader), - Optional.of(association))) + Optional.of(association), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); ApprovedAssociation wrongLegacyId = @@ -309,7 +440,8 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(fixture.roleSource()), - Optional.of(wrongLegacyId))) + Optional.of(wrongLegacyId), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); VerifiedTenantProvenance canonicalProvenance = @@ -335,7 +467,8 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(canonicalRoleHeader), - Optional.of(association))) + Optional.of(association), + Optional.empty())) .isNotNull(); ApprovedAssociation wrongProvenance = @@ -353,7 +486,8 @@ void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { fixture.authoritySnapshot(), fixture.membershipSnapshot(), Optional.of(canonicalRoleHeader), - Optional.of(wrongProvenance))) + Optional.of(wrongProvenance), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); } @@ -405,7 +539,14 @@ private CaptureFixture missingFixture() { null); checkpoints.clear(); return new CaptureFixture( - accountUuid, tenantUuid, authoritySnapshot, membershipSnapshot, null, null, null); + accountUuid, + tenantUuid, + authoritySnapshot, + membershipSnapshot, + null, + null, + null, + freshTenantEvidence(tenantUuid)); } private CaptureFixture activeFixture() { @@ -520,7 +661,107 @@ private CaptureFixture activeFixture() { membershipSnapshot, event, roleSource, - association); + association, + null); + } + + private CaptureFixture freshActiveFixture() { + CaptureFixture retained = activeFixture(); + FreshTenantCreationEvidence evidence = freshTenantEvidence(retained.tenantUuid()); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + RoleSnapshot retainedRole = retained.roleSource(); + RoleSnapshot freshRole = + new RoleSnapshot( + retainedRole.accountId(), + null, + retainedRole.membershipId(), + retainedRole.snapshotVersion(), + retainedRole.roles(), + retained.accountUuid(), + retained.tenantUuid(), + provenance); + return new CaptureFixture( + retained.accountUuid(), + retained.tenantUuid(), + retained.authoritySnapshot(), + retained.membershipSnapshot(), + retained.event(), + freshRole, + null, + evidence); + } + + private AccountMembershipCaptureSources freshSources( + CaptureFixture fixture, RoleSnapshot roleSource, FreshTenantCreationEvidence evidence) { + return new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(roleSource), + Optional.empty(), + Optional.of(evidence)); + } + + private FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String targetNamespace = "account-test-namespace"; + String sourceTenantKey = UUID.randomUUID().toString(); + long sourceGameRowId = 52L; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, sourceTenantKey, "Capture source fixture", null); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind); + return new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + evidenceDigest); + } + + private FreshTenantCreationEvidence copyFreshEvidence( + FreshTenantCreationEvidence source, UUID tenantUuid, UUID operationId) { + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + tenantUuid, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + tenantUuid, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); } private ApprovedAssociation copyAssociation( @@ -570,7 +811,8 @@ private record CaptureFixture( RuntimeMembershipSnapshotDto membershipSnapshot, MembershipAuthorityEventV1Codec.MembershipEvent event, RoleSnapshot roleSource, - ApprovedAssociation tenantAssociation) { + ApprovedAssociation tenantAssociation, + FreshTenantCreationEvidence freshTenantAssociation) { AccountMembershipCaptureSources sources() { return new AccountMembershipCaptureSources( accountUuid, @@ -578,7 +820,8 @@ AccountMembershipCaptureSources sources() { authoritySnapshot, membershipSnapshot, Optional.ofNullable(roleSource), - Optional.ofNullable(tenantAssociation)); + Optional.ofNullable(tenantAssociation), + Optional.ofNullable(freshTenantAssociation)); } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 1766245dc6..2789c0f1a0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -58,6 +58,29 @@ void canonicalFirstJoinRequiresWritableOwnerTransactionBeforeRepositoryReads() { } } + @Test + void existingUuidMembershipReadRequiresOwnerTransactionBeforeRepositoryReads() { + Repositories repositories = new Repositories(); + boolean previousActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean previousReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + try { + assertThatThrownBy( + () -> + repositories + .producer() + .readExistingRuntimeMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + repositories.verifyNoReads(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previousActive); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(previousReadOnly); + } + } + private static final class Repositories { private final AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); From f2242c536f33ec0b5372abfaa74d502e8c0b9278 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:55:22 +1300 Subject: [PATCH 3/6] Repair transactional spy harness and focused receipt-denial proof --- .../player-access-and-session.md | 2 + .../AccountJoinPostgresIntegrationTest.java | 52 +++++++++++++------ 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ca9a2d5f07..e267d056bc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The subsequent `214c6c9a875ce8f37f71891f89a95c1ac8cb85da` [CI37277059204](https://github.com/benhook1013/FireMUD/actions/runs/37277059204) Account job is terminal failure but proves progress: all eighteen required methods executed without skips, fourteen passed and four failed. Both immutable journal methods and all five new fresh-JOIN methods passed; seven of eleven retained-role methods passed. The full raw suites record JOIN 51/eight failures, journal two/zero failures and canonical reconciliation nine/zero failures. Three rollback tests failed during Mockito setup at a MANDATORY transaction proxy, leaving unfinished stubs that contaminated three later methods. One non-explicit denial assertion and one separate missing-receipt fixture also reached different valid guards than expected. The corrected rollback harness stubs the underlying Mockito spy while the actual mutation continues through its unchanged Spring transaction proxy. The missing-receipt fixture supplies coherent membership, roles, event, pair and authority sources and omits only the receipt; its no-mutation assertions remain. The corrected full Account check/JAR/analyzers/format/docs passes in 30s (72 tasks: 14 executed, 58 up-to-date), reusing the unchanged 943 clean unit results; all 349 integration cases remain locally skipped without Docker. Corrected harness PostgreSQL execution is still required. The source PR head/branch match the run, and artifact names identify merge SHA `9b0b39feeb14a4d947d828b4262eafd13794471c`; checkout succeeded, but its exact log/base evidence was unavailable while the aggregate remained active at observer handoff. Independently rehashed raw XML: JOIN `08aed57d0021d429ac4b9f882a1b5332459154aca4d7053cf75341b3d10775d8`, journal `8e2efcc9739e8fe3d2fd5d6f3964c6f3ec5f27eee9a36793e0455b6e2234b064`, canonical reconciliation `d2e02592abe76398feea58bcae0da5040e993e598da02077d1434f5c4d4b9b79`. This is executed component proof, not an authenticated public JOIN, complete authorization bundle, aggregate-green or activation claim. + Exact `b9e06f435a9832d5d520e1626f33e1fd5848f0d7` [CI37270614224](https://github.com/benhook1013/FireMUD/actions/runs/37270614224) supplies actual PostgreSQL execution, not passing proof: all thirteen required retained-role and journal methods executed with zero skips, three passed and ten failed. The JOIN suite executed 51 methods with nine failures, including one additional denial-message regression; the journal suite executed two methods with two failures. Six role tests failed while constructing entitlement-backed fixture state, the non-explicit and overflow setups violated unchanged owner guards, and the journal SQL bound `audit_occurred_at` as varchar instead of TIMESTAMPTZ. The Account job is terminal failure; the aggregate was still running at the observer handoff. Root independently parsed and hashed both raw suites (`82be9d4539a5c710a3fe1763c7616e85537c22be9bdb8df86b0291f21800a368` and `c45a5b48f208fc84abfedb47edd668703ec7af02227ce7a0c1b74f349550dbc0`). Corrected execution remains required; fixture repairs must preserve the production guards and no-mutation assertions. The Account reader correction adds exact positive readback for an already committed fresh-UUID first JOIN, rather than routing every fresh association through never-joined absence. It requires the committed V2 operation and policy, exact receipt and canonical audit, current role/event/pair evidence and complete source checkpoints; it performs no enrollment or mutation and rejects pending, contradictory or unsupported state. Retained role readback now proves its current immutable role journal/event/audit before using a historical lifecycle receipt. The ordinary JOIN receipt reader still rejects stale counters; role revocation may independently advance generation without rewriting that historical receipt. These are unwired component prerequisites, not authenticated JOIN, creator bootstrap or RPC activation. 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 a71e05c953..7ff58f77e4 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 @@ -91,6 +91,7 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -1768,12 +1769,14 @@ void tenantRoleMutationRollsBackAllSourcesWhenEventAppendFailsAfterWriting() { 2L, 2L); + AccountMembershipAuthorityEventProducer producerTarget = + AopTestUtils.getUltimateTargetObject(membershipAuthorityEventProducer); doAnswer( invocation -> { invocation.callRealMethod(); throw new IllegalStateException("injected failure after role event append"); }) - .when(membershipAuthorityEventProducer) + .when(producerTarget) .appendTenantRoleEvent( any(Request.class), any(AccountTenantMembership.class), @@ -1808,12 +1811,14 @@ void tenantRoleMutationRollsBackAllSourcesWhenAuditAppendFailsAfterWriting() { 2L, 2L); + AccountAuditOutboxRepository auditOutboxTarget = + AopTestUtils.getUltimateTargetObject(auditOutboxRepository); doAnswer( invocation -> { invocation.callRealMethod(); throw new IllegalStateException("injected failure after role audit append"); }) - .when(auditOutboxRepository) + .when(auditOutboxTarget) .appendCanonicalTenant(any(UUID.class), anyString(), anyString(), anyString()); assertThatThrownBy(() -> tenantRoleMutationService.mutate(request)) @@ -1844,6 +1849,8 @@ void tenantRoleMutationRollsBackAllSourcesWhenFinalCurrentReadbackFails() { 2L); AtomicInteger readbackCalls = new AtomicInteger(); + AccountMembershipAuthorityEventProducer producerTarget = + AopTestUtils.getUltimateTargetObject(membershipAuthorityEventProducer); doAnswer( invocation -> { PositiveMembershipSnapshot result = @@ -1853,7 +1860,7 @@ void tenantRoleMutationRollsBackAllSourcesWhenFinalCurrentReadbackFails() { } return result; }) - .when(membershipAuthorityEventProducer) + .when(producerTarget) .readCurrentPairBoundPositiveMembershipSnapshot(anyLong(), anyLong()); assertThatThrownBy(() -> tenantRoleMutationService.mutate(request)) @@ -1934,7 +1941,8 @@ void tenantRoleMutationRejectsNonExplicitMembershipWithoutChangingAnyAccountSour 2L, 2L))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("does not match its latest V1 provisional receipt"); + .hasMessageContaining( + "Current Account membership is not a positive active explicit membership"); assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(sourceBefore); assertThat(countAuditOutboxRows(fixture)).isEqualTo(auditCountBefore); assertTenantRoleOperationAbsent(requestId); @@ -2103,24 +2111,26 @@ void positiveMembershipSnapshotFailsClosedForAbsentMembershipOrReceipt() { assertThat(membershipAuthorityReadEvidenceSnapshot(absent)).isEqualTo(absentBeforeRead); JoinFixture missingReceipt = fixture("active"); - dsl.execute( - "INSERT INTO account_tenant_membership " - + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " - + "membership_version, membership_authority_generation, authority_provenance) " - + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", - missingReceipt.accountId(), - missingReceipt.tenantId()); - long retainedMembershipId = seedPlayerRoleSnapshot(missingReceipt); + long retainedMembershipId = + new TransactionTemplate(transactionManager) + .execute( + status -> + seedSyntheticRetainedActiveMembership( + missingReceipt, List.of("player"), false)); Map retainedMembership = membershipSnapshot(missingReceipt); + Map sourceBeforeRead = membershipAuthorityReadEvidenceSnapshot(missingReceipt); + long authorityEventCountBefore = countAuthorityMembershipEvents(missingReceipt); assertThat(retainedMembershipId).isPositive(); + assertThat(authorityEventCountBefore).isEqualTo(1L); assertThat(countMembershipTransitionReceipts(missingReceipt)).isZero(); assertThatThrownBy(() -> readPositiveMembershipSnapshot(missingReceipt)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Account membership exists without a provisional transition receipt"); assertThat(membershipSnapshot(missingReceipt)).isEqualTo(retainedMembership); + assertThat(membershipAuthorityReadEvidenceSnapshot(missingReceipt)).isEqualTo(sourceBeforeRead); assertThat(countMembershipTransitionReceipts(missingReceipt)).isZero(); - assertThat(countAuthorityMembershipEvents(missingReceipt)).isZero(); + assertThat(countAuthorityMembershipEvents(missingReceipt)).isEqualTo(authorityEventCountBefore); } @Test @@ -3108,6 +3118,11 @@ private TenantRoleFixture syntheticRetainedAdminFixture() { } private void seedSyntheticRetainedActiveMembership(JoinFixture fixture, List roles) { + seedSyntheticRetainedActiveMembership(fixture, roles, true); + } + + private long seedSyntheticRetainedActiveMembership( + JoinFixture fixture, List roles, boolean includeTransitionReceipt) { Account account = accountRepository.findByAccountUuidForUpdate(fixture.accountUuid()).orElseThrow(); ApprovedAssociation association = tenantIdentityResolver.resolve(fixture.tenantUuid()); @@ -3142,10 +3157,12 @@ private void seedSyntheticRetainedActiveMembership(JoinFixture fixture, List Date: Mon, 5 Oct 2026 21:29:29 +1300 Subject: [PATCH 4/6] Prove fresh membership producer and consumer over PostgreSQL mTLS --- .github/workflows/ci.yml | 3 + .../player-access-and-session.md | 4 + services/account-service/build.gradle.kts | 1 + ...icalJoinReconciliationIntegrationTest.java | 556 +++++++++++++++++- ...orityGrpcPostgresMtlsCrossServiceTest.java | 481 +++++++++++++++ 5 files changed, 1040 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 992957532e..fcaa2d54cb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1600,6 +1600,7 @@ jobs: --require-suite crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest#realMembershipSnapshotAndSequenceZeroBaselineCrossPostgresAndAuthenticatedSocket()' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest#retainedInactiveLeftAndReactivationSnapshotsCrossPostgresAndAuthenticatedSocket()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest#committedFreshUuidCanonicalJoinSnapshotRoundTripsThroughGameSessionClientOverPostgresMtls()' \ game-session-service - name: Upload Account membership PostgreSQL readback socket mTLS proof results @@ -1791,6 +1792,8 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#pendingCanonicalJoinCannotAuthorizePositiveReadbackOrCauseMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#freshUuidReadRejectsContradictoryReceiptEventRolesPairAndAuditWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#existingOnlyFreshUuidReadRejectsWrongAccountAndTenantSources()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#committedFreshUuidJoinRoundTripsExactSnapshotOverPhysicalMtls()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#physicalMembershipTransportRejectsWrongPeersBeforeProducerAccess()' \ account-service - name: Upload Account canonical JOIN scope and intent PostgreSQL proof results 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 e267d056bc..6525c4e2fd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The next held-back membership proof batch composes an already committed fresh-UUID canonical JOIN with the real Account producer, transaction manager, default response serializer and a physical mutual-TLS listener. Two Account definitions cover exact snapshot readback without source mutation and wrong-workload, wrong-namespace and missing-client-certificate rejection before producer access. A separate Game Session cross-service definition uses its actual `AccountMembershipAuthorityClient`, including complete recipient evidence validation, exact request echoes and unknown-tenant denial. The workflow requires these exact methods without skips. The corrected full Account check/JAR/format/analyzers/docs passes in 1m12s (72 tasks: 18 executed, 54 up-to-date), with 943 clean unit executions and 351 integration cases skipped without Docker. The focused Game Session cross-service check, corresponding Checkstyle/SpotBugs, formatting and boot JAR pass in 12s (114 tasks: 18 executed, 96 up-to-date); its three PostgreSQL/TLS methods compile and skip without Docker. Initial compile checks caught a generic Mockito spy overload and a fresh-versus-retained fixture helper call; the corrections preserve typed sources, transactions and assertions. Workflow lint and documentation hygiene pass. These fixtures stipulate upstream JOIN caller and policy evidence; membership readback binds the Account/tenant pair, not realm/catalog admission. No test definition or Docker-free skip proves PostgreSQL/TLS execution, registry authorization, authenticated JOIN ingress, runtime activation or an enabled membership RPC. The eighteen Account and seventy-one Game Session protobuf configuration-cache problems discard those entries; successful checks are not cache-support proof. + +The corrected harness at `f2242c536f33ec0b5372abfaa74d502e8c0b9278` has executed PostgreSQL proof: [CI37281117744](https://github.com/benhook1013/FireMUD/actions/runs/37281117744) Account job `111669309085` completed successfully. All eighteen then-required methods passed without skips: eleven retained-role, two immutable-journal and five fresh-JOIN cases. Independently parsed full raw suites pass JOIN 51/51, journal 2/2, canonical JOIN reconciliation 9/9 and canonical scope 4/4. The artifact merge `f12c3fc70407ea6a58fbc1c187c184f46684ff65` has the exact World `0bb5da90df09a82e2456811066cb6320b3380ee9` and Account source parents and a tree identical to the source head. Exact checkout logs were unavailable while the aggregate remained active; the observer ended on the successful Account job, not aggregate green. Independently rehashed XML: JOIN `1751fed703c66eb030a6bf86a082dd17c68ed4dda10e91b45533321653952f79`, journal `ec604aa8bb9f2adb3e81e8e112c9ed1bce832c1447b1ca2d5f90817ce105dd3e`, canonical reconciliation `d4ba3ada5d24860d1ebeeecd399a7b803c79131105c8539313a091c7b10c564f`, canonical scope `7b2a0eae5a432fd2f5287401ed83f0cf2f4ba1736f887c4d330f255f2c6d757e`. This closes those fixture-correction execution gaps; it does not execute the subsequent three fresh-UUID physical transport/consumer definitions or establish authenticated JOIN, a complete authorization bundle or activation. + The subsequent `214c6c9a875ce8f37f71891f89a95c1ac8cb85da` [CI37277059204](https://github.com/benhook1013/FireMUD/actions/runs/37277059204) Account job is terminal failure but proves progress: all eighteen required methods executed without skips, fourteen passed and four failed. Both immutable journal methods and all five new fresh-JOIN methods passed; seven of eleven retained-role methods passed. The full raw suites record JOIN 51/eight failures, journal two/zero failures and canonical reconciliation nine/zero failures. Three rollback tests failed during Mockito setup at a MANDATORY transaction proxy, leaving unfinished stubs that contaminated three later methods. One non-explicit denial assertion and one separate missing-receipt fixture also reached different valid guards than expected. The corrected rollback harness stubs the underlying Mockito spy while the actual mutation continues through its unchanged Spring transaction proxy. The missing-receipt fixture supplies coherent membership, roles, event, pair and authority sources and omits only the receipt; its no-mutation assertions remain. The corrected full Account check/JAR/analyzers/format/docs passes in 30s (72 tasks: 14 executed, 58 up-to-date), reusing the unchanged 943 clean unit results; all 349 integration cases remain locally skipped without Docker. Corrected harness PostgreSQL execution is still required. The source PR head/branch match the run, and artifact names identify merge SHA `9b0b39feeb14a4d947d828b4262eafd13794471c`; checkout succeeded, but its exact log/base evidence was unavailable while the aggregate remained active at observer handoff. Independently rehashed raw XML: JOIN `08aed57d0021d429ac4b9f882a1b5332459154aca4d7053cf75341b3d10775d8`, journal `8e2efcc9739e8fe3d2fd5d6f3964c6f3ec5f27eee9a36793e0455b6e2234b064`, canonical reconciliation `d2e02592abe76398feea58bcae0da5040e993e598da02077d1434f5c4d4b9b79`. This is executed component proof, not an authenticated public JOIN, complete authorization bundle, aggregate-green or activation claim. Exact `b9e06f435a9832d5d520e1626f33e1fd5848f0d7` [CI37270614224](https://github.com/benhook1013/FireMUD/actions/runs/37270614224) supplies actual PostgreSQL execution, not passing proof: all thirteen required retained-role and journal methods executed with zero skips, three passed and ten failed. The JOIN suite executed 51 methods with nine failures, including one additional denial-message regression; the journal suite executed two methods with two failures. Six role tests failed while constructing entitlement-backed fixture state, the non-explicit and overflow setups violated unchanged owner guards, and the journal SQL bound `audit_occurred_at` as varchar instead of TIMESTAMPTZ. The Account job is terminal failure; the aggregate was still running at the observer handoff. Root independently parsed and hashed both raw suites (`82be9d4539a5c710a3fe1763c7616e85537c22be9bdb8df86b0291f21800a368` and `c45a5b48f208fc84abfedb47edd668703ec7af02227ce7a0c1b74f349550dbc0`). Corrected execution remains required; fixture repairs must preserve the production guards and no-mutation assertions. diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 79153fc623..ae07ca2c5a 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -19,6 +19,7 @@ dependencies { implementation(libs.stripe.java) // Test-only JDBC mocks need narrowly scoped resource-analysis annotations. testCompileOnly(libs.spotbugs.annotations) + testImplementation(libs.bouncycastle.pkix) // Integration analysis follows the real producer's annotated Account collaborators. add("integrationTestImplementation", "com.github.spotbugs:spotbugs-annotations:4.9.8") } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java index 3acce1e3db..d4a2b394f6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java @@ -2,11 +2,42 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; - +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; @@ -16,6 +47,16 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.accountservice.AccountServiceApplication; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; @@ -45,11 +86,28 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountCanonicalJoinReconciliationService; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.impl.AccountMembershipAuthorityGrpcService; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -58,7 +116,9 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -66,11 +126,12 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * PostgreSQL composition proof for the explicitly unwired canonical JOIN readback component. + * PostgreSQL composition and physical-transport proof for explicitly unwired canonical JOIN and + * membership readback components. * - *

These fixtures call Account owner repositories directly and establish storage/recovery proof - * only. In particular, historical event/receipt/audit rows seeded beside already-expired scopes do - * not exercise or claim authenticated entitlement, caller, or public JOIN authorization. + *

The storage fixtures call Account owner repositories directly. The physical mTLS cases serve + * only the held-back Account membership producer and use synthetic JOIN caller/policy evidence; + * none of these tests proves authenticated entitlement, caller, or public JOIN authorization. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -86,6 +147,11 @@ }) class AccountCanonicalJoinReconciliationIntegrationTest { private static final String TEST_NAMESPACE = "firemud-unit1b"; + private static final String ACCOUNT_SERVER_URI = + "spiffe://firemud/ns/firemud-unit1b/sa/account-service"; + private static final String GAME_SESSION_CLIENT_URI = + "spiffe://firemud/ns/firemud-unit1b/sa/game-session-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); private static final int MAX_ATTEMPTS = 12; private static final DateTimeFormatter RFC3339 = DateTimeFormatter.ISO_INSTANT; @@ -452,6 +518,473 @@ void concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet() thro assertThat(evidenceCounts(fixture)).isEqualTo(before); } + @Test + void committedFreshUuidJoinRoundTripsExactSnapshotOverPhysicalMtls() throws Exception { + // The persisted policy/caller fixture is synthetic. This proves only the held-back producer + // transport and does not claim authenticated public JOIN or Game Session consumer activation. + JoinFixture fixture = committedFreshJoinFixture(); + EvidenceCounts countsBefore = evidenceCounts(fixture); + CanonicalJoinOperationEvidence operationBefore = readOperation(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + long fenceBefore = issuanceFence(fixture.account().accountUuid()); + FreshTenantCreationEvidence freshSourceBefore = + inTransaction(() -> freshAssociations.read(fixture.tenantUuid()).orElseThrow()); + RuntimeMembershipSnapshotDto snapshotBefore = readRuntimeSnapshot(fixture); + + AccountMembershipAuthorityEventProducer producerTarget = + AopTestUtils.getUltimateTargetObject(membershipEventProducer); + AccountMembershipAuthorityEventProducer producerTargetSpy = spy(producerTarget); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return invocation.callRealMethod(); + }) + .when(producerTargetSpy) + .readRuntimeMembershipSnapshot(fixture.account().accountUuid(), fixture.tenantUuid()); + + TestPki pki = newTestPki(); + AtomicInteger applicationCalls = new AtomicInteger(); + Server server = startPhysicalMembershipServer(producerTargetSpy, pki, applicationCalls); + ManagedChannel channel = + newPhysicalMembershipChannel(server.getPort(), pki.gameSessionClient(), pki); + PlayerExecutionContext playerContext = runtimePlayerContext(fixture); + try { + GetTenantMembershipForRuntimeResponse response = + membershipStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext(playerContext) + .build()); + RuntimeMembershipSnapshotDto snapshotAfter = readRuntimeSnapshot(fixture); + + assertRuntimeMembershipResponseMatches(response, playerContext, snapshotBefore); + assertThat(Instant.parse(response.getEvaluatedAt())) + .isBetween(snapshotBefore.evaluatedAt(), snapshotAfter.evaluatedAt()); + assertThat(GetTenantMembershipForRuntimeResponse.parseFrom(response.toByteArray())) + .isEqualTo(response); + assertThat(applicationCalls).hasValue(1); + verify(producerTargetSpy, times(1)) + .readRuntimeMembershipSnapshot(fixture.account().accountUuid(), fixture.tenantUuid()); + assertOwnerEvidenceUnchanged( + fixture, + snapshotBefore, + snapshotAfter, + operationBefore, + pairBefore, + freshSourceBefore, + countsBefore, + fenceBefore); + } finally { + stopPhysicalTransport(server, channel); + } + } + + @Test + void physicalMembershipTransportRejectsWrongPeersBeforeProducerAccess() throws Exception { + JoinFixture fixture = committedFreshJoinFixture(); + EvidenceCounts countsBefore = evidenceCounts(fixture); + CanonicalJoinOperationEvidence operationBefore = readOperation(fixture); + PairAuthority pairBefore = pairAuthority(fixture); + long fenceBefore = issuanceFence(fixture.account().accountUuid()); + FreshTenantCreationEvidence freshSourceBefore = + inTransaction(() -> freshAssociations.read(fixture.tenantUuid()).orElseThrow()); + RuntimeMembershipSnapshotDto snapshotBefore = readRuntimeSnapshot(fixture); + + AccountMembershipAuthorityEventProducer producerTarget = + AopTestUtils.getUltimateTargetObject(membershipEventProducer); + AccountMembershipAuthorityEventProducer producerTargetSpy = spy(producerTarget); + TestPki pki = newTestPki(); + AtomicInteger applicationCalls = new AtomicInteger(); + Server server = startPhysicalMembershipServer(producerTargetSpy, pki, applicationCalls); + ManagedChannel wrongWorkloadChannel = + newPhysicalMembershipChannel(server.getPort(), pki.wrongWorkloadClient(), pki); + ManagedChannel wrongNamespaceChannel = + newPhysicalMembershipChannel(server.getPort(), pki.wrongNamespaceGameSessionClient(), pki); + PlayerExecutionContext playerContext = runtimePlayerContext(fixture); + try { + assertMembershipPeerDenied(wrongWorkloadChannel, playerContext); + assertThat(applicationCalls).hasValue(1); + verifyNoInteractions(producerTargetSpy); + + assertMembershipPeerDenied(wrongNamespaceChannel, playerContext); + assertThat(applicationCalls).hasValue(2); + verifyNoInteractions(producerTargetSpy); + + assertMissingClientCertificateHandshakeRejected(server, pki); + assertThat(applicationCalls) + .as("a missing client certificate must fail before gRPC application dispatch") + .hasValue(2); + verifyNoInteractions(producerTargetSpy); + + RuntimeMembershipSnapshotDto snapshotAfter = readRuntimeSnapshot(fixture); + assertOwnerEvidenceUnchanged( + fixture, + snapshotBefore, + snapshotAfter, + operationBefore, + pairBefore, + freshSourceBefore, + countsBefore, + fenceBefore); + } finally { + stopPhysicalTransport(server, wrongWorkloadChannel, wrongNamespaceChannel); + } + } + + private RuntimeMembershipSnapshotDto readRuntimeSnapshot(JoinFixture fixture) { + return inTransaction( + () -> + membershipEventProducer.readRuntimeMembershipSnapshot( + fixture.account().accountUuid(), fixture.tenantUuid())); + } + + private void assertRuntimeMembershipResponseMatches( + GetTenantMembershipForRuntimeResponse response, + PlayerExecutionContext request, + RuntimeMembershipSnapshotDto expected) { + assertThat(response.getUnknownFields().asMap()).isEmpty(); + assertThat(response.hasError()).isFalse(); + assertThat(response.getAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(response.getAccountId()).isEqualTo(expected.accountUuid()); + assertThat(response.getTenantId()).isEqualTo(expected.tenantUuid()); + assertThat(response.getRequestAccountId()).isEqualTo(request.getAccountId()); + assertThat(response.getRequestTenantId()).isEqualTo(request.getTenantId()); + assertThat(response.getRequestId()).isEqualTo(request.getRequestId()); + assertThat(response.getMembershipExists()).isEqualTo(expected.membershipExists()); + assertThat(response.getGameplayAdmissionAllowed()) + .isEqualTo(expected.gameplayAdmissionAllowed()); + assertThat(response.getMembershipLifecycleState()) + .isEqualTo(expected.membershipBaseline().membershipLifecycleState()); + assertThat(response.getMembershipVersionMap()) + .isEqualTo(expected.membershipBaseline().membershipVersion()); + assertThat(response.getMembershipAuthorityGeneration()) + .isEqualTo(expected.membershipBaseline().membershipAuthorityGeneration()); + assertThat(response.getMembershipBaseline().getMembershipLifecycleState()) + .isEqualTo(expected.membershipBaseline().membershipLifecycleState()); + assertThat(response.getMembershipBaseline().getMembershipVersionMap()) + .isEqualTo(expected.membershipBaseline().membershipVersion()); + assertThat(response.getMembershipBaseline().getMembershipAuthorityGeneration()) + .isEqualTo(expected.membershipBaseline().membershipAuthorityGeneration()); + assertThat(response.getRolesList()).containsExactlyElementsOf(expected.roles()); + assertThat(response.getIssuanceFence()).isEqualTo(expected.issuanceFence()); + + String tenantUuid = expected.tenantUuid(); + assertThat(expected.membershipExists()).isTrue(); + assertThat(expected.gameplayAdmissionAllowed()).isTrue(); + assertThat(expected.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(expected.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(tenantUuid, "2")); + assertThat(expected.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(expected.issuanceFence()).isEqualTo("1"); + var expectedTuple = expected.authorityTuple(); + var actualTuple = response.getAuthorityTuple(); + assertThat(actualTuple.getIssuerAuthGeneration()) + .isEqualTo(expectedTuple.issuerAuthGeneration()); + assertThat(actualTuple.getAccountAuthorityGeneration()) + .isEqualTo(expectedTuple.accountAuthorityGeneration()); + assertThat(actualTuple.getTenantAuthorityGenerationMap()) + .isEqualTo(expectedTuple.tenantAuthorityGeneration()); + assertThat(actualTuple.getMembershipAuthorityGenerationMap()) + .isEqualTo(expectedTuple.membershipAuthorityGeneration()); + assertThat(expectedTuple.issuerAuthGeneration()).isEqualTo("1"); + assertThat(expectedTuple.accountAuthorityGeneration()).isEqualTo("1"); + assertThat(expectedTuple.tenantAuthorityGeneration()).isEqualTo(Map.of(tenantUuid, "1")); + assertThat(expectedTuple.membershipAuthorityGeneration()).isEqualTo(Map.of(tenantUuid, "1")); + assertThat(actualTuple.getPrivateRealmGrantVersionsCount()) + .isEqualTo(expectedTuple.privateRealmGrantVersions().size()); + assertThat(actualTuple.hasAccountSecurityCutoff()) + .isEqualTo(expectedTuple.accountSecurityCutoff().isPresent()); + expectedTuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + assertThat(actualTuple.getAccountSecurityCutoff().getAccountAuthorityGeneration()) + .isEqualTo(cutoff.accountAuthorityGeneration()); + assertThat(actualTuple.getAccountSecurityCutoff().getOutboxStreamKey()) + .isEqualTo(cutoff.outboxStreamKey()); + assertThat(actualTuple.getAccountSecurityCutoff().getOutboxSequence()) + .isEqualTo(cutoff.outboxSequence()); + }); + assertThat(actualTuple.hasTenantBillingCutoff()) + .isEqualTo(expectedTuple.tenantBillingCutoff().isPresent()); + assertThat(expectedTuple.privateRealmGrantVersions()).isEmpty(); + assertThat(expectedTuple.accountSecurityCutoff()).isEmpty(); + assertThat(expectedTuple.tenantBillingCutoff()).isEmpty(); + + assertThat(response.getOutboxCheckpointsCount()).isEqualTo(expected.outboxCheckpoints().size()); + for (int index = 0; index < expected.outboxCheckpoints().size(); index++) { + var actual = response.getOutboxCheckpoints(index); + var checkpoint = expected.outboxCheckpoints().get(index); + assertThat(actual.getOutboxStreamKey()).isEqualTo(checkpoint.outboxStreamKey()); + assertThat(actual.getOutboxSequence()).isEqualTo(checkpoint.outboxSequence()); + assertThat(actual.getUnknownFields().asMap()).isEmpty(); + } + assertThat(response.getOutboxSourceEvidenceCount()) + .isEqualTo(expected.outboxSourceEvidence().size()); + for (int index = 0; index < expected.outboxSourceEvidence().size(); index++) { + var actual = response.getOutboxSourceEvidence(index); + var source = expected.outboxSourceEvidence().get(index); + assertThat(actual.getOutboxStreamKey()).isEqualTo(source.outboxStreamKey()); + assertThat(actual.getOutboxSequence()).isEqualTo(source.outboxSequence()); + assertThat(actual.getEventId()).isEqualTo(source.eventId()); + assertThat(actual.getEventDigest()).isEqualTo(source.eventDigest()); + assertThat(actual.getCanonicalEventJson()).isEqualTo(source.canonicalEventJson()); + assertThat(actual.getUnknownFields().asMap()).isEmpty(); + } + assertThat(expected.sourceEvent()).isNotNull(); + assertThat(response.getOutboxSourceEvidenceCount()).isEqualTo(1); + assertThat(response.getOutboxSourceEvidence(0).getOutboxStreamKey()) + .isEqualTo(eventStreamKey(expected.accountUuid(), expected.tenantUuid())); + assertThat(response.getOutboxSourceEvidence(0).getOutboxSequence()).isEqualTo("1"); + assertThat(response.getOutboxSourceEvidence(0).getCanonicalEventJson()) + .isEqualTo(expected.sourceEvent().canonicalJson()); + } + + private void assertMembershipPeerDenied( + ManagedChannel channel, PlayerExecutionContext playerContext) { + Throwable failure = + catchThrowable( + () -> + membershipStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext(playerContext) + .build())); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private AccountServiceGrpc.AccountServiceBlockingStub membershipStub(ManagedChannel channel) { + return AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(ACCOUNT_SERVER_URI)); + } + + private void assertOwnerEvidenceUnchanged( + JoinFixture fixture, + RuntimeMembershipSnapshotDto snapshotBefore, + RuntimeMembershipSnapshotDto snapshotAfter, + CanonicalJoinOperationEvidence operationBefore, + PairAuthority pairBefore, + FreshTenantCreationEvidence freshSourceBefore, + EvidenceCounts countsBefore, + long fenceBefore) { + assertThat(snapshotAfter) + .usingRecursiveComparison() + .ignoringFields("evaluatedAt") + .isEqualTo(snapshotBefore); + assertThat(readOperation(fixture)).isEqualTo(operationBefore); + assertThat(pairAuthority(fixture)).isEqualTo(pairBefore); + assertThat(inTransaction(() -> freshAssociations.read(fixture.tenantUuid()).orElseThrow())) + .isEqualTo(freshSourceBefore); + assertThat(evidenceCounts(fixture)).isEqualTo(countsBefore); + assertThat(issuanceFence(fixture.account().accountUuid())).isEqualTo(fenceBefore); + } + + private Server startPhysicalMembershipServer( + AccountMembershipAuthorityEventProducer producer, TestPki pki, AtomicInteger applicationCalls) + throws Exception { + AccountMembershipAuthorityGrpcService candidate = + new AccountMembershipAuthorityGrpcService(producer, transactionManager, TEST_NAMESPACE); + ServerInterceptor dispatchCounter = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + applicationCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + candidate, dispatchCounter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private ManagedChannel newPhysicalMembershipChannel( + int port, TestCertificate clientCertificate, TestPki pki) throws Exception { + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient() + .trustManager(pki.caCertificate()) + .keyManager( + clientCertificate.privateKey(), clientCertificate.certificate())) + .build()) + .build(); + } + + private void assertMissingClientCertificateHandshakeRejected(Server server, TestPki pki) + throws Exception { + Throwable handshakeFailure = + catchThrowable( + () -> { + try (Socket transport = new Socket()) { + transport.connect(new InetSocketAddress("127.0.0.1", server.getPort()), 5_000); + try (SSLSocket socket = + (SSLSocket) + trustOnlyClientContext(pki) + .getSocketFactory() + .createSocket(transport, "127.0.0.1", server.getPort(), true)) { + socket.setSoTimeout(5_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setApplicationProtocols(new String[] {"h2"}); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + socket.setSSLParameters(parameters); + socket.startHandshake(); + // TLS 1.3 can report the required client-certificate rejection on first read. + socket + .getOutputStream() + .write( + "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + socket.getInputStream().read(); + } + } + }); + assertThat(handshakeFailure) + .as("the REQUIRED client-certificate handshake must fail") + .isNotNull(); + assertThat(TlsTestSupport.isTlsHandshakeRejection(handshakeFailure)) + .as("failure must identify certificate rejection") + .isTrue(); + } + + private SSLContext trustOnlyClientContext(TestPki pki) throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null); + trustStore.setCertificateEntry("account-membership-test-ca", pki.caCertificate()); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(new KeyManager[0], trustManagers.getTrustManagers(), null); + return context; + } + + private TestPki newTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Account Membership Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + return new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "account-service", ACCOUNT_SERVER_URI), + issueLeaf(caName, caKeyPair.getPrivate(), "game-session-service", GAME_SESSION_CLIENT_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/" + TEST_NAMESPACE + "/sa/world-management-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service-wrong-namespace", + "spiffe://firemud/ns/other/sa/game-session-service")); + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private void stopPhysicalTransport(Server server, ManagedChannel... channels) + throws InterruptedException { + for (ManagedChannel channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private PlayerExecutionContext runtimePlayerContext(JoinFixture fixture) { + return PlayerExecutionContext.newBuilder() + .setAccountId(fixture.account().accountUuid().toString()) + .setTenantId(fixture.tenantUuid().toString()) + .setRealmId(UUID.randomUUID().toString()) + .setPlayableStateNamespaceId(UUID.randomUUID().toString()) + .setPlayableStateScope("SHARED") + .setGameInstanceId(UUID.randomUUID().toString()) + .setSessionId("9001") + .setRequestId(UUID.randomUUID().toString()) + .build(); + } + private JoinFixture fixture(Boolean allowPublicJoin) { AccountFixture account = accountFixture(); UUID tenantUuid = UUID.randomUUID(); @@ -797,6 +1330,10 @@ private String eventStreamKey(JoinFixture fixture) { + fixture.tenantUuid(); } + private String eventStreamKey(String accountUuid, String tenantUuid) { + return "account:auth-authority:v1:membership/" + accountUuid + "/" + tenantUuid; + } + private static UUID auditEventId(String requestId) { return UUID.nameUUIDFromBytes( ("account-join-audit/v1:" + requestId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); @@ -842,6 +1379,15 @@ private record JoinFixture( private record EvidenceCounts(long memberships, long events, long receipts, long audits) {} + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate accountServer, + TestCertificate gameSessionClient, + TestCertificate wrongWorkloadClient, + TestCertificate wrongNamespaceGameSessionClient) {} + private enum Contradiction { LATEST_RECEIPT, LATEST_EVENT, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java index 39a17500fc..5aa4d9677e 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java @@ -17,6 +17,10 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -30,6 +34,7 @@ import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -38,16 +43,30 @@ import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountCanonicalJoinReconciliationService; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; @@ -62,6 +81,8 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.client.AccountMembershipAuthorityClient; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; @@ -113,6 +134,8 @@ class AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest { private static final long CATALOG_REVISION = 31L; private static final long POINTER_VERSION = 13L; private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final DateTimeFormatter RFC3339 = DateTimeFormatter.ISO_INSTANT; + private static final int CANONICAL_JOIN_MAX_ATTEMPTS = 12; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -136,6 +159,15 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private AccountMembershipLifecycleService membershipLifecycleService; @Autowired private AccountLogoutAllOperationRepository logoutAllOperationRepository; @Autowired private AccountPasswordResetOperationRepository passwordResetOperationRepository; + @Autowired private AccountAuditOutboxRepository auditOutboxRepository; + @Autowired private AccountConnectScopeRepository connectScopeRepository; + @Autowired private AccountJoinOperationRepository joinOperationRepository; + @Autowired private AccountMembershipPairAuthorityRepository membershipPairAuthorityRepository; + @Autowired private AccountMembershipTransitionReceiptRepository transitionReceiptRepository; + @Autowired private AccountTenantMembershipRepository tenantMembershipRepository; + @Autowired private AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + @Autowired private FreshTenantIdentityAssociationRepository freshTenantAssociations; + @Autowired private AccountCanonicalJoinReconciliationService canonicalJoinReconciliationService; @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; @Autowired private PlatformTransactionManager transactionManager; @@ -149,6 +181,102 @@ static void configure(DynamicPropertyRegistry registry) { private final Map copiedCertificates = new HashMap<>(); + @Test + void committedFreshUuidCanonicalJoinSnapshotRoundTripsThroughGameSessionClientOverPostgresMtls() + throws Exception { + // This composes Account's committed V2 JOIN owner readback with the actual Game Session + // consumer over the physical socket. Caller/policy evidence is synthetic: this proves neither + // upstream caller/policy authentication, registry authorization, nor gameplay admission, and + // it does not register or enable the runtime RPC. + FreshCanonicalJoinFixture fixture = committedFreshCanonicalJoinFixture(); + CanonicalJoinOwnerState before = readCanonicalJoinOwnerState(fixture); + RuntimeMembershipSnapshotDto expected = before.snapshot(); + assertThat(before.operation().status()).isEqualTo("COMMITTED"); + assertThat(before.operation().outcome()).isEqualTo("JOINED"); + assertThat(before.operation().requestId()).isEqualTo(fixture.requestId()); + assertThat(before.operation().scopeEvidence().accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(before.operation().scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(before.operation().scopeEvidence().realmId()).isEqualTo(fixture.scope().realmId()); + assertThat(before.operation().scopeEvidence().catalogRevision()) + .isEqualTo(fixture.scope().catalogRevision()); + assertThat(before.operation().scopeEvidence().pointerVersion()) + .isEqualTo(fixture.scope().pointerVersion()); + assertThat(before.operation().scopeEvidence().tenantProvenance()) + .isEqualTo(fixture.provenance()); + assertThat(before.freshTenantSource()).isEqualTo(fixture.creationEvidence()); + assertThat(before.freshTenantSource().canonicalTenantId()).isEqualTo(fixture.tenantUuid()); + assertThat(before.pairAuthority().provenance()).isEqualTo(fixture.provenance()); + assertThat(expected.membershipExists()).isTrue(); + assertThat(expected.gameplayAdmissionAllowed()).isTrue(); + assertThat(expected.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(expected.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(expected.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(expected.roles()).containsExactly("player"); + assertThat(expected.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(expected.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(expected.outboxCheckpoints()).hasSize(4); + assertThat(expected.outboxCheckpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()) + .isEqualTo(membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(checkpoint.outboxSequence()).isEqualTo("1"); + }); + + Server server = startServer(); + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + PlayerExecutionContext originalContext = freshPlayerContext(fixture, fixture.requestId()); + GetTenantMembershipForRuntimeResponse originalResponse = + client.getTenantMembershipForRuntime(originalContext); + assertResponseMatchesSnapshot(originalResponse, originalContext, expected); + assertFreshCanonicalJoinMembershipEvent(originalResponse, fixture, expected); + RuntimeMembershipSnapshotDto repeatedSnapshot = readRuntimeMembershipSnapshot(fixture); + assertSameCurrentMembershipSnapshot(expected, repeatedSnapshot); + GetTenantMembershipForRuntimeResponse repeatedResponse = + client.getTenantMembershipForRuntime(originalContext); + assertResponseMatchesSnapshot(repeatedResponse, originalContext, repeatedSnapshot); + assertThat(stableCarrier(repeatedResponse)).isEqualTo(stableCarrier(originalResponse)); + + // A distinct caller request ID is not allowed to inherit the first response's correlation. + PlayerExecutionContext changedRequestContext = + originalContext.toBuilder().setRequestId(UUID.randomUUID().toString()).build(); + GetTenantMembershipForRuntimeResponse changedRequestResponse = + client.getTenantMembershipForRuntime(changedRequestContext); + assertResponseMatchesSnapshot( + changedRequestResponse, changedRequestContext, repeatedSnapshot); + assertThat(changedRequestResponse.getRequestId()) + .isEqualTo(changedRequestContext.getRequestId()) + .isNotEqualTo(originalContext.getRequestId()); + assertThat(stableCarrier(changedRequestResponse)).isEqualTo(stableCarrier(originalResponse)); + assertFreshCanonicalJoinMembershipEvent(changedRequestResponse, fixture, repeatedSnapshot); + + // The Account snapshot is selected by the exact canonical Account/tenant pair. An unknown + // fresh tenant cannot be treated as this JOIN or cause an absence baseline to be created. + UUID changedTenantUuid = UUID.randomUUID(); + PlayerExecutionContext changedTargetContext = + originalContext.toBuilder() + .setTenantId(changedTenantUuid.toString()) + .setRequestId(UUID.randomUUID().toString()) + .build(); + assertRemoteFailure( + () -> client.getTenantMembershipForRuntime(changedTargetContext), + Status.Code.FAILED_PRECONDITION); + assertThat(countMembershipPairRows(fixture.accountUuid(), changedTenantUuid)).isZero(); + assertThat(countMembershipGenerationRows(fixture.accountUuid(), changedTenantUuid)).isZero(); + assertThat(countCanonicalMembershipRows(fixture.accountId(), changedTenantUuid)).isZero(); + assertThat(countStreamEvents(membershipStreamKey(fixture.accountUuid(), changedTenantUuid))) + .isZero(); + assertCanonicalJoinOwnerEvidenceUnchanged(fixture, before); + } finally { + stop(server); + } + } + @Test void realMembershipSnapshotAndSequenceZeroBaselineCrossPostgresAndAuthenticatedSocket() throws Exception { @@ -647,6 +775,211 @@ void retainedInactiveLeftAndReactivationSnapshotsCrossPostgresAndAuthenticatedSo } } + private FreshCanonicalJoinFixture committedFreshCanonicalJoinFixture() { + FreshCanonicalJoinFixture fixture = freshCanonicalJoinFixture(); + persistCanonicalJoinEvidence(fixture); + Instant diagnosticAt = Instant.now(); + inTransactionWithoutResult( + () -> { + joinOperationRepository.recordCanonicalPolicyUnavailable( + fixture.requestId(), fixture.scope(), fixture.callerBinding(), "ENTITLEMENT_TIMEOUT"); + joinOperationRepository.recordCanonicalReconciliationAttempt( + fixture.requestId(), + 0, + CANONICAL_JOIN_MAX_ATTEMPTS, + diagnosticAt, + "CANONICAL_JOIN_READBACK_UNAVAILABLE", + diagnosticAt); + }); + canonicalJoinReconciliationService.reconcileDueOperations( + Instant.parse(fixture.scope().connectScopeExpiresAt()).plus(Duration.ofDays(1))); + CanonicalJoinOperationEvidence operation = + new TransactionTemplate(transactionManager) + .execute( + status -> + joinOperationRepository + .findCanonicalEvidenceByRequestId(fixture.requestId()) + .orElseThrow()); + assertThat(operation.status()).isEqualTo("COMMITTED"); + assertThat(operation.outcome()).isEqualTo("JOINED"); + return fixture; + } + + private FreshCanonicalJoinFixture freshCanonicalJoinFixture() { + String suffix = UUID.randomUUID().toString(); + String shortSuffix = suffix.replace("-", "").substring(0, 12); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "fresh-mtls-" + shortSuffix, + "fresh-membership-mtls-" + suffix + "@example.test", + "synthetic-fixture-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence creationEvidence = freshTenantCreationEvidence(tenantUuid); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + creationEvidence.operationId(), + creationEvidence.evidenceDigest()); + inTransactionWithoutResult( + () -> { + freshTenantAssociations.importVerified(creationEvidence); + authorityGenerationRepository.initializeTenantIfAbsent(tenantUuid); + authorityGenerationRepository.initializeIssuerIfAbsent( + AccountServiceImpl.ACCOUNT_JWT_ISSUER); + membershipAuthorityEventProducer.readFreshNeverJoinedMembershipSnapshot( + accountUuid, tenantUuid); + }); + + Instant evaluatedAt = Instant.now().minus(Duration.ofHours(1)); + Instant expiresAt = Instant.now().minus(Duration.ofMinutes(30)); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "fresh-mtls-join-" + UUID.randomUUID(), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "fresh-tenant-" + shortSuffix, + "fresh-world-" + shortSuffix, + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 3L, + 2L, + RFC3339.format(evaluatedAt.atOffset(ZoneOffset.UTC)), + RFC3339.format(expiresAt.atOffset(ZoneOffset.UTC))); + String requestId = UUID.randomUUID().toString(); + String callerBinding = "synthetic-caller-" + UUID.randomUUID(); + inTransactionWithoutResult( + () -> { + connectScopeRepository.insertCanonical(accountId, scope, provenance); + joinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); + joinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 11L); + }); + return new FreshCanonicalJoinFixture( + accountId, + accountUuid, + tenantUuid, + provenance, + creationEvidence, + scope, + requestId, + callerBinding); + } + + private FreshTenantCreationEvidence freshTenantCreationEvidence(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, creationRequestId, sourceTenantKey, "Fresh membership mTLS fixture", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private void inTransactionWithoutResult(Runnable callback) { + new TransactionTemplate(transactionManager).executeWithoutResult(status -> callback.run()); + } + + private void persistCanonicalJoinEvidence(FreshCanonicalJoinFixture fixture) { + inTransactionWithoutResult( + () -> { + Account account = + accountRepository.findByAccountUuid(fixture.accountUuid()).orElseThrow(); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(fixture.provenance().legacyTenantId()); + membership.setTenantUuid(fixture.tenantUuid()); + membership.setTenantProvenanceKind(fixture.provenance().kind().name()); + membership.setTenantSourceOperationId(fixture.provenance().sourceOperationId()); + membership.setTenantProvenanceDigest(fixture.provenance().digest()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(2L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + tenantMembershipRepository.saveCanonical( + membership, fixture.accountUuid(), fixture.tenantUuid(), fixture.provenance()); + roleSnapshotRepository.replaceCanonical( + membership, + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.provenance(), + 2L, + List.of("player")); + membershipAuthorityEventProducer.publishCanonicalFirstJoinMembershipChange( + fixture.scope(), fixture.requestId(), fixture.callerBinding()); + transitionReceiptRepository.appendCanonicalTransition( + fixture.accountUuid(), + fixture.tenantUuid(), + "MEMBERSHIP_JOINED", + fixture.requestId()); + String auditPayload = + AccountAuditOutboxRepository.canonicalJoinPayload( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.scope().worldSlug(), + fixture.scope().realmSlug(), + Map.of(fixture.tenantUuid().toString(), "2"), + fixture.requestId()); + auditOutboxRepository.appendCanonicalTenant( + canonicalJoinAuditEventId(fixture.requestId()), + fixture.tenantUuid().toString(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + auditPayload); + }); + } + + private PlayerExecutionContext freshPlayerContext( + FreshCanonicalJoinFixture fixture, String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId(fixture.accountUuid().toString()) + .setTenantId(fixture.tenantUuid().toString()) + .setRealmId(fixture.scope().realmId().toString()) + .setPlayableStateNamespaceId(fixture.scope().playableStateNamespaceId().toString()) + .setPlayableStateScope(fixture.scope().playableStateScope()) + .setGameInstanceId(fixture.scope().gameInstanceId().toString()) + .setSessionId("9001") + .setRequestId(requestId) + .build(); + } + + private static UUID canonicalJoinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + private JoinFixture fixture() { String suffix = UUID.randomUUID().toString(); String shortSuffix = suffix.replace("-", "").substring(0, 12); @@ -757,6 +1090,129 @@ private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture f fixture.accountUuid(), fixture.tenantUuid())); } + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( + FreshCanonicalJoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( + fixture.accountUuid(), fixture.tenantUuid())); + } + + private CanonicalJoinOwnerState readCanonicalJoinOwnerState(FreshCanonicalJoinFixture fixture) { + UUID accountUuid = fixture.accountUuid(); + UUID tenantUuid = fixture.tenantUuid(); + return new CanonicalJoinOwnerState( + readRuntimeMembershipSnapshot(fixture), + new TransactionTemplate(transactionManager) + .execute( + status -> + joinOperationRepository + .findCanonicalEvidenceByRequestId(fixture.requestId()) + .orElseThrow()), + new TransactionTemplate(transactionManager) + .execute( + status -> + membershipPairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow()), + new TransactionTemplate(transactionManager) + .execute(status -> freshTenantAssociations.read(tenantUuid).orElseThrow()), + canonicalJoinEvidenceCounts(fixture), + readAuthorityState(AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER)), + readAuthorityState(AuthorityScope.account(accountUuid)), + readAuthorityState(AuthorityScope.tenant(tenantUuid)), + readAuthorityState(AuthorityScope.membership(accountUuid, tenantUuid)), + accountIssuanceFence(accountUuid)); + } + + private void assertCanonicalJoinOwnerEvidenceUnchanged( + FreshCanonicalJoinFixture fixture, CanonicalJoinOwnerState before) { + CanonicalJoinOwnerState after = readCanonicalJoinOwnerState(fixture); + assertSameCurrentMembershipSnapshot(before.snapshot(), after.snapshot()); + assertThat(after.operation()).isEqualTo(before.operation()); + assertThat(after.pairAuthority()).isEqualTo(before.pairAuthority()); + assertThat(after.freshTenantSource()).isEqualTo(before.freshTenantSource()); + assertThat(after.evidenceCounts()).isEqualTo(before.evidenceCounts()); + assertThat(after.issuerAuthority()).isEqualTo(before.issuerAuthority()); + assertThat(after.accountAuthority()).isEqualTo(before.accountAuthority()); + assertThat(after.tenantAuthority()).isEqualTo(before.tenantAuthority()); + assertThat(after.membershipAuthority()).isEqualTo(before.membershipAuthority()); + assertThat(after.issuanceFence()).isEqualTo(before.issuanceFence()); + } + + private CanonicalJoinEvidenceCounts canonicalJoinEvidenceCounts( + FreshCanonicalJoinFixture fixture) { + return new CanonicalJoinEvidenceCounts( + countCanonicalMembershipRows(fixture.accountId(), fixture.tenantUuid()), + countStreamEvents(membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid())), + Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND receipt_version = 2", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(0, Long.class)), + Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + canonicalJoinAuditEventId(fixture.requestId())) + .fetchOne(0, Long.class))); + } + + private long countCanonicalMembershipRows(long accountId, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ?", + accountId, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private void assertFreshCanonicalJoinMembershipEvent( + GetTenantMembershipForRuntimeResponse response, + FreshCanonicalJoinFixture fixture, + RuntimeMembershipSnapshotDto snapshot) { + var event = snapshot.sourceEvent(); + assertThat(event).isNotNull(); + assertThat(event.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.requestId()).isEqualTo(fixture.requestId()); + assertThat(event.outboxStreamKey()) + .isEqualTo(membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(event.gameplayAdmissionAllowed()).isTrue(); + assertThat(event.membershipVersion()).isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(event.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(event.authorityTuple()).isEqualTo(snapshot.authorityTuple()); + assertThat(event.issuanceFence()).isEqualTo("1"); + + var membershipEvidence = + response.getOutboxSourceEvidenceList().stream() + .filter(source -> event.outboxStreamKey().equals(source.getOutboxStreamKey())) + .toList(); + assertThat(membershipEvidence).hasSize(1); + assertThat(membershipEvidence.getFirst().getOutboxSequence()).isEqualTo(event.outboxSequence()); + assertThat(membershipEvidence.getFirst().getEventId()).isEqualTo(event.eventId()); + assertThat(membershipEvidence.getFirst().getEventDigest()).isEqualTo(event.eventDigest()); + assertThat( + membershipEvidence.getFirst().getCanonicalEventJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(event.canonicalJsonUtf8()); + + var persistedEvent = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT request_id, event_id, event_digest FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + event.outboxStreamKey()) + .fetchOne()); + assertThat(persistedEvent.get("request_id", String.class)).isEqualTo(fixture.requestId()); + assertThat(persistedEvent.get("event_id", String.class)).isEqualTo(event.eventId()); + assertThat(persistedEvent.get("event_digest", String.class)).isEqualTo(event.eventDigest()); + } + private JoinFixture reactivationFixture(JoinFixture existing) { String suffix = UUID.randomUUID().toString(); String requestId = "membership-mtls-reactivation-" + suffix; @@ -1431,6 +1887,31 @@ private record JoinFixture( DirectTextCallerContext caller, DirectTextJoinScope scope) {} + private record FreshCanonicalJoinFixture( + long accountId, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + FreshTenantCreationEvidence creationEvidence, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding) {} + + private record CanonicalJoinOwnerState( + RuntimeMembershipSnapshotDto snapshot, + CanonicalJoinOperationEvidence operation, + PairAuthority pairAuthority, + FreshTenantCreationEvidence freshTenantSource, + CanonicalJoinEvidenceCounts evidenceCounts, + ScopeState issuerAuthority, + ScopeState accountAuthority, + ScopeState tenantAuthority, + ScopeState membershipAuthority, + long issuanceFence) {} + + private record CanonicalJoinEvidenceCounts( + long memberships, long events, long receipts, long audits) {} + private record DenialReadback( ScopeState issuerState, ScopeState accountState, From 3440d4d646414c2c7244e5e0cc1b650cd9e242d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:26:55 +1300 Subject: [PATCH 5/6] test(account): retain transaction observation when stubbing OTP target --- .../implementation-tracking/player-access-and-session.md | 4 ++++ .../service/AccountAuthenticationUuidIntegrationTest.java | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) 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 6525c4e2fd..ca1a1946e2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact `b5cf5ae01bf546657c7601919ba704b99a56d939`, [CI37284046862](https://github.com/benhook1013/FireMUD/actions/runs/37284046862) completed with aggregate failure, Account job `111678940179` failure and Game Session job `111678940188` cancellation of unestablished cause. Nevertheless, independently parsed raw XML proves all twenty required Account cases passed without skips: eleven retained-role, two journal, five fresh-JOIN and two new physical mTLS cases. The actual Game Session client PostgreSQL/mTLS suite passed all three cases without skips, including fresh positive readback, exact retry, authenticated request echoes, wrong/unknown identity rejection and no source mutation. Full Account raw suites pass JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. Checkout logs and verified merge `1db0f4d5075cd980b90dc64c90a61daec2586ab5` establish exact World `0bb5da90df09a82e2456811066cb6320b3380ee9` and Account source parents; merge tree `d432827ecf4edd022ca6e50f8f0071f02ba87c0b` matches the source tree. This closes these physical producer/consumer component execution gaps, not authenticated upstream JOIN, realm/catalog admission, current-parent composition, registry authorization or activation. Root rehashed JOIN `05d7ec0f8b4365088530c0683d506c19eacd6da1d182bac1626b366285cce13c`, journal `379240db16df126fb1173de3c789a8cbcf58e33a2f67a19940c649a2b56b96d2`, reconciliation `2601fe70801883c9b8286e30a603aeabefc52681826f9b31ab782db615b7db50`, scope `044f2a210cdf770adcc77bf2076fd69164429b4537ab1f7a014b20150cdbc3cd` and Game Session PostgreSQL/mTLS `cfe8163275c615aac7de40a1cfcc577fed1f8224e05d4c381d0b1f4865d629c7`. + +The broader Account integration task executed 355 methods with one failure: `AccountAuthenticationUuidIntegrationTest.emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce` reported `UnfinishedStubbingException` at its direct Spring-proxy stubbing line. Commit `b16642830b3bf8206979c48f05054562b6d7cd60` had replaced the underlying Mockito target with that proxy; the fixture correction restores target stubbing while retaining the real repository method and actual owner-transaction assertion. The available CI summary has no detailed stack trace, so this attribution is source/log evidence, not proof that the correction executes successfully. The new World epoch checkpoint is propagated by normal merge, with Account's unique patch preserved; exact corrected/composed execution remains required. + The next held-back membership proof batch composes an already committed fresh-UUID canonical JOIN with the real Account producer, transaction manager, default response serializer and a physical mutual-TLS listener. Two Account definitions cover exact snapshot readback without source mutation and wrong-workload, wrong-namespace and missing-client-certificate rejection before producer access. A separate Game Session cross-service definition uses its actual `AccountMembershipAuthorityClient`, including complete recipient evidence validation, exact request echoes and unknown-tenant denial. The workflow requires these exact methods without skips. The corrected full Account check/JAR/format/analyzers/docs passes in 1m12s (72 tasks: 18 executed, 54 up-to-date), with 943 clean unit executions and 351 integration cases skipped without Docker. The focused Game Session cross-service check, corresponding Checkstyle/SpotBugs, formatting and boot JAR pass in 12s (114 tasks: 18 executed, 96 up-to-date); its three PostgreSQL/TLS methods compile and skip without Docker. Initial compile checks caught a generic Mockito spy overload and a fresh-versus-retained fixture helper call; the corrections preserve typed sources, transactions and assertions. Workflow lint and documentation hygiene pass. These fixtures stipulate upstream JOIN caller and policy evidence; membership readback binds the Account/tenant pair, not realm/catalog admission. No test definition or Docker-free skip proves PostgreSQL/TLS execution, registry authorization, authenticated JOIN ingress, runtime activation or an enabled membership RPC. The eighteen Account and seventy-one Game Session protobuf configuration-cache problems discard those entries; successful checks are not cache-support proof. The corrected harness at `f2242c536f33ec0b5372abfaa74d502e8c0b9278` has executed PostgreSQL proof: [CI37281117744](https://github.com/benhook1013/FireMUD/actions/runs/37281117744) Account job `111669309085` completed successfully. All eighteen then-required methods passed without skips: eleven retained-role, two immutable-journal and five fresh-JOIN cases. Independently parsed full raw suites pass JOIN 51/51, journal 2/2, canonical JOIN reconciliation 9/9 and canonical scope 4/4. The artifact merge `f12c3fc70407ea6a58fbc1c187c184f46684ff65` has the exact World `0bb5da90df09a82e2456811066cb6320b3380ee9` and Account source parents and a tree identical to the source head. Exact checkout logs were unavailable while the aggregate remained active; the observer ended on the successful Account job, not aggregate green. Independently rehashed XML: JOIN `1751fed703c66eb030a6bf86a082dd17c68ed4dda10e91b45533321653952f79`, journal `ec604aa8bb9f2adb3e81e8e112c9ed1bce832c1447b1ca2d5f90817ce105dd3e`, canonical reconciliation `d4ba3ada5d24860d1ebeeecd399a7b803c79131105c8539313a091c7b10c564f`, canonical scope `7b2a0eae5a432fd2f5287401ed83f0cf2f4ba1736f887c4d330f255f2c6d757e`. This closes those fixture-correction execution gaps; it does not execute the subsequent three fresh-UUID physical transport/consumer definitions or establish authenticated JOIN, a complete authorization bundle or activation. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 033cbb9647..4a33c39fd8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -106,13 +106,15 @@ static void configure(DynamicPropertyRegistry registry) { @BeforeEach void observeOwnerTransaction() { + AccountEmailLoginChallengeRepository challengeRepositoryTarget = + AopTestUtils.getUltimateTargetObject(challengeRepositorySpy); doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); invocation.callRealMethod(); return null; }) - .when(challengeRepositorySpy) + .when(challengeRepositoryTarget) .lockAccountChallenge(anyLong()); } From 1a3122769f1251e6773838fe140788d5dcf20f99 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:09:01 +1300 Subject: [PATCH 6/6] docs(account): record corrected OTP and physical source proof --- .../implementation-tracking/player-access-and-session.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 ca1a1946e2..c827b82302 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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. + At exact `b5cf5ae01bf546657c7601919ba704b99a56d939`, [CI37284046862](https://github.com/benhook1013/FireMUD/actions/runs/37284046862) completed with aggregate failure, Account job `111678940179` failure and Game Session job `111678940188` cancellation of unestablished cause. Nevertheless, independently parsed raw XML proves all twenty required Account cases passed without skips: eleven retained-role, two journal, five fresh-JOIN and two new physical mTLS cases. The actual Game Session client PostgreSQL/mTLS suite passed all three cases without skips, including fresh positive readback, exact retry, authenticated request echoes, wrong/unknown identity rejection and no source mutation. Full Account raw suites pass JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. Checkout logs and verified merge `1db0f4d5075cd980b90dc64c90a61daec2586ab5` establish exact World `0bb5da90df09a82e2456811066cb6320b3380ee9` and Account source parents; merge tree `d432827ecf4edd022ca6e50f8f0071f02ba87c0b` matches the source tree. This closes these physical producer/consumer component execution gaps, not authenticated upstream JOIN, realm/catalog admission, current-parent composition, registry authorization or activation. Root rehashed JOIN `05d7ec0f8b4365088530c0683d506c19eacd6da1d182bac1626b366285cce13c`, journal `379240db16df126fb1173de3c789a8cbcf58e33a2f67a19940c649a2b56b96d2`, reconciliation `2601fe70801883c9b8286e30a603aeabefc52681826f9b31ab782db615b7db50`, scope `044f2a210cdf770adcc77bf2076fd69164429b4537ab1f7a014b20150cdbc3cd` and Game Session PostgreSQL/mTLS `cfe8163275c615aac7de40a1cfcc577fed1f8224e05d4c381d0b1f4865d629c7`. -The broader Account integration task executed 355 methods with one failure: `AccountAuthenticationUuidIntegrationTest.emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce` reported `UnfinishedStubbingException` at its direct Spring-proxy stubbing line. Commit `b16642830b3bf8206979c48f05054562b6d7cd60` had replaced the underlying Mockito target with that proxy; the fixture correction restores target stubbing while retaining the real repository method and actual owner-transaction assertion. The available CI summary has no detailed stack trace, so this attribution is source/log evidence, not proof that the correction executes successfully. The new World epoch checkpoint is propagated by normal merge, with Account's unique patch preserved; exact corrected/composed execution remains required. +The earlier `b5cf5ae` Account integration task executed 355 methods with one failure: `AccountAuthenticationUuidIntegrationTest.emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce` reported `UnfinishedStubbingException` at its direct Spring-proxy stubbing line. Commit `b16642830b3bf8206979c48f05054562b6d7cd60` had replaced the underlying Mockito target with that proxy; the fixture correction restores target stubbing while retaining the real repository method and actual owner-transaction assertion. That earlier summary lacked a detailed stack trace; the corrected method subsequently executed successfully at `3440d4d` above. The World epoch checkpoint was propagated by normal merge, preserving Account's unique patch. This is not proof of later parent alignment or aggregate CI success. The next held-back membership proof batch composes an already committed fresh-UUID canonical JOIN with the real Account producer, transaction manager, default response serializer and a physical mutual-TLS listener. Two Account definitions cover exact snapshot readback without source mutation and wrong-workload, wrong-namespace and missing-client-certificate rejection before producer access. A separate Game Session cross-service definition uses its actual `AccountMembershipAuthorityClient`, including complete recipient evidence validation, exact request echoes and unknown-tenant denial. The workflow requires these exact methods without skips. The corrected full Account check/JAR/format/analyzers/docs passes in 1m12s (72 tasks: 18 executed, 54 up-to-date), with 943 clean unit executions and 351 integration cases skipped without Docker. The focused Game Session cross-service check, corresponding Checkstyle/SpotBugs, formatting and boot JAR pass in 12s (114 tasks: 18 executed, 96 up-to-date); its three PostgreSQL/TLS methods compile and skip without Docker. Initial compile checks caught a generic Mockito spy overload and a fresh-versus-retained fixture helper call; the corrections preserve typed sources, transactions and assertions. Workflow lint and documentation hygiene pass. These fixtures stipulate upstream JOIN caller and policy evidence; membership readback binds the Account/tenant pair, not realm/catalog admission. No test definition or Docker-free skip proves PostgreSQL/TLS execution, registry authorization, authenticated JOIN ingress, runtime activation or an enabled membership RPC. The eighteen Account and seventy-one Game Session protobuf configuration-cache problems discard those entries; successful checks are not cache-support proof.