diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb9f99ad1b..cbc9db43c9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1068,6 +1068,10 @@ jobs: npm run format -- -c working-directory: web-client + - name: Run email-link regression tests + run: npm run test:email-link + working-directory: web-client + - name: Run first-invoice checkout regression tests run: npm run test:checkout working-directory: web-client @@ -1186,7 +1190,8 @@ jobs: permissions: contents: read id-token: write - timeout-minutes: 60 + # The fourth partition needs time for static analysis and proof retention after integration tests. + timeout-minutes: ${{ matrix.partition == '4' && 75 || 60 }} strategy: fail-fast: false matrix: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 25b0e5c379..ef1ddb5bd5 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -615,11 +615,11 @@ jobs: const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { - "dev-tools/verify-smoke-images.sh": "6597800feb9604921a55be989e70247ec4610f81ac8c203f038429c1be7d0bc7", + "dev-tools/verify-smoke-images.sh": "67660c9c0c18441f626f5ecf611584e8e17930d5f84e3c3f33b64eac59fc0bb5", "dev-tools/smoke/smoke_common.py": "523a3986814fcbdf91531ccc98fa36f3901ed91d311436870ae1a958f9e8bd18", "services/game-session-service/websocket-login-look-smoke.sh": "7f10f11a36bc758ca5556e67c63cbcd5e3b67b893945a461d52f39958a4f15ad", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", - "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", + "dev-tools/smoke/held-admission-qualification.sh": "bbc693808495c0dce0e11cfdbc074c8eba8924cc5172f5d6ca33af96ba15f83d", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", "dev-tools/smoke/run-owned-compose.sh": "7b96cb02d5414283264c4d5e9a1b85ae063ada35dc834696f9016e520583a960", "dev-tools/certs/ensure-dev-certs.sh": "b94f8b1a18d53c818528d1fe31caa5d4270ad324dad6408aeaf896cdbf5f2e2b", diff --git a/build.gradle.kts b/build.gradle.kts index 1bdbe0ae08..6a2f145294 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -448,6 +448,19 @@ subprojects { } filter.setIncludePatterns(*includePatterns.toTypedArray()) filter.setFailOnNoMatchingTests(false) + // Required Account owner-local physical proof must execute in this + // job, not replay cached/up-to-date XML. Compile and unit tasks + // retain their normal cache behavior; unrelated partitions do too. + val requiredAccountPhysicalClasses = setOf( + "integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest", + "integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest", + "integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest" + ) + if (project.name == "account-service" && name == "integrationTest" && + selectedClasses.any { it in requiredAccountPhysicalClasses }) { + outputs.upToDateWhen { false } + outputs.doNotCacheIf("Required Account physical proof must execute") { true } + } } } } diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index c8576ba8df..33160da200 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -20,6 +20,18 @@ Public pruning is not implemented by this receiving boundary: it supplies no aut Account is the API boundary for platform identity, durable membership, entitlement authority, and Account-owned authentication mutations. This document retains endpoint and transport consequences; gameplay admission and JOIN identity binding are defined by [Authentication](../../system-architecture-authentication.md), while token refresh, replacement, generation, revocation, fencing, and logout are defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.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 first `tenantAdmin` of a newly created tenant is established by Account's [tenant-creation path](#tenant-creation-current-authorization-read), not by this mutation contract or public `JOIN`. + +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 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. 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 freshness evidence contract](./runtime-and-data.md#membership-and-entitlement-authority). 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. + +The mutation path stays unavailable until authenticated operator ingress exists: a `tenant_regular` control-UI route that verifies the actor at the owner commit. Authorization of a retained member whose current role snapshot is not owner-proven is an open prerequisite; such a member's role rows are not backfilled or admitted by this policy. + ### 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. @@ -36,6 +48,12 @@ Supported reads and downloads, including any controlled export the product suppo Decline or missing reacceptance does not itself cancel a subscription, delete content, decide a refund, or change billing or entitlement state. Subscription and billing consequences remain independent under [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) and the Account subscription lifecycle; payment or continued hosting never implies hosted-terms acceptance or marketplace enrollment. Future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +### Account-Owned Hosted-Terms and Draft Evidence + +Account selects the hosted-terms scope through trusted current environment authority, not caller-selected scope or tenant roles. The environment binding is a separate `HOSTED_TERMS` source identified by `environment-boundary/`, with an independent positive source version; the catalog and affirmative party acceptance remain separate evidence. Capture external environment authority outside Account transactions, then lock and reread the binding, catalog, party, acceptance and deadline in the writable owner transaction. A disclosed effective date is not extended by unresolved owner work, and a source observation is not a through-commit authorization token. + +The exact `account-draft-authorization-fence/v2` binding carries the ordered required-owner set, original operation, commit, fence, inputs and source evidence. Syntactic validity is not authenticated or complete owner selection. Settlement uses the original binding and immutable owner readbacks: missing, unknown or mixed outcomes remain pending and cannot release an unresolved source mutation. Exact historical reads do not mint fresh actor authority. Component registration, producer coverage and proof limitations are recorded in [the donor component checkpoint](../../../project-management/implementation-tracking/player-access-and-session.md#account-draft-and-hosted-terms-donor-component-checkpoint). + ### Original Creator Callback Authorization For fresh current-actor callbacks, Account observes its existing clock after the final blocking owner operations and immediately before invoking the callback. The original ControlUI issuance must have whole-second `issuedAt = iat = nbf`, with zero skew, and one clock observation must satisfy `issuedAt <= now < expiresAt`. Account does not rewrite the token, registry cleanup deadline, source evidence, or retained order. Exact historical recovery of an already-held original order remains separate and may proceed after creator expiry. Global token profile, signature, and key contracts remain defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). @@ -52,6 +70,8 @@ Both terminal-read transports retain the complete original binding and complete ### Account-Owned Playtest Grant Contract +Current containment: legacy `POST` and `DELETE /internal/runtime/realm-access-grants` retain existing privilege and input checks but return `AUTH_UNAVAILABLE` before dispatch; direct legacy service calls likewise refuse before repository access. This does not implement the canonical mutation transport described below or change existing read behavior. + Account is the sole writer and read authority for non-public realm grants under [ADR 0138 (PLAYTEST-01)](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). The canonical grant identity is `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}`, with `playtestLifecycleId` immutable for the lifecycle; the record carries active/revoked state, monotonic `grantRevision`, `grantExpiresAt`, grantor/audit metadata, and the stable `requestId` outcome. `tenantAdmin` may create, extend, list, and revoke grants only within the exact tenant it administers. Authenticated `platformAdmin` may create, extend, revoke, or deliberately re-grant only through a distinct reasoned and audited `privileged_control`/break-glass grant-mutation branch governed by [Operator Authorization References](#operator-authorization-references) and [operator delegation](../../system-architecture-authz-route-matrix.md#operator-delegation). The branch requires an Account-issued authorization reference bound to the typed grant action, exact target and current playtest lifecycle, canonical `mutationDigest/v1` digest, live `platformAdmin` role, exact target-tenant generation, and `privileged_control` evidence. The grant's stable `requestId` remains the domain idempotency identity; the operator flow's `controlPlaneRequestId` is a separate correlation identity, and the reference binds both. The branch carries an explicit reason and audit attribution, is distinct from `tenantAdmin`, and is not tenant impersonation or a gameplay grant. Both paths validate the exact tenant, world, realm, account, and current playtest lifecycle; a slug or caller-supplied tenant identifier is not proof. The unregistered `AccountCurrentLifecycleRealmGrantReadOwner` composes a read through the exact Game Session workload with Account's five-field grant storage. The finite peer-qualified source call runs outside Account SQL; a separate bounded Account read transaction evaluates its retained grant or tombstone against the exact selected lifecycle and minimum grant/fork expiry. Missing source, a different current lifecycle, revocation and expiry do not fall back to legacy grants. Its result is explicitly as-of: even an active grant has `admissionAllowed=false` while preparation remains incomplete, and this read supplies neither mutation authorization nor a cross-owner commit hold. The source transport and preparation limits belong to [Game Session API Contracts](../game-session-service/api-contracts.md#initial-fresh-playtest-lifecycle-source-preparation). @@ -139,6 +159,8 @@ Fresh-enrollment certification is internal Account owner work, not a public regi ## Implementation Status +Authenticated tenant-role mutation is unavailable; no role-mutation route, RPC, or service is enabled. The existing operation journal is storage only and is described in [Runtime & Data](./runtime-and-data.md#tenant-role-operation-journal); source, implementation, and proof gaps are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#old-stack-account-receiving-preparation). + The UUID billing foundation archives numeric subscription rows as immutable, non-authorizing retained evidence and supplies canonical intent, provisioning, lifecycle and cancellation-recovery storage. It also prepares the distinct [`TENANT_OPERATION` source and protected transport](#private-tenant-operation-entitlement-read); these owners remain manually composed and unregistered. Detailed receiving proof and unfinished authority boundaries belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The public WORLDS/REALMS, browser/direct JOIN and CHARS facades now delegate to explicitly composed canonical UUID owners and the retained V2 reader; absent composition returns `AUTH_UNAVAILABLE` before legacy sources. JOIN captures actual Account intent/member/pair/role/event/audit state, reads protected Game Session/World and provider sources outside SQL, then revalidates in its final Account transaction. Existing ACTIVE membership returns its truthful snapshot without repair; INACTIVE restoration advances its membership version/event. `gameplayAdmissionAllowed` is an explicit result and a successful membership response cannot grant gameplay when false. @@ -153,7 +175,7 @@ The initial private gameplay LOGIN owner, signer, registry, and response-recover Account UUID generation currently has three established provenances: `ACCOUNT_REPOSITORY_INSERT` uses `AccountRepository` and `UUID.randomUUID()`; `ACCOUNT_V29_MIGRATION` uses `gen_random_uuid()` for retained rows; and `ACCOUNT_DATABASE_INSERT` uses the `gen_random_uuid()` database default. These current producer outputs are RFC 4122 version 4 UUIDs. This records generator provenance and does not claim that database constraints reject custom UUID versions. -This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. +This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 retains its runtime gap, and abandoned-`PENDING` JOIN recovery remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps). `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. @@ -294,6 +316,12 @@ The response echoes the exact request scope and includes `CURRENT_AT_REVALIDATIO The handler returns `PERMISSION_DENIED` for a caller that is not the exact verified workload peer, `INVALID_ARGUMENT` for malformed scope or request shape, and `FAILED_PRECONDITION` when current owner evidence is absent or contradictory. Account source unavailability maps to `UNAVAILABLE`; other read or evidence-production failures map to `INTERNAL`. No partial evidence is returned on failure. +### Canonical Issuer Authority Source Read + +The manually composed `AccountIssuerAuthoritySourceService.ReadCurrentIssuerAuthoritySource` method requires the exact same-namespace Game Session workload without an end-user caller context. Account reads the complete current issuer generation, source version, valid original enrollment or latest sealed source event, and stream checkpoint in one owner transaction. The response binds the reconciliation request identity, namespace and authenticated workload to that evidence. Exact revalidation compares the entire captured snapshot, including retained event bytes, against a fresh Account owner read. The method remains unregistered and carries no projection or signer mutation authority. + +The same unregistered service prepares `ReadExactIssuerAuthorityEvent` for retained issuer history. The caller supplies the exact positive outbox sequence, event ID, and sealed event digest with the same reconciliation identity and namespace. Value `0` identifies the initial checkpoint and has no event payload. Account reads the original event and the independently current checkpoint in one owner transaction. The client validates the canonical event bytes and selector, and requires exact byte equality if the selected event is the current head. A later issuer advancement does not change which historical event the request selects. The read carries no authority to update projections or signers. + ### Canonical public-production NEW admission lease source The local [AccountGameplayAdmissionLeaseService](../../../../protos/account/v1/account_gameplay_admission_lease.proto) carrier prepares the seven purpose-specific `AcquireGameplayAdmissionLease`, `FinalizeGameplayAdmissionLease`, `ReadGameplayAdmissionLease`, `AbortGameplayAdmissionLease`, `IssueOriginalNewGameplayCredential`, `ConfirmOriginalNewGameplayAdmission` and `AbortNeverAdmittedGameplayAdmissionLease` methods selected by [canonical session admission](../../system-architecture-session-behavior.md#canonical-public-production-new-admission). The intended peer is the exact same-namespace Game Session workload. Acquisition carries a transient initial LOGIN GSA credential and typed expected candidate/target values; those values remain comparisons against independently resolved current owners. Finalize, Read and Abort carry the complete unchanged original canonical lease bytes. Abort's absent decision remains unknown, and its cleanup reference represents an outstanding obligation. The expected candidate’s `issuer_id` is the exact Account issuer string; the manual authenticated owner joins it to the independently verified token and current issuer source/checkpoint, rather than accepting an equal generation as issuer identity. @@ -385,7 +413,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `POST` | `/auth/request-password-reset` | Request account-scoped password reset by normalized email with a neutral known/unknown response | | `POST` | `/auth/complete-password-reset` | Complete account-scoped password reset | | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | -| `POST` | `/auth/verify-email` | **Current public route.** Verify an account-scoped email token without a bearer JWT. The configured verification email still links to `GET /auth/verify-email`, which has no controller mapping; browser handoff to the public POST remains unavailable. See the separate link-routing gap in [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | +| `POST` | `/auth/verify-email` | **Current public route.** Verify an account-scoped email token without a bearer JWT. Configured mail links target the non-mutating `/verify-email#token=…` browser landing; explicit user submission invokes this POST. Deployed delivery and browser completion remain unproved. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/login-auth-modes` | Read primary login modes for the selected global Account; the current account selector is a canonical lowercase non-nil Account UUID. | @@ -417,8 +445,8 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. See [Current Receiver Composition](#current-receiver-composition) for the current held issuance boundary. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The Gateway path remains blocked; see [Current Receiver Composition](#current-receiver-composition) for the service and adapter boundary. The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. See [Current Receiver Composition](#current-receiver-composition) for the current held issuance boundary. `ConnectTokenResponse` and its OpenAPI schema exclude `jti`; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The Gateway path remains blocked; see [Current Receiver Composition](#current-receiver-composition) for the service and adapter boundary. The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery of an abandoned `PENDING` JOIN after an unknown commit outcome remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps), and Logging receipt receiver/readback remains at the Logging-owned boundary. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -427,7 +455,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco The listed Account UUID representation is implemented through the qualified ordinary receiving boundary, including Account-issued credentials, shared forwarding, caller-bound REST/profile use, and UUID-valued downstream Account references. Private numeric Account rows and the separate legacy numeric GameInstance owner/StartSession boundary remain distinct. Full token-profile/registry qualification, production custody and gameplay admission/activation remain held; proof status is in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -Current verification routing/auth status: base and production HTTP configurations allowlist public `POST /auth/verify-email`, which has no bearer requirement. The configured verification email remains a `GET /auth/verify-email` link with no controller mapping, and browser handoff to the public POST is not implemented; see the separate [verification-link routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). +Verification and password-reset emails open the read-only frontend landings `/verify-email#token=…` and `/reset-password#token=…`. The browser captures the fragment token in memory and removes it from the address before React mounts; loading the link does not mutate Account state. Explicit user submission posts JSON to `/api/account/auth/verify-email` or `/api/account/auth/complete-password-reset` through Gateway. Base and production configurations allow those POSTs without a bearer token; GET remains unavailable. The frontend uses a no-referrer policy and distinguishes rejected input from uncertain completion without automatically retrying mutations. Deployed frontend reachability and real email/browser proof remain required; see [Email and Notification Design](./runtime-and-data.md#email-and-notification-design). The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` handlers follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity), including PUT path/body equality. They enforce exact UUID `SessionContext` self-binding before private owner resolution, retaining current tenant-membership checks (`gameplayAdmissionAllowed` is not required), public policy vocabulary checks, and post-commit update notification. Legacy PUT rejects `HIDDEN_STAFF` before persistence; a successful update stores the supplied selectable policy. Normalizing retained legacy policy to `PRIVATE` applies to read/export projection without rewriting that row, not acceptance of the retired policy on update. These selectors do not authorize another Account's profile or activate the canonical tenant-qualified route, scoped tenant roles, or membership-authority-generation checks. The legacy route and its route/policy shape remain implementation drift. @@ -465,7 +493,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | +| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. Public `POST /auth/verify-email` is configured. The fragment-token browser landing requires explicit submission; loading the email link makes no Account mutation. Deployed mail/browser completion remains unproved. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | | Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms?tenantSlug={tenant}`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. Default discovery remains unavailable; JOIN and connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | @@ -499,7 +527,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response uses closed version-2 selectors and carries exact canonical `PLAYER_ADMISSION` evidence with `bundleVersion=2`. The evidence binds the exact target and `verifiedConnectScopeTokenHash`, the `sha256:`-prefixed lowercase SHA-256 of the exact UTF-8 scope bearer. Game Session compares the response target and independently computes that hash from its original request. The capacity commitment and replay carry the complete hash-bound evidence. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` independently binds the complete retained V2 scope tuple, and the initial LOGIN issuance token and registry hashes use their separate raw-hex grammar. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. -This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). +This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver is absent by default. Its isolated receiving configuration requires both the `isolated-player-admission-receiving` profile and `firemud.account.player-admission-receiving.enabled=true`, an independently supplied genuine Account owner, and a valid workload namespace. Every gRPC service binding retains the exact transport-derived Game Session guard. This opt-in configuration does not provision source authority or establish production registration; the isolated server still must supply mTLS and the bounded wire policy. The Game Session client remains manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). ### Private tenant-operation entitlement read diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 6cd30ebcf3..f5941bf4a6 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -47,8 +47,8 @@ Additional variables configure outbound email delivery and payment behavior: | `SMTP_USERNAME` | Username for SMTP auth | *(empty)* | | `SMTP_PASSWORD` | Password for SMTP auth | *(empty)* | | `SMTP_FROM` | From address for transactional emails | `no-reply@firemud.local` | -| `FIREMUD_MAIL_VERIFICATION_URL` | Public URL for email verification links | `http://localhost:8080/auth/verify-email?token=%s` | -| `FIREMUD_MAIL_RESET_URL` | Public URL for password reset links | `http://localhost:8080/reset-password?token=%s` | +| `FIREMUD_MAIL_VERIFICATION_URL` | Public URL for email verification links | `http://localhost:5173/verify-email#token=%s` | +| `FIREMUD_MAIL_RESET_URL` | Public URL for password reset links | `http://localhost:5173/reset-password#token=%s` | | `FIREMUD_PAYMENT_STRIPE_API_KEY` | Stripe API key used for payments | *(none)* | | `FIREMUD_PAYMENT_PLATFORM_FEE_PERCENT` | Unsupported creator-share substrate; implementations must ignore this variable and it cannot enable provider mutation. No legacy value is an approved fee policy. Any future FireMUD-managed creator-player fee remains target-only under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). | *(unsupported; unset)* | | `FIREMUD_AUTH_JWT_SECRET` | Inline JWT signing key material for local/dev or explicitly ephemeral stacks only (legacy compatibility; not for player-facing environments) | *(none)* | diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 5c4e2fc4c5..49f62e0dd8 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -72,7 +72,7 @@ ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.member ## Saga Participation -The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's directly callable offline delivery method submits the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's directly callable offline delivery method submits the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025 and is tracked in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps). These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 39995f8fe7..52811b39c9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -32,6 +32,8 @@ The manually composed admission acquisition owner reads the retained original Ac Account's initial private gameplay LOGIN source graph has an explicit default-off composition for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. The [configuration owner](./configuration.md#canonical-gameplay-login-receiving) specifies its required protected delivery and policy inputs. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. Conditional registration through the existing Account gRPC service does not provision signer enrollment, committed publication, key material or Redis custody; deployed ACL/TLS, consumer authorization, gameplay admission and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. +The current issuer projection publisher uses the versioned `account.game-session-delegation-authority-project-issuer.v2` owner script with unchanged projection payload v1. Before replacement, the Java owner verifies the complete retained canonical issuer event; the script then compares that exact prior byte image atomically using `ABSENT`, `PRESENT`, or `VERIFY`. Malformed retained evidence, a changed prior value, and unexpected expiry fail closed without repair or TTL refresh. The immutable v1 script and descriptor remain retained, but the current caller/catalog select only v2. This stricter caller contract retains `CLUSTER` reset sensitivity and `REQUIRES_CLUSTER_RESET`; its evidenced combination is caller v2 with payload v1, not mixed v1/v2 writers. Deployed writer fencing, reset/cutover custody and runtime activation are not established by this implementation. + Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V1013 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. The manually composed Java owner and current full migration lineage require PostgreSQL 18; the retained SQL reader’s historical PostgreSQL 16 predicate does not establish Java-owner or full-lineage support on that major. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. @@ -72,19 +74,19 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Current JOIN receiver composition and refusal boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis). The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Current JOIN receiver composition and refusal boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis). The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); recovery of an abandoned `PENDING` JOIN after an unknown commit outcome remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps), with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` and its Account/client persistence and reservation components are locally prepared but remain manually composed and unregistered; cross-implementation vector consumption, remaining physical PostgreSQL qualification, deployed custody, and selected-owner/final activation proof remain open. The [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the capability and proof status. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while abandoned-`PENDING` JOIN recovery after an unknown database commit remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps) and Logging receipt receiver/readback remains at the Logging-owned boundary. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` and its Account/client persistence and reservation components are locally prepared but remain manually composed and unregistered; cross-implementation vector consumption, remaining physical PostgreSQL qualification, deployed custody, and selected-owner/final activation proof remain open. The [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the capability and proof status. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. -The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. +The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes preserve their existing authentication, privilege and numeric input checks, then return `AUTH_UNAVAILABLE` without service dispatch. The corresponding legacy service mutations also refuse before Account or grant repository access. They cannot create, reactivate, revise or revoke grants, including retained tombstones. Existing reads remain unchanged and are not canonical lifecycle-bound authority. Canonical owner transport, authenticated attribution, lifecycle identity, revision, digest and request-replay proof remain required before any replacement mutation path can be enabled. Recovery/verification foundations are live. Password-reset completion now uses an owner-locked atomic token claim/consume, Account update, canonical event and operation receipt, and current-source readback; an unresolved prior source intent fences token/password mutation and returns retryable `AUTH_UNAVAILABLE` until an exact retry can establish its outcome. `AccountAuthoritySourceEventReadback` accepts only the supported closed-operation event shapes with their exact immutable operation receipts; generic Account authority events without that receipt remain unreadable as current source evidence and fail closed as `AUTH_UNAVAILABLE`. This does not establish complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. Exact retry, concurrent reuse, and physical PostgreSQL proof for this cut remain pending under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; abandoned-`PENDING` JOIN recovery remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps), Logging receipt receiver/readback remains at the Logging-owned boundary, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints require exact reservation-derived usage; eligibility reads and issuer-local counters cannot initialize or replace it. Forward installation audits the complete retained inventory once under a writer lock and refuses mismatches without repairing source rows. Thereafter a protected per-tenant/owner aggregate changes only with database-validated reservation insertions and state transitions. Deferred usage checks use primary-key point reads rather than summing lifetime finalized or released history. Fresh zero aggregates require the same new-tenant bootstrap authority; direct aggregate writes, deletion and truncation remain forbidden. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. New-attempt current-source qualification follows the usage-row lock, with a fresh database-clock check before mutation. The additive V1046 deferred write guard also rejects original creation or rearm that is expired at transaction completion, rolling back any usage or history changes. Retained exact replay and same-attempt recovery do not renew authorization and remain available after expiry. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. @@ -96,6 +98,14 @@ The canonical gameplay LOGIN primary-credential adapter reuses Account’s passw Local unregistered Account owners now cover tenant-creation intent, admission, current authorization, and final initial-owner consent/reauthentication completion; the private Game Design receiver is also present. The dispatch and original read/close/recovery composition is present locally, while physical cross-owner qualification and public/default registration remain incomplete; creation and runtime admission are not enabled. The normative admission and recovery ordering belongs to [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md#account-tenant-creation-admission-receipt); implementation and proof status remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-creation-admission-preparation). +### Tenant-role operation journal + +V1048.1 adds the immutable-request, one-way-commit `account_tenant_role_operations` request/result journal and immutable `account_tenant_role_operation_members` event-evidence rows, accessed through `AccountTenantRoleOperationRepository`. It is storage only: there is no role-mutation service, authenticated caller ingress, route, or RPC, and nothing verifies an authenticated actor at the commit boundary or produces the complete Account authorization-evidence bundle. The mutation path stays unavailable until authenticated operator (`tenant_regular` control-UI) ingress exists, and authorization for a retained member without an owner-proven role snapshot remains an open prerequisite. The journal 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. Mutation authority and policy are owned by [Account API Contracts](./api-contracts.md#account-owned-tenant-role-administration). + +The closed persisted actions are `GRANT_DESIGNER`, `REVOKE_DESIGNER`, and `TRANSFER_TENANT_ADMIN`; a designer change records one member result and an administrator transfer records both affected member results in canonical Account UUID order. 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, 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. Capability and proof limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#old-stack-account-receiving-preparation). + ## Architecture and Runtime Notes - Stateless authentication uses exact short-lived JWT profiles for meta/control and gameplay bootstrap: @@ -105,7 +115,7 @@ Local unregistered Account owners now cover tenant-creation intent, admission, c Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile events and membership creation or restoration through `JoinPublicProductionMembership` use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a JOIN that creates or restores membership records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. An existing ACTIVE member commits `ALREADY_ACTIVE` without a new audit/outbox row. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and explicit JOIN membership creation or restoration append immutable Account audit envelopes in their respective local transactions. The `ALREADY_ACTIVE` outcome commits without a new audit row. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work; for membership creation or restoration, policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile events and membership creation or restoration through `JoinPublicProductionMembership` use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a JOIN that creates or restores membership records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. An existing ACTIVE member commits `ALREADY_ACTIVE` without a new audit/outbox row. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and explicit JOIN membership creation or restoration append immutable Account audit envelopes in their respective local transactions. The `ALREADY_ACTIVE` outcome commits without a new audit row. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work; for membership creation or restoration, policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; recovery of an abandoned `PENDING` JOIN remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps), and no periodic pending-operation reconciler is claimed. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and explicit JOIN membership creation or restoration use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). @@ -271,7 +281,7 @@ Runtime caller contract: - For a selected target confirmed as public production, fresh Account entitlement and fresh selected-target catalog/pointer/public-production evidence remain separate admission gates. `allowPublicJoin` is the enrollment predicate only: when membership is missing or `INACTIVE`, `false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while `JOIN_REQUIRED` is available only when fresh entitlement permits joining and the target evidence passes. An existing `ACTIVE` member is not denied connect-token issuance or `PLAY` solely because `allowPublicJoin=false`; the member must still pass all other fresh entitlement and admission checks, including `gameplayAvailable`. The target `allowNewGameplayBindings` field and enforcement are not currently available. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. - Target issuance also requires the shared replay-readiness record to be `OPEN` and binds its exact `replayAdmissionFence` into the signed token. Missing, unreadable, quarantined, or changing readiness fails closed before the token is exposed. - Minimum request fields: `connectScopeId`, `requestId`. - - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Dormant DTO/source-shape drift:** `ConnectTokenResponse` declares `jti`, and `ConnectTokenResult`/`AccountServiceImpl` do not carry `playtestLifecycleId` or `playtestStateGeneration` required for target non-public response metadata. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before constructing this response, so these fields are not a live HTTP response or token disclosure. + - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. The response DTO and OpenAPI schema exclude `jti`. **Dormant source-shape drift:** `ConnectTokenResult`/`AccountServiceImpl` do not carry `playtestLifecycleId` or `playtestStateGeneration` required for target non-public response metadata. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before constructing this response, so these fields are not a live HTTP response or token disclosure. - Target success delivery uses only `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is not returned in the response body or a response-header fallback. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before creating a token or cookie, so no current first-party WebSocket admission is established. Under the target flow, browser/mobile clients and first-party non-browser clients with a protected cookie jar remain cookie-only. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. @@ -296,6 +306,8 @@ Runtime caller contract: The target Account persistence shape is not current implementation: one Account-schema `connect_token_issuance_operation` record owns the exact `(accountId, tenantId, connectScopeId, requestId)` identity, Account-computed versioned request digest, lifecycle (`PENDING`, `COMMITTED`, deterministic `FAILED`, or `ABORTED`), token identity/hash and authority/postcondition evidence, and reconciliation metadata; it never stores a raw JWT. A separate bounded `connect_token_response_envelope` record is keyed to that operation and stores the exact success credential or deterministic failure only as an Account-encrypted envelope with its key/version and authenticated binding to the operation identity, digest, authority tuple, issuance fence, and applicable postconditions. Both records are Account-owned service-schema objects introduced and accessed through the service-local Flyway/jOOQ lineage; Redis remains only the reset-sensitive exact-result projection/cache. +The immutable request fingerprint version `1` is `sha256:<64 lowercase hexadecimal characters>` over RFC 8785 canonical JSON UTF-8 for one closed object containing exactly five string fields: `domain` fixed to `connect-token-request/v1`, `accountId` as the authenticated canonical non-nil Account UUID, `tenantId` as the verified scope's canonical non-nil tenant UUID, `connectScopeId` as the exact verified opaque scope value, and `requestId` as the exact request value. Scope and request values must be nonblank valid UTF-8 without U+0000 (NUL), bounded to 2048 and 128 bytes respectively; they are not trimmed, case-folded or Unicode-normalized. JSON escaping is canonical encoding, not identity normalization. Current authentication and exact scope provenance are separate preconditions, not established by hashing. A refreshed valid login for the same Account and same exact scope/request produces the same fingerprint; a different Account, tenant, scope or request is a different operation identity, never permission to read another identity's result. Bootstrap credential bytes, credential `jti`, current membership/version/generation, entitlement or routing observations do not participate in this immutable fingerprint. Scope validation remains at its existing owner; encoding does not accept an expired or changed scope as current authority. Deterministic failure recovery follows the retained-receipt rule below without reevaluating mutable membership; successful credential recovery still requires all current authorization and postcondition checks. No public route is activated by this encoding contract. + The operation identity is claimed by a serializable transaction or equivalent Account-owned CAS: one matching digest wins, a concurrent matching request waits for and reads the same operation, and any changed digest returns `IDEMPOTENCY_CONFLICT` without minting or mutating. Account records the durable operation before exposing a result, accepts and reads back the required registry/admission postconditions before `COMMITTED`, and exact retries revalidate current authority and all applicable registry/admission postconditions before decrypting and returning a successful credential envelope. If that revalidation fails, the retry returns the applicable canonical denial and leaves the committed operation and envelope unchanged; it does not remint or replace the credential. A deterministic `FAILED` result, such as `JOIN_REQUIRED`, replays its stored failure envelope directly after the exact operation identity and digest match, without rerunning authority or membership checks, while that failure envelope remains retained. If the matching compact receipt remains after its response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`; a changed digest still returns `IDEMPOTENCY_CONFLICT`. That outcome is terminal for the original issuance attempt and callers must use a new `requestId` for a fresh authorized request. Missing, ambiguous, or unreconciled durable state fails closed; no retry reconstructs or silently remints a JWT. The response envelope must not be removed while the operation is pending, ambiguous, or otherwise blocked on reconciliation. This target persistence/CAS/readback path is unimplemented and must not be inferred from the current Redis map. The target projection is physically isolated from the legacy map: `session:connect-token:v1:tenant::account::scope::request:` is target-only, while the unversioned family remains legacy-only. Because the legacy writer has no issuance fence, cutover requires closing issuance for the full Account cohort, stopping legacy writers, draining in-flight requests, waiting the configured maximum legacy TTL/retry horizon, and verifying that no legacy writer remains before enabling target issuance. A mixed-version rollout is not permitted unless every writer first honors a shared owner fence. Legacy entries are retained read-only through the TTL/retry horizon, then Account performs owner cleanup from an exact inventory with readback; they are not migrated, promoted, or interpreted as target envelopes. Region/tenant reset preservation follows the reset matrix for both families; after a cluster/cold-start loss, exact durable target repair/readback is required and otherwise the handshake fails closed. @@ -382,13 +394,13 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea ### Runtime Implementation Status and Drift -- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. +- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), abandoned-`PENDING` JOIN recovery (see the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps)), PostgreSQL execution, and direct text-client proof remain outstanding. -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; abandoned-`PENDING` JOIN recovery remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps), and Logging receipt receiver/readback remains at the Logging-owned boundary. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). -Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. +Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on abandoned-`PENDING` JOIN recovery, which remains open in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#active-gaps). No universal retention duration is implied. ## Monetization and Notification Domain Notes @@ -412,7 +424,7 @@ This service sends verification and password reset emails using a configured SMT Email verification uses the token association only to locate the Account, then locks the current complete Account row before claiming the exact original token. The conditional SQL consumption matches token row ID, opaque token, Account owner and original expiry, requiring expiry strictly after the captured process-local time. The claim and Account/source update share the writable owner transaction; losing, changed or expired claims cannot mutate Account state, and a failed source update rolls the claim back. Current password, role, email, login modes and UUID provenance come from that locked owner rather than the earlier partial token join. This preserves the existing local timestamp basis described above; it adds no cross-node timezone or retained-row migration claim. Focused implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment). -The configured default verification URL is a `GET /auth/verify-email` link, but Account exposes only `POST /auth/verify-email`; the GET has no controller mapping. Although the base and production HTTP configurations allow the POST as public, the configured mail link still requires an explicit browser handoff or matching GET handler to reach it. The default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). Deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live; see the canonical route/auth contract in [Account API Contracts](./api-contracts.md#rest-apis). +Configured verification and password-reset URLs target the static frontend fragment-token landings defined in [API Contracts](./api-contracts.md). The browser consumes tokens only after explicit submission through Gateway; merely loading an emailed link makes no Account mutation. Local Vite proxies `/api` to Gateway. Hosted reachability, SMTP delivery and fresh browser completion remain unproved until the static artifact and its edge routing are qualified on the exact deployment. The existing synchronous-delivery timing limitation above is unchanged. ## Original StartSession Source-Protection Storage diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 9d61684ca2..939e13af87 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -20,7 +20,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco ## Implementation Status -- Account's local canonical tenant/source-currentness and JOIN v2 persistence foundations do not change the direct-text REALMS-to-JOIN authority contract or prove that Game Session dispatches text JOIN; that #2898 capability remains incomplete, as does #2848 unknown-outcome recovery. +- Account's local canonical tenant/source-currentness and JOIN v2 persistence foundations do not change the direct-text REALMS-to-JOIN authority contract or prove that Game Session dispatches text JOIN; that #2898 capability remains incomplete, and recovery of an abandoned `PENDING` JOIN after an unknown commit outcome remains open in the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#active-gaps). - **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:** The existing Account connect-token surface and Gateway first-party cookie handshake fail closed while the canonical Account producer, shared replay-readiness fence, and dedicated Gateway key delivery remain unavailable. Game Session locally prepares complete signed-context verification, canonical current-target comparison, and exact retained-context recovery; bare first-party `LOGIN` and `PLAY` deny before legacy authentication or binding effects. These prepared consumers do not qualify issuance, gameplay admission, or a deployed end-to-end flow. Current capability and proof limits are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 4da81b127d..ff8f427eee 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -29,6 +29,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes. Their seed entries are Account Service `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` and Account Service `GetTenantEntitlementsForRuntime`; the latter records the exact Game Session or World Management caller alternatives. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - 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. +- 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. 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/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 16ae5dad6b..cb436b179d 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1971,7 +1971,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, IDEMPOTENCY_CONFLICT, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, IDEMPOTENCY_CONFLICT, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable @@ -2031,7 +2031,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] mutation_contract: explicit_public_membership_atomic exact_scope_revalidation: required: true diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index e8f90660fb..e557699c10 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -18,7 +18,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi ## Implementation Status -The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. +The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output. An unprivileged read-only static-container definition and opt-in preview Helm Deployment, Service and route split prepare the host boundary, including an `/auth/**` rewrite to Gateway. Both preview-stack and frontend enablement are required; hosted defaults keep the frontend disabled. Independent image publication and selection, public-site delivery and mail-origin configuration, running-host health/security/cache behavior, rollback, and bounded end-to-end browser proof remain unproved. Source and render preparation does not establish live delivery. + +The `/verify-email` and `/reset-password` landings capture fragment-only tokens in memory and scrub the address. Loading the page does not consume a token: an explicit user submission sends the Account POST. Account local mail defaults target these browser routes. Gateway default retries are GET-only; the client does not automatically replay an ambiguous completion. These prepared source boundaries do not prove SMTP delivery or the deployed browser-to-Gateway-to-Account journey. Account distributed credential-abuse policy and Gateway opaque rate-limit subject migration remain separate obligations. Explicit `JOIN`/`Join & Play` is target behavior, not a complete current runtime flow. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response exposes only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; current connect-token issuance and text `PLAY` proceed only when the two admission fields are true, and an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed. Explicit `JOIN`/`Join & Play` and the required connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remain unimplemented/proof gaps, so the current fail-closed result must not be read as an actionable join flow or as proof that the complete target sequence is implemented. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to the otherwise eligible current `membershipExists=false` or existing `gameplayAdmissionAllowed=false` cases; the latter cannot be classified as `INACTIVE`, and target lifecycle-specific handling of missing or `INACTIVE` membership remains target-only. Returning members and grant-backed private/playtest flows remain eligible only when the live membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unimplemented. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. @@ -244,7 +246,7 @@ WebSocket interactions for real-time gameplay are handled by `src/websocket.ts`, ## Hosting and Release Boundary -The target first-party static frontend boundary is required by the supported baseline. When implemented, preview and hobby/self-hosted deployments will serve the immutable `web-client` artifact from an unprivileged static host; production may use that host directly or place an approved CDN/object-store origin in front of the same artifact. The public site router keeps frontend documents and `/frontend-assets/**` separate from Gateway ingress, rewrites public `/auth/**` to Gateway's existing `/api/account/auth/**` route, preserves explicitly allowlisted `/api/{service}/**` and `/ws/game/**` ingress, and keeps the published `/assets/**` family separate; the reserved compiled-asset prefix does not SPA-fallback. The router/rewrite and end-to-end browser proof remain unimplemented. +The target first-party static frontend boundary is required by the supported baseline. When implemented, preview and hobby/self-hosted deployments will serve the immutable `web-client` artifact from an unprivileged static host; production may use that host directly or place an approved CDN/object-store origin in front of the same artifact. The public site router keeps frontend documents and `/frontend-assets/**` separate from Gateway ingress, rewrites public `/auth/**` to Gateway's existing `/api/account/auth/**` route, preserves explicitly allowlisted `/api/{service}/**` and `/ws/game/**` ingress, and keeps the published `/assets/**` family separate; the reserved compiled-asset prefix does not SPA-fallback. The opt-in preview chart prepares this router/rewrite, disabled by default; published image selection and end-to-end browser proof remain incomplete. The Telnet `LOGIN -> PLAY -> LOOK` hosted proof remains useful protocol evidence, but it is not a reason to defer the frontend boundary. The browser journey, static-host health/security/cache checks, independent frontend rollback, and versioned `PlayerOutput` consumer are separate implementation/proof obligations. A browser application may begin as a terminal-style client and grow richer UX without changing the static-host authority boundary. @@ -255,7 +257,8 @@ The frontend uses **Vite** for fast development and production builds: - `npm run dev` starts the local development server with hot module replacement. - `npm run build` produces an optimized bundle under `dist/`, with compiled assets under `dist/frontend-assets/` and the existing public base preserved in generated references. - `npm run preview` serves the production bundle locally for verification. -- `npm run test` runs unit tests with Jest and React Testing Library. The script runs the test suite. +- `npm run test:email-link` runs the TypeScript-aware Node tests for email-link completion. +- `npm run test:checkout` runs the selected Vitest/React Testing Library checkout and Account UI tests. - `npm run lint` and `npm run format` ensure consistent code style. - `npm run format:fix` writes formatting changes back to disk. - `npm run accessibility` audits the compiled site with axe-core. See [Developer Setup](../../DEVELOPER_SETUP.md#frontend-lint--accessibility) for Chrome requirements. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 4e840ecd3d..51df93a668 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -1,6 +1,6 @@ # Consequential Design Decision Inventory -Status: Inventory and human-led review are complete and independently coverage/fidelity-audited. All 182 historical archive decision keys and the six post-archive direct human decisions now have applied review provenance, for 188 current decision keys. Packet 6 is complete at 25 applied outcomes through ADRs 0151-0167. Packet 7 is complete at 17 applied outcomes through ADRs 0168-0178 plus clarifications to existing authority. The six direct decisions are `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, `OPS-07`, `EDGE-WITHDRAWAL-01`, and `TICK-20`; they are applied through ADRs 0179-0184 without changing historical Packet 1-7 totals. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. ADR numbering records how outcomes were materialized but does not define the application boundary; the planned whole-corpus authority review follows this completed decision integration. +Status: Inventory and human-led review are complete and independently coverage/fidelity-audited. All 182 historical archive decision keys and the seven post-archive direct human decisions now have applied review provenance, for 189 current decision keys. Packet 6 is complete at 25 applied outcomes through ADRs 0151-0167. Packet 7 is complete at 17 applied outcomes through ADRs 0168-0178 plus clarifications to existing authority. The six direct decisions are `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, `OPS-07`, `EDGE-WITHDRAWAL-01`, and `TICK-20`; they are applied through ADRs 0179-0184 without changing historical Packet 1-7 totals. The seventh, `AUTH-TENANT-ROLE-OWNER-01`, is applied through the Account tenant-role contract without an ADR. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. ADR numbering records how outcomes were materialized but does not define the application boundary; the planned whole-corpus authority review follows this completed decision integration. ## Implementation Status @@ -60,7 +60,7 @@ The merged Packet 6 P1-P3 baseline covered `340` discovered sources (`337` alloc | Microservice architecture | 76 covered paths (74 allocated evidence paths; 2 explicit governance/template exemptions) | 23 service-source rows = 22 distinct decisions (21 active + formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) + excluded historical `MS-AA-TOKEN-REVOCATION` alias; `MS-PO-OWNER-REMEDIATION` remains historical review evidence; stronger evidence for 41 existing keys | Complete in the historical source archive plus direct `HOSTED-TERMS-01` provenance | Complete and independently audited | | Specialized runtime architecture | 38 sources | 54 new; stronger evidence for 20 existing keys | Complete in the source archive | Complete and independently audited | | Product and operations architecture | 38 sources | 41 new; stronger evidence for 11 existing keys | Complete in the historical source archive plus the four earlier direct post-archive decisions; `EDGE-WITHDRAWAL-01` is recorded in this control ledger | Complete and independently audited | -| **Decision keys / navigation rows** | **All 357 design sources: 354 allocated decision-bearing sources (172 allocated non-ADR documents and 182 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 354 allocated and 3 total exemptions** | **188 current decision keys; 189 navigation/key rows including one historical service-scan alias** | **All 183 historical queue/navigation rows reviewed in the source archive plus six direct post-archive decisions** | **All 188 current decision keys have outcomes applied; Packet 1-7 remains complete through ADR 0178 and six direct post-archive decisions are applied through ADR 0184, including TICK-20 / ADR 0183** | +| **Decision keys / navigation rows** | **All 357 design sources: 354 allocated decision-bearing sources (172 allocated non-ADR documents and 182 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 354 allocated and 3 total exemptions** | **189 current decision keys; 190 navigation/key rows including one historical service-scan alias** | **All 183 historical queue/navigation rows reviewed in the source archive plus seven direct post-archive decisions** | **All 189 current decision keys have outcomes applied; Packet 1-7 remains complete through ADR 0178, six direct post-archive decisions are applied through ADR 0184, including TICK-20 / ADR 0183, and `AUTH-TENANT-ROLE-OWNER-01` is applied through the Account contract** | ## Legacy ADR Alias Navigation @@ -385,6 +385,7 @@ Packet 2 historical-alias rule: `MS-AA-TOKEN-REVOCATION` is a superseded service - [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] `TICK-20` — `accepted` on 2026-10-04; human owner delegated the technical choice to the Overseer, who selected acceptance; [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.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 ### Post-Archive Clarification Of Existing Decision 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 5bd988b9d5..6098d2b3ad 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,14 @@ The run-owned Compose demo completes canonical LOGIN, WORLDS, REALMS, JOIN, PLAY Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. +### Old-stack Account receiving preparation + +The consolidation receiver preserves the explicit email verification/reset browser handoff from donor #2861: [`EmailLinkLanding.tsx`](../../../web-client/src/EmailLinkLanding.tsx) and [`emailLinkLanding.ts`](../../../web-client/src/emailLinkLanding.ts) retain fragment tokens only in memory, scrub the address before mounting and dispatch only on explicit user submission. Current Account checkout routes remain intact. The focused [email-link tests](../../../web-client/tests/email-link.test.mjs) pass all 12 cases, the existing checkout suite passes all 96 cases, and the TypeScript/Vite build passes. This is local component proof, not deployed static delivery, browser/SMTP proof or donor retirement. The recovered static packaging remains default-off, with Stripe.js next-action origins reconciled into its CSP; image publication, edge routing and actual browser CSP proof remain activation prerequisites. + +The received Gateway auth catalog is restricted to the twelve explicit Account authentication endpoints and their declared HTTP methods, rather than forwarding the entire `/api/account/auth/**` subtree. Email verification and password-reset completion are POST-only. Catalog and predicate tests cover all declared methods and reject wrong methods, extra path segments and unknown auth endpoints; the existing public bootstrap-join denial remains in force. This is source and local predicate proof, not fresh-image forwarding or public activation proof. + +The unregistered tenant-role operation journal from donor #2998 is also being received on the current migration history as V1048.1. It preserves immutable request/result and membership-event evidence without a public mutation route. The retained-membership snapshot/actor authorization and role-mutation owner prerequisites remain unresolved; the current fresh-tenant reader cannot stand in for retained-member authority. The focused digest, journal and mail-configuration JVM proof passes 13 cases with zero failures/errors using explicit Mockito startup instrumentation; integration-test compilation, affected Java formatting, link checks and Markdown lint also pass. On the received source at `2371268`, focused native PostgreSQL execution now passes both journal cases with zero failures, errors or skips: immutable original-byte retry after a later role operation with changed-intent rejection, and atomic rollback of the operation journal with its member evidence. This is journal-only proof, not retained-member authorization or a role-mutation capability. + ### Temporary canonical PLAY transition exception The [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) covered the earlier classified backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE` after successful LOGIN, held-admission qualification, and authenticated cleanup. Its recorded outcome is diagnostic evidence for labeled exact PR comparisons. The #3461 → #3474 → #3481 stack leaves `canonical-play-transition` unset and uses normal Smoke Gate qualification. @@ -364,6 +372,14 @@ Unchanged Common proof remains 1,001 cases from R65; R69 passed 49 Game Session Game Session prepares the unregistered public-target discovery and full creation-source reads, alongside the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). Genuine source custody, created-roster consumption, runtime registration, successful public admission and activation remain future gaps, as do the broader UUID runtime and CHARACTER_CREATE owners. +### Unregistered Account character-creation producer handoff + +The recovered CHARACTER_CREATE producer is adapted to the current Account bootstrap verifier and an independently authenticated public `PLAYER_CREATED` target. Its dedicated selector owner retains and exactly reads the existing V2 scope without widening the PRESEEDED realm owner. Identity is revalidated after source reads and after protection commit; revocation prevents delegation but never releases an ambiguous protection. + +[AccountCharacterCreateRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateRepository.java) and V1049 retain immutable intents, owner protections and exact terminal settlements. Shared acquisition uses the existing sorted source locks without treating another protection as a writer; actual source writers and deferred source changes remain fenced until a definitive original settlement. The SQL boundary rejects malformed or mismatched terminal wire bytes and exact original/protection bindings. Authenticating Entity and validating complete domain evidence remain the [Entity client's](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateEntityClient.java) responsibility, not a property supplied by a digest or SQL row. + +Focused unit and real PostgreSQL source tests cover the recovered boundaries, including pending-operation coexistence, malformed settlement refusal, immutable rows and source-writer exclusion. The PostgreSQL fixture stipulates upstream membership and entitlement observations; it is not genuine cross-owner authority or public runtime proof. This handoff remains unregistered and restricted to the donor's public-production, non-paid-demo path. Private realm grants, complete genuine cross-owner producer/consumer qualification and route activation remain separate obligations. It does not restore the cancelled PLAY side task, enable character allocation through a registered endpoint, close the entire donor note, or authorize historical source retirement. + ### Retained Draft authorization fence migrations The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. @@ -468,7 +484,7 @@ Game Session now carries a default-off source path for current route and publish This recovery-scheduling handoff points to the [canonical sealed-roster retention prerequisite and its current proof/status](gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite) and the [Game Session canonical roster selection and reference ownership contract](../../architecture/microservices/game-session-service/runtime-and-data.md#canonical-roster-selection-and-reference-ownership); this path remains non-admitting and does not activate PLAY or LOOK. -The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898 and [abandoned-`PENDING` JOIN recovery](#active-gaps) gaps and capability statuses remain unchanged. ### Game Logic intake client shutdown @@ -628,6 +644,14 @@ The current correction's initial focused selection passes 71 fresh cases with ze The local follow-up on `8870a062` qualifies bounded complete public-read requalification for proven owner movement under one immutable anchor and incoming deadline, locked first enrollment and independent established-pin reads. It preserves terminal genuine tamper, the exact three-trial exhaustion boundary, writer-window receipt/deny behavior and default-off composition. After observed owner movement, retry API/SQL outage, missing resource, cancellation or deadline expiry is terminal; ordinary first-trial outages retain their previous behavior. Queued initial readers leave the monitor once another caller has installed the immutable pin. The historical-key fingerprint case now pins and positively loads the valid source before testing actual missing/substituted retained keys with a newly generated same-kid modulus; earlier passing selections did not prove that substitution. Final affected focused qualification passed 84 fresh cases: 47 trusted-source, 17 desired-state repository, 6 publication repository, 7 prepublication service and 7 physical PostgreSQL cases. The earlier 81-case run remains attributed to its earlier source; initial fixture failures are retained separately. The 84-case checkpoint is retained as its own source baseline. A bounded continuation distinguishes fully verified stable prepublication and exact-owned-data resource-version-only temporary classifications from dependency failure after movement; final affected continuation qualification passed 87 fresh cases (50 trusted-source, 17 desired-state repository, 6 publication repository, 7 prepublication service and 7 physical PostgreSQL), including both stable temporary controls, version-only moving-bracket requalification and retained terminal outage/cancellation, three-trial and tamper controls. Current LOGIN status is selectable default-off dispatch/composition, and prepared-deny recovery follows the linked two-read Game Session owning gate; historical source proof retains its original registration scope. +### Account canonical JOIN history and retry proof + +A test-only follow-up to Account `8731a005` passes 55 selected native PostgreSQL cases: ten [authority-storage cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java), 29 [canonical JOIN cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java), eleven canonical scope-persistence cases and five paid first-JOIN cases, with zero failures, errors or skips. Three added cases prove direct retained-event UPDATE/DELETE refusal followed by valid append/head advance, two real owner transactions contending on the Account lock and retaining one exact membership/event/audit/terminal receipt, and migration waiting for a legacy writer without inventing UUID, role or event authority. Enabled integration analysis and Java formatting pass. + +The upgrade witness preserves the committed logical identity and unverified membership fields. Its row version remains unchanged through V40; the published V40.1 STORED generated retention column then changes the physical heap and `xmin`, as expected for [PostgreSQL's documented table rewrite](https://www.postgresql.org/docs/current/sql-altertable.html), while logical evidence remains exact through the later migrations. The first overbroad unchanged-`xmin` assertion failed and is retained as failed evidence, not counted as a passing aggregate. These are owner-local component proofs with fixture-controlled caller, tenant and entitlement inputs, not production caller authentication, transport/runtime activation, a background JOIN reconciler, an obsolete numeric-to-UUID conversion path or whole-donor #2976 consumption. + +The canonical Account partition aggregate additionally requires the distinct current-JOIN [55-case contract](../../../dev-tools/validation/account_current_join_required_cases.json), alongside the unchanged hosted-terms/Draft contract. Every current named case must be present once and green in its proven partition, and the complete partition union must include all four families. Two scope-persistence parameterized methods use method-specific display names so identical boolean labels cannot substitute for each other; duplicate-case refusal remains intact. This guard retains the existing same-run/source artifact provenance and integration-task freshness checks. It does not establish the six legacy donor obligations as literally recovered, background or expiry-worker behavior, old conversion semantics, or runtime activation. + ### Direct-text JOIN client and command receiving preparation The local preparation adds a typed `JOIN` command/parser, Account scope/JOIN clients, immutable request retry, response-bound world selection, observed proxy UUID and separate numeric transport-session correlation, a bounded original-menu snapshot, and the [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion). These are manually composed sources; no production receiving registration or admission authority is established. The [Authentication contract](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) owns caller-bound scope and logical JOIN attempts, the [Redis menu contract](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu) owns menu storage and recovery, and [Redis Ops Access](../../architecture/system-architecture-redis-ops-access.md) records the missing protected-connection binding and deployed ACL. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion) owns SQL retention and ordering consequences. @@ -680,7 +704,7 @@ The newer inactive consumer adds exact mTLS World acquisition/identity and lifec The exact-head artifact and the historical owner/history suite results are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof), including the limitation that the aggregate artifact does not map the earlier job's failures one by one. The `AA-2.1` capability remains partial because namespace-aware atomic takeover, final Account admission, runtime activation, and live playable proof are still open. -The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898, [abandoned-`PENDING` JOIN recovery](#active-gaps), and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. @@ -694,7 +718,7 @@ Account's persisted UUID now backs registration REST/gRPC output and the Account Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account-local explicit public-production JOIN writer and durable audit outbox/producer retry components remain prepared source without default production composition. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally. Its default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account-local explicit public-production JOIN writer and durable audit outbox/producer retry components remain prepared source without default production composition. Logging & Admin receipt persistence/readback belongs to the Logging-owned boundary and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally. Its default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Recovery of an abandoned `PENDING` JOIN after an unknown database outcome remains open under the Overseer decision (see [Active Gaps](#active-gaps)); PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -735,7 +759,7 @@ With canonical scope consumers absent from the default composition, Account conn | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; profile and legacy runtime/export tenant IDs remain numeric, while public bootstrap, direct-text scope and JOIN results follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary); full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. Recovery of an abandoned `PENDING` JOIN after an unknown database commit outcome remains a separate open gap under the Overseer decision (see [Active Gaps](#active-gaps)); do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml); [bounded capacity owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java); [original-NEW final owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [Account/Game Session capacity composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java); [native final-admission evidence](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | Bounded reservation/final-admission source and focused proof are prepared but unregistered; [strict capacity status](#strict-tenant-capacity-owner-preparation) records the executed and unrun boundaries and remaining production qualification. The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | @@ -768,7 +792,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. The target non-public discovery flow requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. With default composition absent, Account bootstrap discovery and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured discovery follows the [Account API canonical receiver paths](../../architecture/microservices/account-service/api-contracts.md), while connect-token validates bootstrap identity and reads scope but remains held before cached-success replay or issuance. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for the held boundary and preserved obligations. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. Prepared Account JOIN persistence components and the local `POST /auth/bootstrap/join` route remain, but their default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. Manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The current Gateway guard still blocks external exposure; the held boundary and preserved positive obligations are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. Prepared Account JOIN persistence components and the local `POST /auth/bootstrap/join` route remain, but their default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. Manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The current Gateway guard still blocks external exposure; the held boundary and preserved positive obligations are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. Recovery of an abandoned `PENDING` JOIN after an unknown database outcome remains open (see [Active Gaps](#active-gaps)), as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -776,6 +800,10 @@ The Account-authorized request flow forwarded to Game Session remains target-sta Live Account authentication hashes and verifies passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with character-array handling and post-use wiping. Profile, external-account persistence/service scaffolds, recovery and verification, notification, payment, subscription, and virtual-currency surfaces have live foundations; the unsupported caller-asserted external-link REST route is removed and denied at the public edge. The broader account lifecycle state machine, server-verified provider linking, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial or unavailable as tracked below. +#### Bounded two-member transfer capture preparation + +The unregistered AccountTransferCaptureRepository prepares fresh-tenant observations of two Account owners in one writable transaction, acquiring both Account locks in canonical UUID-string order before reading membership evidence. TransferCaptureCodec preserves bounded immutable observations and rejects inconsistent membership generations on both observed construction and direct decoding. This is not actor authentication, transfer permission, mutation intent, runtime registration or current authority recovered from historical bytes; retained-tenant provenance remains unsupported. The isolated predecessor proof passed eight focused unit cases and six PostgreSQL cases, including reverse-order lock contention and unchanged stored rows, plus affected static checks and formatting. Receiving-head qualification on Account bucket parent `c10ee148` passes six freshly executed PostgreSQL cases, eight unit cases restored from the matching Gradle task cache, affected main/test/integration static checks, formatting and documentation checks. The cached unit results retain their predecessor timestamps and are not fresh executions. This does not complete donor #3097. + #### Ordinary Account authentication owner preparation The authentication owner-preparation component enforces the existing Account UUID/provenance/source-row owner at ordinary control-UI authentication, gameplay password authentication, verified-email OTP completion, and player-bootstrap issuance. After successful credential and lifecycle checks, issuance requires the existing UUID lookup to resolve back to the authenticated row before challenge consumption, signing, or session mutation. Missing, nil, inconsistent, or unavailable identity evidence returns `AUTH_UNAVAILABLE`; invalid-credential behavior remains separate. That component adds no Account UUID storage, mapping subsystem, schema, wire/profile transition, or downstream activation. The qualified owner-preparation checkpoint retained numeric authentication/bootstrap results and JWT Account claims; the published bootstrap-only credential and scope transitions are recorded below, followed by the current unpublished ordinary UUID receiving preparation. @@ -888,6 +916,10 @@ Earlier admission-preparation proof remains limited to its named owners and cont ### Admission and Gameplay Binding +The dormant Account connect-token persistence prerequisite now has separate immutable operation receipts and encrypted-response envelope storage. Exact identity is uniquely claimed; digest and outcome rewrites, post-completion envelope replacement and premature or unreconciled envelope erasure are rejected by PostgreSQL. Compact receipt deletion remains disabled pending the owner safe-watermark implementation. Six physical PostgreSQL integration cases pass for terminal-envelope atomicity, committed and deterministic-failure envelope retention, no reinsertion after erasure, and observed duplicate-claim lock serialization; enabled integration Checkstyle, SpotBugs and Java formatting also pass. This is storage proof only: canonical request-digest production, ciphertext authentication, authoritative issuance evidence, successful replay revalidation, API conflict/recovery-expired classification, safe-watermark cleanup, and the unregistered issuer/access layer remain incomplete. No endpoint, registry, scheduler or activation is enabled. + +The unregistered storage-only classifier accepts an explicitly supplied, format-validated retained digest; it does not construct or authenticate that digest, expose ciphertext, mint, or authorize successful replay. The combined twelve-case PostgreSQL suite passes with no skipped cases, including real concurrent terminal-commit readback after a blocking owner lock. Receipt locking and the subsequent envelope query share one pinned owner connection; the separate query avoids the reproduced pre-wait outer-join snapshot error. Enabled main/integration Checkstyle, SpotBugs and Java formatting pass. Production digest construction remains held: Account Runtime and Data requires a versioned digest but does not define the preimage, ADR 0021 step 5 does not settle that mapping, and the JWT-contract link to Authentication's connect-token-issuance-api heading has no matching current heading. Retained-history searches for that anchor and the explicit names connectTokenRequestDigest and connect-token-request/v1 found no authoritative definition. The owner choice is between stable canonical request/caller identity and additional bootstrap or changing authority inputs, which would change retry behavior. The recommendation, not an adopted contract, is stable request/caller identity with current authority checked separately on successful replay; credential bytes and live authority versions should not be invented as digest inputs. + Trusted proxy, first-party, bootstrap, and connect-token inputs fail closed before they can establish or preserve routing state. Signed actor identity requires canonical, matching non-nil UUID `sub` and `accountId` claims. Gameplay routing requires a complete positive bundle of `tenantId`, `gameInstanceId`, `worldSlug`, `realmSlug`, and `pointerVersion`; blank slugs, partial bundles, stale pointers, mismatched world/realm targets, and malformed claims are rejected before routing reuse or persistence. Game Session owns the canonical admitted-runtime normalization through `GameplayAdmissionPointerSnapshots`. `LoginCommandHandler` and `SessionRoutingNormalizationService` validate strict runtime identity while remaining scope-agnostic about `playableStateScope`; command-routing-authoritative seams such as `CommandServiceImpl` enforce scope-aware durable routing metadata. Game Logic and Entity Management receive a complete-or-absent admitted routing bundle and fail rather than consuming a partial one. Room identifiers are opaque text routing identities such as `R-*`, not positive numeric IDs. @@ -936,7 +968,7 @@ Shared coordination state carries reconnect/connect-context tracking, disconnect ### Account email verification and deferred currency containment -Local receiving work for #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. The later R1418 held-smoke result below supplies fresh local runtime qualification. The remaining #2848 JOIN reconciliation, receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. +Local receiving work from donor #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. The later R1418 held-smoke result below supplies fresh local runtime qualification. The remaining abandoned-`PENDING` JOIN recovery, Logging receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC before selector parsing or owner reads; five focused gRPC/REST cases pass, with the separate REST/service authorization retained. The local Helm namespace render and development-certificate retention contracts pass, together with scoped ShellCheck and documentation checks. New credential receivers use exact Game Session certificate identity for OTP and the separately gated [Account-local Entity demo fixture](../../architecture/microservices/account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture) for Authenticate only. The first credential aggregate fails a missing test assertion import before test execution. Its corrected source passes 162 fresh Account cases, including eleven physical loopback-mTLS cases with a mocked credential owner; six unchanged Entity demo cases are up to date, not fresh executions. Subsequent main/test analysis recoveries pass after removing an unnecessary constructor suppression and retaining the channel shutdown return value; the eleven physical cases pass again without failures, errors or skips. These are separate scoped results across retained failed aggregates, not one complete Account suite or genuine credential verification. The later R1418 held-smoke result below supplies the current local runtime result. @@ -988,7 +1020,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the prepared local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox components, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The current JOIN receiving method denies before invoking that prepared writer. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the prepared local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox components, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The current JOIN receiving method denies before invoking that prepared writer. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while abandoned-`PENDING` JOIN recovery remains open (see [Active Gaps](#active-gaps)) and Logging receipt receiver/readback remains at the Logging-owned boundary. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. The #3224 candidate adds an explicit held-admission image-smoke mode: it preserves the existing isolated backend `LOGIN` -> `PLAY` -> `LOOK` proof and checks that real Gateway and Telnet public paths fail closed while admission readiness is out of service. This is separate from successful public admission. The focused transport and image-environment contracts pass. Fresh source-built held-admission qualification on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` passes from 2026-10-16 05:20:30 to 05:27:42 UTC: the run-owned Gateway public listener receives the first-party loopback request outside configured TCP-proxy trust and returns exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`; Telnet returns `startup_unavailable` and closes; the direct backend completes `WORLDS`, `LOGIN`, `PLAY`, `LOOK` and `LOGOUT`. Canonical teardown completes and independent exact-project inspection finds no containers, networks or volumes. This proves the held mode and isolated backend flow; it does not prove Kubernetes Service endpoint withdrawal or independent TCP Proxy Service readiness. Host-published Gateway ingress and successful public admission also remain unproved. @@ -1040,6 +1072,7 @@ The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled dem ## Active Gaps +- Recovery of an abandoned `PENDING` JOIN operation after an unknown database commit outcome is open. The canonical first JOIN commits membership, event, audit and terminal receipt in one transaction and an exact retry replays the stored outcome under [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); no reconciler resolves an intent left `PENDING`, so ADR 0025 is not complete. Logging receipt receiver/readback remains at the Logging-owned boundary. - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. - Signup-time login-mode selection and authenticator-app TOTP enrollment/management are not implemented; the live credential contract remains password plus email OTP. Richer MFA policy for elevated users is also future work. - Tenant membership currently persists admission permission rather than the designed tenant-role set; Account JWT issuance does not emit tenant `scopedRoles`, and realm grants have no expiry or tenant-admin management surface. @@ -1052,7 +1085,7 @@ The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled dem - Gameplay presence classification ignores global roles and derives elevation only from explicit current-tenant gameplay roles. Production tenant-gameplay-grant qualification remains incomplete as recorded in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence); no staff impersonation or hidden-observer mode is part of the target. - Account hard-delete currently fails closed; retained payment and subscription lifecycle and deletion reconciliation remain incomplete. - The billing-owner deletion precondition does not yet inspect nonterminal canonical UUID subscriptions. Once the retained-JOIN blocker is clear, a canonical-only billing owner receives `ACCOUNT_DELETE_UNAVAILABLE` instead of `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER`. Account's retention/deletion owner must add the canonical current-owner check and positive/negative proof before enabling deletion, preserving retained-history blockers; see [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). -- Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on #2848 JOIN receipt and unknown-outcome reconciliation. No universal retention duration is selected. +- Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on abandoned-`PENDING` JOIN recovery, which remains open above. No universal retention duration is selected. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. - The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. @@ -1075,3 +1108,23 @@ No competing target state is currently recorded. Future design discussion is req | Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | + +### Legacy realm-grant mutation containment receiving + +The Account consolidation carries the fail-closed boundary from #2923 (`c8444bb1`): legacy internal POST/DELETE preserve privilege and input checks but refuse before service dispatch; direct legacy grant/revoke calls refuse before Account or grant lookup/mutation. Existing grant reads and tombstone storage are unchanged. Focused receiving proof passed 4 MockMvc controller cases and 333 Account service cases, with no failures or skips; production and test compilation also passed. These are controlled local fixtures, not deployed ingress or database qualification. The canonical lifecycle-qualified mutation owner, authenticated transport, attribution and replay proof remain open; this containment grants no new authority or runtime activation. + +## Account Draft and Hosted Terms Donor Component Checkpoint + +The unregistered `AccountHostedTermsService` retains immutable catalog publication, affirmative individual acceptance, exact publication recovery and environment-bound currentness. Its environment binding is a separate `HOSTED_TERMS` source identified by `environment-boundary/`, with an independent positive source version. The bound catalog and exact party acceptance are separate evidence, not a caller-selected scope or permission inferred from tenant roles. Publication and individual-action collaborators in component tests are stipulated authorities, not qualified production publishers or live legal acceptance. + +Current environment authority is captured outside Account transactions. The service-issued capture is then checked by the same service instance while its writable owner transaction locks and rereads the binding, catalog, party, acceptance and deadline. Scheduled catalog evidence retains its disclosed effective date; unresolved owner work cannot extend prior acceptance beyond that date. This source evidence is not a through-commit authorization token. Actual publisher custody, protected caller composition, consumer commit-bound checks and runtime registration remain separate gates. + +The retained `account-draft-authorization-fence/v2` binds an exact ordered required-owner set and original operation, commit, fence, inputs and source evidence. Syntactic validity does not prove authenticated or complete owner selection. Settlement reads the original binding and immutable owner readbacks: missing, unknown or mixed outcomes remain pending rather than replacing original evidence or releasing an unresolved source mutation. Required owners without an implemented authenticated reader remain pending. An exact historical read does not mint fresh actor authority. + +Current PasswordReset and LogoutAll owner components persist waiting source intent before refusing unresolved Draft outcomes. Their exact retries preserve that intent; an explicit reset source-abort also refuses while affected owner outcomes remain mixed. Physical component proofs use persisted Account provenance and actual SQL transactions but stipulate presented token and remote owner evidence. They do not restore absent legacy JOIN, issuer, tenant-creation or publication producers, enable authoring, or establish whole-donor consumption. The forward receiving migrations are V76 (required owners), V85 (hosted terms) and V86 (environment binding); historical donor migration numbers are not new migrations to apply. + +### Overseer authority donor: bounded presence-policy membership filtering + +The received legacy tenant-scoped bulk policy query now requires an existing membership row for the exact Account and tenant pair using a correlated SQL `EXISTS`, without per-subject queries. This preserves the supplied authority-donor omission behavior: a retained profile alone cannot return a presence policy after its membership is absent. The canonical UUID batch/provenance checks and Social `PRIVATE`-by-omission behavior are unchanged. A focused native PostgreSQL test exercises the actual repository query against isolated projection tables: exact membership is retained, absent and other-tenant memberships are omitted, mixed batches and later membership insertion are handled, and all four seeded profile rows remain. This is query behavior proof, not forward-migration, current lifecycle/generation authority, full Social composition, or deployment proof. The broader 29-path authority handover and its remaining role/caller/runtime requirements remain incomplete. + +The Account request-fingerprint checkpoint implements the versioned closed RFC 8785 encoding owned by Account Runtime and Data. It binds the exact authenticated Account UUID, verified scope tenant and opaque scope, and request ID, not the current login credential or mutable membership state. The encoder is unregistered and returns only an existing classifier lookup; it neither authenticates inputs nor validates current scope, claims an operation, decrypts an envelope, mints, or mutates a registry. Earlier preimage uncertainty is superseded for this bounded encoding, not for the remaining active issuer, authentication-bundle, scope recovery, encryption or admission-CAS work. Validation passed 55 focused unit tests and 13 native PostgreSQL receipt tests with no skips, plus enabled main/test/integration Checkstyle and SpotBugs and Java formatting checks. The actual bootstrap verifier uses controlled parsed-token and current-session collaborators: refreshed same-account authentication preserves the fingerprint and inactive authentication is rejected; this is not cryptographic refresh proof. Existing scope-reader tests separately reject changed/expired scope evidence. The database test changes controlled membership-pair state from absent to present and preserves the exact retained JOIN_REQUIRED receipt and encrypted envelope, with no token JTI and no writes by classification. This is read-only storage behavior, not a real authorized JOIN, issuer/registry composition, encryption or successful-replay access revalidation proof. No public or runtime activation is implied. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 3e3b758ea7..636e028c4a 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -28,7 +28,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - previously recorded focused evidence remains attributed to its original sources; R1423 qualifies PLAYER-only creation/projection, cached-role read projection without persisting demotion or extending presence TTL, and ordinary field-preserving updates. Snapshot-bound pagination, current friendship/block revalidation, bounded-page proof, and production tenant-gameplay-grant qualification also remain incomplete. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [RedisGameplayPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java); [RedisAccountRecentPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java); [AccountClient.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [WhoCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java); [RedisAccountRecentPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java); [AccountClientTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Current Game Session has no independently verified gameplay-grant carrier, so new and returned presence uses `PLAYER`; JWT global/scoped claims and retained elevated cache roles do not elevate a presence projection. Read-side role demotion is projection-only and does not persist the role change or extend presence TTL; ordinary activity updates persist `PLAYER` while preserving the other presence fields. R1423 qualifies this bounded behavior through the Redis, WHO/reconnect units and real-Redis cases described below. Complete snapshot-bound pagination, current relationship/block revalidation, bounded-page proof, production tenant-gameplay-grant qualification, and broader authorization/disclosure proof remain open. Keep in-world concealment under gameplay policy before calling this capability proven. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | -| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, but this is not the independently released static player application boundary. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. No independently released static host/public-site routing or browser proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json) | No focused executable proof: `npm run lint` and `npm run build` from the [web-client package](../../../web-client/package.json) passed as general frontend validation and emitted the `dist/frontend-assets/` bundle, but no focused browser or independently released host proof exists. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, unprivileged static host and deployment, reserved-path routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | +| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - The received source includes the static host and disabled Helm routing. Local frontend build and enabled/disabled Helm render validation were recorded during receiving; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | The canonical [frontend validation workflow](../../../.github/workflows/ci.yml) contains frontend checks and the production bundle build. Local email-link component/build and Helm render checks were recorded during receiving; no fresh static-host image, running-host or deployed browser journey is claimed. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | ## Canonical Design Sources @@ -85,7 +85,7 @@ Focused source proof covers complete Common Security and Social unit suites, nat ### First-Party Frontend -- Current implementation: `web-client` is a React/Vite/MUI/TanStack Query baseline with a generic WebSocket envelope/JSON consumer that parses payloads as `unknown`, plus local feature/form state. Its Vite production build now emits compiled assets under `dist/frontend-assets/`; semantic structured `PlayerOutput` consumption, the complete admitted runtime-bundle asset bootstrap, independent immutable frontend artifact/release metadata, unprivileged static host, richer player UX, admin/design-tool integration, and end-to-end browser proof are not implemented. The target boundary and independent-release proof requirements remain in [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). +- Current implementation: `web-client` is a React/Vite/MUI/TanStack Query baseline with a generic WebSocket envelope/JSON consumer that parses payloads as `unknown`, plus local feature/form state. Its Vite production build now emits compiled assets under `dist/frontend-assets/`; source and opt-in preview preparation now includes an unprivileged static host and public-route split, but hosted values leave it disabled and no frontend image is published or deployed by this slice. Semantic structured `PlayerOutput` consumption, the complete admitted runtime-bundle asset bootstrap, independent immutable frontend artifact/release metadata, richer player UX, admin/design-tool integration, and end-to-end browser proof remain unimplemented or unproved. The target boundary and independent-release proof requirements remain in [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). ### Validation and Proof diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index dbca5d270f..a3fce48311 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -41,6 +41,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: ("batch/v1", "Job"), ("networking.k8s.io/v1", "Ingress"), ("networking.k8s.io/v1", "NetworkPolicy"), + ("traefik.io/v1alpha1", "Middleware"), } SERVICE_IMAGES = { "account-service", @@ -71,8 +72,17 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: GATEWAY_CLIENT_WORKLOADS = {"spring-cloud-gateway"} NAMESPACE_BOUND_GRPC_WORKLOADS = DISTINCT_GRPC_WORKLOADS | GATEWAY_CLIENT_WORKLOADS | {"logging-admin-service"} EXPECTED_NAMES = { - "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, - "Service": SERVICE_IMAGES | {"spring-cloud-gateway-mtls", "postgres", "redis-coord", "redis-cache", "minio"}, + "Deployment": SERVICE_IMAGES + | {"postgres", "redis-coord", "redis-cache", "minio", "frontend"}, + "Service": SERVICE_IMAGES + | { + "spring-cloud-gateway-mtls", + "postgres", + "redis-coord", + "redis-cache", + "minio", + "frontend", + }, "ConfigMap": {"firemud-config", "firemud-seed-sql"}, "PersistentVolumeClaim": {"postgres-data", "redis-coord-data", "redis-cache-data", "minio-data"}, "Job": {"firemud-seed"}, @@ -87,7 +97,15 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "spring-cloud-gateway-egress", "game-session-authenticated-gameplay-ingress", "tcp-proxy-service-egress", + "frontend-static-host", }, + "Middleware": {"firemud-preview-auth-path-rewrite"}, +} +FRONTEND_EXPECTED_NAMES = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, } EXPECTED_PVC_SPECS = { "postgres-data": { @@ -123,7 +141,12 @@ def walk(value: object, path: str = "object"): yield from walk(child, f"{path}[{index}]") -EXPECTED_OBJECTS = {(kind, name) for kind, names in EXPECTED_NAMES.items() for name in names} +EXPECTED_OBJECTS = { + (kind, name) + for kind, names in EXPECTED_NAMES.items() + for name in names + if name not in FRONTEND_EXPECTED_NAMES.get(kind, set()) +} TRUSTED_HOSTED_VALUES = Path(__file__).resolve().parents[3] / "k8s/helm/firemud/values-hosted-shared.example.yaml" @@ -174,6 +197,58 @@ def _trusted_database_images(values_path: Path) -> dict[str, str]: "account-service", "social-groups-service", ) +FRONTEND_IMAGE_REPOSITORIES = { + "ghcr.io/benhook1013/web-client", +} +FRONTEND_MIDDLEWARE_NAME = "firemud-preview-auth-path-rewrite" +FRONTEND_MIDDLEWARE_ANNOTATION = "traefik.ingress.kubernetes.io/router.middlewares" +FRONTEND_MIDDLEWARE_REFERENCE = re.compile( + rf"^pr-[1-9][0-9]{{0,50}}-{re.escape(FRONTEND_MIDDLEWARE_NAME)}@kubernetescrd$" +) +FRONTEND_MIDDLEWARE_SPEC = { + "replacePathRegex": { + "regex": r"^/auth(/.*)?$", + "replacement": r"/api/account/auth$1", + } +} +FRONTEND_SERVICE_SPEC = { + "selector": {"app": "frontend"}, + "ports": [ + { + "name": "http", + "port": 80, + "targetPort": "http", + "protocol": "TCP", + } + ], + "type": "ClusterIP", +} +FRONTEND_NETWORK_POLICY_SPEC = { + "podSelector": {"matchLabels": {"app": "frontend"}}, + "policyTypes": ["Ingress", "Egress"], + "ingress": [ + { + "from": [ + { + "namespaceSelector": { + "matchLabels": { + "kubernetes.io/metadata.name": "kube-system" + } + }, + "podSelector": { + "matchLabels": {"app.kubernetes.io/name": "traefik"} + }, + } + ], + "ports": [{"protocol": "TCP", "port": 8080}], + } + ], + "egress": [], +} +FRONTEND_RESOURCES = { + "requests": {"cpu": "10m", "memory": "32Mi"}, + "limits": {"cpu": "250m", "memory": "128Mi"}, +} EXPECTED_TOP_LEVEL_LABELS = { "app.kubernetes.io/name": "firemud", "app.kubernetes.io/managed-by": "Helm", @@ -236,9 +311,17 @@ def _exposure_mode_for_service_type(service_type: object) -> str: fail("validated TCP Proxy Service has no canonical exposure mode") -def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[str]]: +def _expected_names_for_mode( + certificate_identity_mode: str, + frontend_enabled: bool = False, +) -> dict[str, set[str]]: _validate_certificate_identity_mode(certificate_identity_mode) - expected_names = {kind: set(names) for kind, names in EXPECTED_NAMES.items()} + expected_names = { + kind: set(names) for kind, names in EXPECTED_NAMES.items() + } + if not frontend_enabled: + for kind, names in FRONTEND_EXPECTED_NAMES.items(): + expected_names.setdefault(kind, set()).difference_update(names) if certificate_identity_mode == "standalone": expected_names["NetworkPolicy"].difference_update( { @@ -250,6 +333,63 @@ def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[st return expected_names +def _frontend_render_enabled(documents: list[object]) -> bool: + """Detect the explicit frontend opt-in without trusting arbitrary objects.""" + + frontend_objects = { + (kind, name) + for kind, names in FRONTEND_EXPECTED_NAMES.items() + for name in names + } + frontend_paths = { + "/frontend-assets", + "/auth", + "/api", + "/ws/game", + "/assets", + } + for document in documents: + if not isinstance(document, dict): + continue + metadata = document.get("metadata") + name = metadata.get("name") if isinstance(metadata, dict) else None + if (document.get("kind"), name) in frontend_objects: + return True + if document.get("kind") != "Ingress": + continue + if ( + isinstance(metadata, dict) + and isinstance(metadata.get("annotations"), dict) + and FRONTEND_MIDDLEWARE_ANNOTATION in metadata["annotations"] + ): + return True + spec = document.get("spec") + if not isinstance(spec, dict): + continue + rules = spec.get("rules", []) + if not isinstance(rules, list): + continue + for rule in rules: + if not isinstance(rule, dict): + continue + http = rule.get("http") + if not isinstance(http, dict): + continue + paths = http.get("paths") + if isinstance(paths, list) and any( + isinstance(path, dict) and path.get("path") in frontend_paths + for path in paths + ): + return True + return False + + +def _expected_frontend_middleware_reference(expected_namespace: str) -> str: + if re.fullmatch(r"pr-[1-9][0-9]{0,50}", expected_namespace) is None: + fail(f"runtime namespace is not canonical: {expected_namespace!r}") + return f"{expected_namespace}-{FRONTEND_MIDDLEWARE_NAME}@kubernetescrd" + + def _is_tcp_proxy_identity_object(document: dict) -> bool: return document.get("kind") in {"Deployment", "Service"} and ( isinstance(document.get("metadata"), dict) and document["metadata"].get("name") == "tcp-proxy-service" @@ -855,6 +995,7 @@ def _validate_image_reference( location: str, value: str, expected_image_tag: str, + allow_frontend: bool = False, ) -> None: if value in INFRASTRUCTURE_IMAGES: return @@ -865,6 +1006,14 @@ def _validate_image_reference( if not separator or not repository or not tag: fail(f"{location} uses an untagged image") service = repository.rsplit("/", 1)[-1] + if service == "web-client": + if not allow_frontend: + fail(f"{location} uses an unapproved service image repository") + if repository not in FRONTEND_IMAGE_REPOSITORIES: + fail(f"{location} uses an unapproved frontend image repository") + if tag != expected_image_tag: + fail(f"{location} uses image tag {tag!r}, expected {expected_image_tag!r}") + return if service in SERVICE_IMAGES: if repository != f"ghcr.io/benhook1013/{service}": fail(f"{location} uses an unapproved service image repository") @@ -1168,6 +1317,161 @@ def validate_extra_security_fields(security: dict, security_path: str) -> None: fail(f"{path}.securityContext.windowsOptions.hostProcess is forbidden") +def _validate_frontend_image( + image: object, path: str, expected_image_tag: str | None = None +) -> None: + if not isinstance(image, str) or "@" in image: + fail(f"{path} must be an immutable tagged frontend image") + repository, separator, tag = image.rpartition(":") + if ( + not separator + or repository not in FRONTEND_IMAGE_REPOSITORIES + or not tag + ): + fail(f"{path} uses an unapproved frontend image") + if expected_image_tag is not None and tag != expected_image_tag: + fail(f"{path} uses image tag {tag!r}, expected {expected_image_tag!r}") + + +def validate_frontend_deployment( + document: dict, expected_image_tag: str | None = None +) -> None: + """Require the exact unprivileged static-host Deployment contract.""" + + name = document.get("metadata", {}).get("name", "frontend") + spec = _require_mapping(document.get("spec"), f"Deployment/{name}.spec") + if set(spec) != {"replicas", "selector", "template"}: + fail(f"Deployment/{name} has an unsafe frontend spec") + if spec.get("replicas") != 1: + fail(f"Deployment/{name} must have exactly one replica") + if spec.get("selector") != {"matchLabels": {"app": "frontend"}}: + fail(f"Deployment/{name} has an unsafe frontend selector") + template = _require_mapping( + spec.get("template"), f"Deployment/{name}.spec.template" + ) + if template.get("metadata") != {"labels": {"app": "frontend"}}: + fail(f"Deployment/{name} has unsafe frontend pod-template metadata") + pod = _require_mapping( + template.get("spec"), f"Deployment/{name}.spec.template.spec" + ) + expected_pod_security = { + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "fsGroup": 101, + "fsGroupChangePolicy": "OnRootMismatch", + "seccompProfile": {"type": "RuntimeDefault"}, + } + expected_pod_fields = { + "automountServiceAccountToken", + "securityContext", + "containers", + "volumes", + "imagePullSecrets", + } + if set(pod) - expected_pod_fields: + fail(f"Deployment/{name} has unsupported frontend pod fields") + if pod.get("automountServiceAccountToken") is not False: + fail(f"Deployment/{name} must disable the ServiceAccount token") + if pod.get("securityContext") != expected_pod_security: + fail(f"Deployment/{name} has unsafe frontend pod security") + if "imagePullSecrets" in pod and pod["imagePullSecrets"] != [ + {"name": "ghcr-preview-pull"} + ]: + fail(f"Deployment/{name} has an unsafe frontend imagePullSecret") + containers = _require_mapping_list( + pod.get("containers"), f"Deployment/{name}.spec.template.spec.containers" + ) + if len(containers) != 1: + fail(f"Deployment/{name} must contain exactly one frontend container") + container = containers[0] + container_path = f"Deployment/{name}.spec.template.spec.containers[0]" + expected_container_fields = { + "name", + "image", + "imagePullPolicy", + "securityContext", + "ports", + "readinessProbe", + "livenessProbe", + "resources", + "volumeMounts", + } + if set(container) != expected_container_fields: + fail(f"{container_path} has an unsafe frontend container shape") + if container.get("name") != "frontend": + fail(f"{container_path} has an unexpected name") + _validate_frontend_image( + container.get("image"), f"{container_path}.image", expected_image_tag + ) + if container.get("imagePullPolicy") != "Always": + fail(f"{container_path}.imagePullPolicy must be Always") + if container.get("securityContext") != { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "capabilities": {"drop": ["ALL"]}, + }: + fail(f"{container_path} has unsafe frontend container security") + if container.get("ports") != [ + {"name": "http", "containerPort": 8080, "protocol": "TCP"} + ]: + fail(f"{container_path} has an unsafe HTTP port") + expected_probe = { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 2, + "periodSeconds": 10, + } + if container.get("readinessProbe") != expected_probe: + fail(f"{container_path} has an unsafe readiness probe") + expected_liveness_probe = { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 5, + "periodSeconds": 20, + } + if container.get("livenessProbe") != expected_liveness_probe: + fail(f"{container_path} has an unsafe liveness probe") + if container.get("resources") != FRONTEND_RESOURCES: + fail(f"{container_path} has unsafe resource limits") + if container.get("volumeMounts") != [ + {"name": "nginx-tmp", "mountPath": "/tmp"} + ]: + fail(f"{container_path} has an unsafe temporary volume mount") + if pod.get("volumes") != [ + {"name": "nginx-tmp", "emptyDir": {"sizeLimit": "16Mi"}} + ]: + fail(f"Deployment/{name} has an unsafe temporary volume") + + +def validate_frontend_middleware(document: dict, expected_namespace: str) -> None: + name = document.get("metadata", {}).get("name", FRONTEND_MIDDLEWARE_NAME) + if document.get("apiVersion") != "traefik.io/v1alpha1": + fail(f"Middleware/{name} has an unsupported apiVersion") + if document.get("kind") != "Middleware": + fail(f"Middleware/{name} has an unexpected kind") + if document.get("spec") != FRONTEND_MIDDLEWARE_SPEC: + fail(f"Middleware/{name} has an unsafe spec") + if name != FRONTEND_MIDDLEWARE_NAME: + fail(f"Middleware/{name} is not the trusted frontend middleware") + _expected_frontend_middleware_reference(expected_namespace) + + +def _frontend_ingress_paths() -> list[dict]: + gateway = { + "service": {"name": "spring-cloud-gateway", "port": {"number": 80}} + } + frontend = {"service": {"name": "frontend", "port": {"number": 80}}} + return [ + {"path": "/frontend-assets", "pathType": "Prefix", "backend": frontend}, + {"path": "/auth", "pathType": "Prefix", "backend": gateway}, + {"path": "/api", "pathType": "Prefix", "backend": gateway}, + {"path": "/ws/game", "pathType": "Prefix", "backend": gateway}, + {"path": "/", "pathType": "Prefix", "backend": frontend}, + ] + + def _strip_annotations(value: object) -> None: if isinstance(value, dict): metadata = value.get("metadata") @@ -1195,12 +1499,22 @@ def _validate_no_annotations(value: object, path: str = "object") -> None: def sanitize(source: Path, destination: Path) -> None: """Produce the credential-free artifact consumed by the trusted workflow.""" + raw_documents = [ + raw + for raw in yaml.safe_load_all(source.read_text(encoding="utf-8")) + if raw is not None + ] + if any(not isinstance(raw, dict) for raw in raw_documents): + fail("render contains a non-object document") + frontend_enabled = _frontend_render_enabled(raw_documents) + expected_names = { + kind: set(names) for kind, names in EXPECTED_NAMES.items() + } + if not frontend_enabled: + for kind, names in FRONTEND_EXPECTED_NAMES.items(): + expected_names.setdefault(kind, set()).difference_update(names) documents = [] - for raw in yaml.safe_load_all(source.read_text(encoding="utf-8")): - if raw is None: - continue - if not isinstance(raw, dict): - fail("render contains a non-object document") + for raw in raw_documents: api_version = raw.get("apiVersion") kind = raw.get("kind") if kind in SANITIZER_FORBIDDEN_KINDS: @@ -1211,7 +1525,7 @@ def sanitize(source: Path, destination: Path) -> None: if not isinstance(metadata, dict) or not metadata.get("name"): fail(f"{kind} has no metadata.name") name = metadata["name"] - if not isinstance(name, str) or name not in EXPECTED_NAMES[kind]: + if not isinstance(name, str) or name not in expected_names.get(kind, set()): fail(f"{kind}/{name} is not an approved preview object") if metadata.get("namespace") in {"firemud-system", "kube-system"}: fail(f"{kind}/{metadata['name']} targets a control namespace") @@ -1226,6 +1540,42 @@ def sanitize(source: Path, destination: Path) -> None: pod, f"{kind}/{metadata['name']}.spec.template.spec", ) + if frontend_enabled and kind == "Deployment" and name == "frontend": + validate_frontend_deployment(raw) + if ( + frontend_enabled + and kind == "Middleware" + and name == FRONTEND_MIDDLEWARE_NAME + and raw.get("spec") != FRONTEND_MIDDLEWARE_SPEC + ): + fail(f"Middleware/{name} has an unsafe spec") + trusted_frontend_annotation = None + if frontend_enabled and kind == "Ingress" and name == "firemud-preview": + annotations = metadata.get("annotations") + if annotations is not None: + if not isinstance(annotations, dict): + fail("Ingress/firemud-preview annotations are not an object") + unexpected_annotations = set(annotations) - { + "cert-manager.io/cluster-issuer", + FRONTEND_MIDDLEWARE_ANNOTATION, + } + if unexpected_annotations: + fail( + "Ingress/firemud-preview has unsupported frontend annotations: " + f"{sorted(unexpected_annotations)}" + ) + trusted_frontend_annotation = annotations.get( + FRONTEND_MIDDLEWARE_ANNOTATION + ) + if trusted_frontend_annotation is not None and ( + not isinstance(trusted_frontend_annotation, str) + or not FRONTEND_MIDDLEWARE_REFERENCE.fullmatch( + trusted_frontend_annotation + ) + ): + fail( + "Ingress/firemud-preview has an unsafe frontend middleware reference" + ) sanitized = _clean_config_map(copy.deepcopy(raw)) if sanitized.get("kind") == "Service": name = sanitized["metadata"]["name"] @@ -1234,6 +1584,10 @@ def sanitize(source: Path, destination: Path) -> None: for port in ports: port.pop("nodePort", None) _strip_annotations(sanitized) + if trusted_frontend_annotation is not None: + sanitized.setdefault("metadata", {})["annotations"] = { + FRONTEND_MIDDLEWARE_ANNOTATION: trusted_frontend_annotation + } _validate_sanitized_secret_refs(sanitized) documents.append(sanitized) if not documents: @@ -1268,6 +1622,7 @@ def inject_telnet_port( if exposure_mode is not None and exposure_mode not in EXPOSURE_MODES: fail("preview exposure mode is not canonical") documents = list(yaml.safe_load_all(source.read_text(encoding="utf-8"))) + frontend_enabled = _frontend_render_enabled(documents) matches = [] ingress_matches = 0 for document in documents: @@ -1276,18 +1631,41 @@ def inject_telnet_port( metadata = _validate_object_metadata( document, expected_namespace, + allow_trusted_ingress_annotation=( + frontend_enabled + and document.get("kind") == "Ingress" + and isinstance(document.get("metadata"), dict) + and document["metadata"].get("name") == "firemud-preview" + ), certificate_identity_mode=certificate_identity_mode, ) namespace = metadata.get("namespace") if namespace not in (None, expected_namespace): - fail(f"{document.get('kind')}/{metadata.get('name')} targets namespace {namespace!r}") - if "annotations" in metadata: + fail( + f"{document.get('kind')}/{metadata.get('name')} targets namespace {namespace!r}" + ) + if "annotations" in metadata and not ( + frontend_enabled + and document.get("kind") == "Ingress" + and metadata.get("name") == "firemud-preview" + and metadata.get("annotations") == { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + } + ): fail("validated preview render retains untrusted annotations") metadata["namespace"] = expected_namespace if document.get("kind") == "Ingress" and metadata.get("name") == "firemud-preview": ingress_matches += 1 if certificate_identity_mode == "standalone": - metadata["annotations"] = {"cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER} + metadata["annotations"] = { + "cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER, + } + if frontend_enabled: + metadata["annotations"][FRONTEND_MIDDLEWARE_ANNOTATION] = ( + _expected_frontend_middleware_reference(expected_namespace) + ) if document.get("kind") != "Service": continue if metadata.get("name") != "tcp-proxy-service": @@ -1351,6 +1729,7 @@ def validate_runtime_target( documents = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) if not documents: fail("prepared preview render is empty") + frontend_enabled = _frontend_render_enabled(documents) node_ports: list[tuple[str, object, object]] = [] ingress_matches = 0 for index, document in enumerate(documents): @@ -1360,10 +1739,12 @@ def validate_runtime_target( document, expected_namespace, allow_trusted_ingress_annotation=( - certificate_identity_mode == "standalone" - and document.get("kind") == "Ingress" + document.get("kind") == "Ingress" and isinstance(document.get("metadata"), dict) and document["metadata"].get("name") == "firemud-preview" + and ( + certificate_identity_mode == "standalone" or frontend_enabled + ) ), allow_trusted_allocated_telnet_port=( document.get("kind") == "Service" @@ -1379,8 +1760,23 @@ def validate_runtime_target( if document.get("kind") == "Ingress" and name == "firemud-preview": ingress_matches += 1 expected_annotations = ( - {"cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER} - if certificate_identity_mode == "standalone" + { + **( + {"cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER} + if certificate_identity_mode == "standalone" + else {} + ), + **( + { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + } + if frontend_enabled + else {} + ), + } + if certificate_identity_mode == "standalone" or frontend_enabled else None ) if annotations != expected_annotations: @@ -1637,15 +2033,25 @@ def validate_service_consumers( fail(f"Deployment/{service} has an unsafe {volume_name} projection") -def validate_services(documents: list[dict], certificate_identity_mode: str = "standalone") -> None: +def validate_services( + documents: list[dict], + certificate_identity_mode: str = "standalone", + frontend_enabled: bool | None = None, +) -> None: """Require the exact trusted preview Service specs.""" _validate_certificate_identity_mode(certificate_identity_mode) + if frontend_enabled is None: + frontend_enabled = _frontend_render_enabled(documents) for document in documents: if document.get("kind") != "Service": continue name = document.get("metadata", {}).get("name") spec = _require_mapping(document.get("spec"), f"Service/{name}.spec") + if name == "frontend": + if not frontend_enabled or spec != FRONTEND_SERVICE_SPEC: + fail(f"Service/{name} has an unsafe frontend spec") + continue expected_spec = EXPECTED_SERVICE_SPECS.get(name) if expected_spec is None: fail(f"Service/{name} is not an approved preview Service") @@ -1694,16 +2100,37 @@ def _validate_gateway_egress_policy(policy: dict) -> None: fail("NetworkPolicy/spring-cloud-gateway-egress has an unsafe spec") +def validate_frontend_network_policy(document: dict) -> None: + name = document.get("metadata", {}).get("name", "frontend-static-host") + spec = _require_mapping( + document.get("spec"), f"NetworkPolicy/{name}.spec" + ) + if name != "frontend-static-host" or spec != FRONTEND_NETWORK_POLICY_SPEC: + fail(f"NetworkPolicy/{name} has an unsafe spec") + + def validate_network_policies( documents: list[dict], certificate_identity_mode: str = "hosted-controller", + frontend_enabled: bool | None = None, ) -> None: """Keep the runtime policy set and every allowed traffic exception exact.""" _validate_certificate_identity_mode(certificate_identity_mode) - raw_policies = [document for document in documents if document.get("kind") == "NetworkPolicy"] - policies = {document.get("metadata", {}).get("name"): document for document in raw_policies} - expected_names = _expected_names_for_mode(certificate_identity_mode)["NetworkPolicy"] + if frontend_enabled is None: + frontend_enabled = _frontend_render_enabled(documents) + raw_policies = [ + document for document in documents if document.get("kind") == "NetworkPolicy" + ] + policies = { + document.get("metadata", {}).get("name"): document + for document in raw_policies + } + expected_names = _expected_names_for_mode( + certificate_identity_mode, frontend_enabled + )[ + "NetworkPolicy" + ] if len(raw_policies) != len(policies) or set(policies) != expected_names: fail( "runtime NetworkPolicy set is not closed " @@ -1712,6 +2139,9 @@ def validate_network_policies( ) _validate_internal_network_policies(policies) + if frontend_enabled: + validate_frontend_network_policy(policies["frontend-static-host"]) + expected_from = { "namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "firemud-system"}}, "podSelector": { @@ -1847,6 +2277,7 @@ def validate_ingress( document: dict, expected_namespace: str, expected_hostname: str, + frontend_enabled: bool = False, ) -> None: """Require the complete trusted preview Ingress routing contract.""" @@ -1863,30 +2294,60 @@ def validate_ingress( if len(rules) != 1 or rules[0].get("host") != expected_hostname: fail("Ingress/firemud-preview has an unsafe host") http = _require_mapping(rules[0].get("http"), f"{ingress_path}.rules[0].http") - paths = _require_mapping_list(http.get("paths"), f"{ingress_path}.rules[0].http.paths") - if len(paths) != 1: - fail("Ingress/firemud-preview has an unexpected route set") - route = paths[0] - backend = _require_mapping( - route.get("backend"), - f"{ingress_path}.rules[0].http.paths[0].backend", + paths = _require_mapping_list( + http.get("paths"), f"{ingress_path}.rules[0].http.paths" ) - service_backend = _require_mapping( - backend.get("service"), - f"{ingress_path}.rules[0].http.paths[0].backend.service", - ) - service_port = _require_mapping( - service_backend.get("port"), - f"{ingress_path}.rules[0].http.paths[0].backend.service.port", - ) - if ( - route.get("path") != "/" - or route.get("pathType") != "Prefix" - or service_backend.get("name") != "spring-cloud-gateway" - or service_port.get("number") != 80 - ): - fail("Ingress/firemud-preview has an unsafe backend") + if len(paths) != (5 if frontend_enabled else 1): + fail("Ingress/firemud-preview has an unexpected route set") + if frontend_enabled: + if paths != _frontend_ingress_paths(): + fail("Ingress/firemud-preview has an unsafe frontend route set") + else: + route = paths[0] + backend = _require_mapping( + route.get("backend"), + f"{ingress_path}.rules[0].http.paths[0].backend", + ) + service_backend = _require_mapping( + backend.get("service"), + f"{ingress_path}.rules[0].http.paths[0].backend.service", + ) + service_port = _require_mapping( + service_backend.get("port"), + f"{ingress_path}.rules[0].http.paths[0].backend.service.port", + ) + if ( + route.get("path") != "/" + or route.get("pathType") != "Prefix" + or service_backend.get("name") != "spring-cloud-gateway" + or service_port.get("number") != 80 + ): + fail("Ingress/firemud-preview has an unsafe backend") + if frontend_enabled: + annotations = document.get("metadata", {}).get("annotations") + if annotations != { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + }: + fail("Ingress/firemud-preview has an unsafe frontend middleware reference") + expected_paths = ( + _frontend_ingress_paths() + if frontend_enabled + else [ + { + "path": "/", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + } + ] + ) expected_spec = { "ingressClassName": "traefik", "tls": [ @@ -1900,16 +2361,7 @@ def validate_ingress( "host": expected_hostname, "http": { "paths": [ - { - "path": "/", - "pathType": "Prefix", - "backend": { - "service": { - "name": "spring-cloud-gateway", - "port": {"number": 80}, - } - }, - } + *expected_paths, ] }, } @@ -1927,11 +2379,18 @@ def validate_manifest( certificate_identity_mode: str = "hosted-controller", ) -> None: _validate_certificate_identity_mode(certificate_identity_mode) - expected_names = _expected_names_for_mode(certificate_identity_mode) - expected_objects = {(kind, name) for kind, names in expected_names.items() for name in names} documents = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) if not documents: fail("manifest is empty") + frontend_enabled = _frontend_render_enabled(documents) + expected_names = _expected_names_for_mode( + certificate_identity_mode, frontend_enabled + ) + expected_objects = { + (kind, name) + for kind, names in expected_names.items() + for name in names + } seen: set[tuple[str, str]] = set() for index, document in enumerate(documents): if not isinstance(document, dict): @@ -1942,6 +2401,9 @@ def validate_manifest( metadata = _validate_object_metadata( document, expected_namespace, + allow_trusted_ingress_annotation=( + frontend_enabled and document.get("kind") == "Ingress" + ), certificate_identity_mode=certificate_identity_mode, ) name = metadata.get("name") @@ -1961,13 +2423,27 @@ def validate_manifest( pod, f"{document['kind']}/{name}.spec.template.spec", ) + if frontend_enabled and document["kind"] == "Deployment" and name == "frontend": + validate_frontend_deployment(document, expected_image_tag) if document["kind"] == "Ingress": - validate_ingress(document, expected_namespace, expected_hostname) + validate_ingress( + document, + expected_namespace, + expected_hostname, + frontend_enabled, + ) + if frontend_enabled and document["kind"] == "Middleware": + validate_frontend_middleware(document, expected_namespace) object_key = (document["kind"], name) if object_key in seen: fail(f"manifest contains duplicate {document['kind']}/{name}") seen.add(object_key) - _validate_no_annotations(document) + if frontend_enabled and document["kind"] == "Ingress": + without_annotations = copy.deepcopy(document) + without_annotations.get("metadata", {}).pop("annotations", None) + _validate_no_annotations(without_annotations) + else: + _validate_no_annotations(document) for location, value in walk(document): if location.endswith(".nodePort"): fail(f"{location} retains a PR-selected nodePort") @@ -1987,7 +2463,14 @@ def validate_manifest( fail(f"{location} contains an unapproved Secret reference") for location, value in walk(document): if location.endswith(".image") and isinstance(value, str): - _validate_image_reference(location, value, expected_image_tag) + _validate_image_reference( + location, + value, + expected_image_tag, + allow_frontend=( + document["kind"] == "Deployment" and name == "frontend" + ), + ) if document["kind"] in {"Deployment", "Job"}: _validate_workload_selector_metadata(document) if document["kind"] == "PersistentVolumeClaim": @@ -1996,8 +2479,10 @@ def validate_manifest( missing = sorted(expected_objects - seen) extra = sorted(seen - expected_objects) fail(f"manifest object set is not closed (missing={missing}, extra={extra})") - validate_services(documents, certificate_identity_mode) - validate_network_policies(documents, certificate_identity_mode) + validate_services(documents, certificate_identity_mode, frontend_enabled) + validate_network_policies( + documents, certificate_identity_mode, frontend_enabled + ) validate_infrastructure_deployments(documents) if ("Service", "tcp-proxy-service") in expected_objects: tcp_proxy_service = next( diff --git a/dev-tools/smoke/held-admission-qualification.sh b/dev-tools/smoke/held-admission-qualification.sh index 867c7dd760..acc004d387 100644 --- a/dev-tools/smoke/held-admission-qualification.sh +++ b/dev-tools/smoke/held-admission-qualification.sh @@ -8,6 +8,22 @@ fi HELD_ADMISSION_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +# The smoke mTLS profile enables pre-v1 gate waivers (ADR 0185): Gateway and TCP +# Proxy then admit gameplay and cannot stay held. A held request, such as the +# trusted default-branch refresh, runs the full baseline proof instead. Only the +# diagnostics contract may keep exercising the held wrapper. +apply_pre_v1_waived_admission_qualification() { + [[ "${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-}" == "held" ]] || return 0 + if [[ "${FIREMUD_SMOKE_TEST_MODE:-}" == "1" && "${SMOKE_TEST_HELD_IGNORES_WAIVERS:-}" == "true" ]]; then + return 0 + fi + if grep -Eq '^[[:space:]]*FIREMUD_PRE_V1_GATE_WAIVERS_ENABLED:[[:space:]]*"true"' \ + "$HELD_ADMISSION_REPO_ROOT/docker/docker-compose.grpc-mtls.override.yml"; then + echo "Held admission is unattainable with pre-v1 gate waivers enabled; running the baseline proof." >&2 + FIREMUD_SMOKE_ADMISSION_QUALIFICATION=baseline + fi +} + run_held_admission_qualification() { local gateway_api_base="${SMOKE_GATEWAY_API_BASE:-http://localhost:8080}" local tcp_proxy_api_base="${SMOKE_TCP_PROXY_API_BASE:-http://localhost:8089}" diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index cff412c91e..d6f382681a 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -596,12 +596,17 @@ groups = { "build-and-test-game-session": ("game_session_module_check_matrix", "game-session-service"), "build-and-test-world": ("world_module_check_matrix", "world-management-service"), } +timeouts = { + None: "${{ matrix.module == 'game-design-service' && 30 || 20 }}", + "account-service": "${{ matrix.partition == '4' && 75 || 60 }}", + "game-session-service": "90", + "world-management-service": "60", +} for job_id, (output, module) in groups.items(): job = ci["jobs"][job_id] name_module = module or "${{ matrix.module }}" require_equal(job, ("name",), "Build and Test (" + name_module + " / ${{ matrix.partition }})", job_id) - timeout = "60" if module in ("account-service", "world-management-service") else "90" if module == "game-session-service" else "${{ matrix.module == 'game-design-service' && 30 || 20 }}" - require_equal(job, ("timeout-minutes",), timeout, job_id) + require_equal(job, ("timeout-minutes",), timeouts[module], job_id) require_equal(job, ("needs",), ["changes"], job_id) require_equal(job, ("strategy", "fail-fast"), "false", job_id) require_equal(job, ("strategy", "matrix"), {"include": "${{ fromJSON(needs.changes.outputs." + output + ") }}"}, job_id) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 270e033bac..46ce8609ad 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -300,6 +300,19 @@ run_failure_diagnostic_regressions() { return 1 fi + # The smoke profile enables pre-v1 gate waivers, so a held request runs the baseline proof. + run_diagnostic_smoke_case held-waived false 0 false 0 "" held + if ! grep -Fq 'Held admission is unattainable with pre-v1 gate waivers enabled' "$ERR_FILE" || + ! grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE" || ! grep -Fq 'MOCK_TELNET_PROBE' "$OUT_FILE" || + grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held request under pre-v1 gate waivers did not run the baseline proof" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + # The remaining cases exercise the held wrapper itself. + export SMOKE_TEST_HELD_IGNORES_WAIVERS=true run_diagnostic_smoke_case held-success false 0 false 0 "" held if ! grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE" || ! grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE" || @@ -368,6 +381,7 @@ run_failure_diagnostic_regressions() { return 1 fi done + unset SMOKE_TEST_HELD_IGNORES_WAIVERS run_diagnostic_smoke_case config-only true 37 false 0 if grep -Fq 'MOCK_LOG service=' "$OUT_FILE" || grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE"; then diff --git a/dev-tools/tests/test_account_current_join_required_cases.py b/dev-tools/tests/test_account_current_join_required_cases.py new file mode 100644 index 0000000000..5159b2a1a9 --- /dev/null +++ b/dev-tools/tests/test_account_current_join_required_cases.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Synthetic strict-proof contracts, not physical execution evidence.""" +import importlib.util +import json +import tempfile +import unittest +import xml.etree.ElementTree as ET +from pathlib import Path + +ROOT = Path(__file__).parents[1] +SPEC = importlib.util.spec_from_file_location('proof', ROOT / 'validation/account_donor_required_cases.py') +proof = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(proof) +CURRENT = json.loads((ROOT / 'validation/account_current_join_required_cases.json').read_text())['required_cases'] + + +class CurrentJoinRequiredCasesTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def report(self, name, cases): + suite = ET.Element('testsuite', name=name, tests=str(len(cases)), failures='0', errors='0', skipped='0') + for case in cases: + ET.SubElement(suite, 'testcase', classname=name, name=case) + ET.ElementTree(suite).write(self.root / ('TEST-' + name + '.xml')) + + def test_scope_is_distinct_and_contains_all_55_unique_cases(self): + original = json.loads(proof.CONTRACT.read_text())['required_cases'] + self.assertFalse(original.keys() & CURRENT.keys()) + self.assertEqual(sorted(map(len, CURRENT.values())), [5, 10, 11, 29]) + for cases in CURRENT.values(): + self.assertEqual(len(cases), len(set(cases))) + self.assertEqual(proof.required_cases().keys(), original.keys() | CURRENT.keys()) + + def test_every_named_case_is_required_without_duplicate_substitution(self): + for name, cases in CURRENT.items(): + self.report(name, cases) + self.assertEqual(proof.verify_partition(self.root, {name}), {name}) + for index, case in enumerate(cases): + with self.subTest(suite=name, missing=case): + missing = cases[:index] + cases[index + 1:] + self.report(name, missing) + with self.assertRaisesRegex(ValueError, 'named cases missing'): + proof.verify_partition(self.root, {name}) + self.report(name, missing + [missing[0]]) + with self.assertRaisesRegex(ValueError, 'duplicate'): + proof.verify_partition(self.root, {name}) + (self.root / ('TEST-' + name + '.xml')).unlink() + + def test_old_ambiguous_parameter_labels_cannot_prove_scope(self): + name = next(name for name in CURRENT if 'JoinScopePersistence' in name) + cases = [case for case in CURRENT[name] if ' bound=' not in case] + self.report(name, cases + ['[1] bound = false', '[2] bound = true'] * 2) + with self.assertRaisesRegex(ValueError, 'duplicate'): + proof.verify_partition(self.root, {name}) + + def test_original_contract_alone_cannot_satisfy_complete_union(self): + original = set(json.loads(proof.CONTRACT.read_text())['required_cases']) + with self.assertRaisesRegex(ValueError, 'missing from partition union'): + proof.verify_complete_union([original]) + proof.verify_complete_union([original, set(CURRENT)]) + + +if __name__ == '__main__': + unittest.main() diff --git a/dev-tools/tests/test_account_donor_required_cases.py b/dev-tools/tests/test_account_donor_required_cases.py new file mode 100644 index 0000000000..601a7a1982 --- /dev/null +++ b/dev-tools/tests/test_account_donor_required_cases.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Synthetic negative contracts; these are not physical database evidence.""" +import importlib.util +import tempfile +import unittest +import xml.etree.ElementTree as ET +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location('proof', Path(__file__).parents[1] / 'validation/account_donor_required_cases.py') +proof = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(proof) + + +class AccountRequiredCasesTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.contract = proof.required_cases() + self.name = min(self.contract) + self.path = self.root / 'TEST-obligated.xml' + self.suite = ET.Element('testsuite', name=self.name, tests=str(len(self.contract[self.name])), failures='0', errors='0', skipped='0') + for name in sorted(self.contract[self.name]): + ET.SubElement(self.suite, 'testcase', name=name, classname=self.name) + self.write() + + def write(self): + ET.ElementTree(self.suite).write(self.path) + + def verify(self): + self.write() + return proof.verify_partition(self.root, {self.name}) + + def test_complete_selected_suite(self): + self.assertEqual(self.verify(), {self.name}) + + def test_missing_named_case_even_with_consistent_count(self): + self.suite.remove(self.suite[-1]); self.suite.set('tests', str(len(self.suite))) + with self.assertRaises(ValueError): self.verify() + + def test_skipped_case_with_lying_suite_totals(self): + ET.SubElement(self.suite[0], 'skipped') + with self.assertRaises(ValueError): self.verify() + + def test_error_and_failure_cases_with_lying_totals(self): + for tag in ('failure', 'error'): + with self.subTest(tag=tag): + child = ET.SubElement(self.suite[0], tag) + with self.assertRaises(ValueError): self.verify() + self.suite[0].remove(child) + + def test_namespaced_outcomes_refused_despite_zero_totals(self): + for tag in ('failure', 'error', 'skipped'): + with self.subTest(tag=tag): + child = ET.SubElement(self.suite[0], '{urn:unsupported}' + tag) + with self.assertRaisesRegex(ValueError, 'namespaced'): + self.verify() + self.suite[0].remove(child) + + def test_nested_outcomes_cannot_hide_failure(self): + for tag in ('failure', 'error', 'skipped'): + with self.subTest(tag=tag): + wrapper = ET.SubElement(self.suite[0], 'unsupported-wrapper') + ET.SubElement(wrapper, tag) + with self.assertRaises(ValueError): + self.verify() + self.suite[0].remove(wrapper) + + def test_namespaced_structural_elements_refused(self): + for target in (self.suite, self.suite[0]): + original = target.tag + target.tag = '{urn:unsupported}' + original + with self.assertRaisesRegex(ValueError, 'namespaced'): + self.verify() + target.tag = original + + def test_duplicate_method_cannot_replace_obligation(self): + self.suite[-1].set('name', self.suite[0].get('name')) + with self.assertRaises(ValueError): self.verify() + + def test_wrong_case_class_refused(self): + self.suite[0].set('classname', 'foreign.Class') + with self.assertRaises(ValueError): self.verify() + + def test_duplicate_xml_refused(self): + (self.root / 'TEST-duplicate.xml').write_bytes(self.path.read_bytes()) + with self.assertRaises(ValueError): self.verify() + + def test_missing_suite_refused(self): + self.path.unlink() + with self.assertRaises(ValueError): proof.verify_partition(self.root, {self.name}) + + def test_wrong_partition_refused(self): + with self.assertRaises(ValueError): proof.verify_partition(self.root, set()) + + def test_missing_and_duplicate_union_refused(self): + with self.assertRaises(ValueError): proof.verify_complete_union([{self.name}]) + with self.assertRaises(ValueError): proof.verify_complete_union([set(self.contract), {self.name}]) + proof.verify_complete_union([{name} for name in self.contract]) + + def test_unobligated_empty_partition_allowed(self): + self.path.unlink() + self.assertEqual(proof.verify_partition(self.root, {'another.CurrentTest'}), set()) + + def test_missing_or_nonzero_suite_totals_refused(self): + for attribute in ('failures', 'errors', 'skipped'): + with self.subTest(attribute=attribute): + self.suite.set(attribute, '1') + with self.assertRaises(ValueError): self.verify() + del self.suite.attrib[attribute] + with self.assertRaises(ValueError): self.verify() + self.suite.set(attribute, '0') + + +if __name__ == '__main__': + unittest.main() diff --git a/dev-tools/tests/test_slow_service_ci_partition.py b/dev-tools/tests/test_slow_service_ci_partition.py index 4efae374ee..a64e25f46d 100644 --- a/dev-tools/tests/test_slow_service_ci_partition.py +++ b/dev-tools/tests/test_slow_service_ci_partition.py @@ -5,6 +5,7 @@ import json import tempfile import unittest +import xml.etree.ElementTree as ET from pathlib import Path ROOT = Path(__file__).resolve().parents[2] @@ -53,6 +54,13 @@ def make_plan(module="account-service", run_attempt="2"): plan["tasks"]["test"]["class_universe"].append(name) plan["tasks"]["test"]["expected_test_classes"].append(name) plan["tasks"]["test"]["assignments"][name] = partition + if module == "account-service": + required = sorted(PARTITION.ACCOUNT_PROOF.required_cases()) + plan["tasks"]["integrationTest"] = { + "class_universe": required, + "expected_test_classes": required, + "assignments": {name: index % 4 + 1 for index, name in enumerate(required)}, + } return plan @@ -247,6 +255,20 @@ def write_artifact(root, plan, partition, attempt): f'\n', encoding="utf-8", ) + if plan["module"] == "account-service": + integration = manifest["tasks"]["integrationTest"] + selected = integration["selected_classes"] + if selected: + (destination / "jacoco/integrationTest.exec").write_bytes(b"physical execution data") + required = PARTITION.ACCOUNT_PROOF.required_cases() + for name in selected: + suite = ET.Element("testsuite", name=name, tests=str(len(required[name])), + failures="0", errors="0", skipped="0") + for case in sorted(required[name]): + ET.SubElement(suite, "testcase", classname=name, name=case) + xml = destination / "test-results/integrationTest" / ("TEST-" + name + ".xml") + xml.parent.mkdir(parents=True, exist_ok=True) + ET.ElementTree(suite).write(xml) return destination @@ -620,6 +642,28 @@ def write_reported_groups(reported_groups): ): PARTITION.verify_artifact_reports(artifact_dir, runnable_manifest) + def test_account_required_case_negatives_reach_actual_aggregate(self): + for mutation in ("missing", "skipped", "namespaced_failure", "absent_suite"): + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as temporary: + module = "account-service" + provenance = make_provenance(module) + selection = PARTITION.selection_document(provenance, module, RUN_ID, SOURCE_SHA, "2") + inputs, selection_path, verified, artifacts = prepare_aggregate(Path(temporary), module, selection) + report = next((artifacts[1] / "test-results/integrationTest").glob("TEST-*.xml")) + tree = ET.parse(report); suite = tree.getroot() + if mutation == "missing": + suite.remove(suite[-1]); suite.set("tests", str(len(suite))) + elif mutation == "skipped": + ET.SubElement(suite[0], "skipped") + elif mutation == "namespaced_failure": + ET.SubElement(suite[0], "{urn:unsupported}failure") + else: + report.unlink() + if mutation != "absent_suite": tree.write(report) + with self.assertRaises(ValueError): + PARTITION.verify_aggregate(inputs, selection_path, verified, module, RUN_ID, SOURCE_SHA, "2") + self.assertFalse(verified.exists(), "failed proof must not publish verified class outputs") + def test_partial_retry_uses_latest_outcomes_and_physical_execution_attempts(self): module = "account-service" provenance = make_provenance(module) @@ -668,7 +712,7 @@ def test_partial_retry_uses_latest_outcomes_and_physical_execution_attempts(self SOURCE_SHA, "2", ), - 4, + 8, # Four unit and four obligated physical partition execution files. ) copied = { path.relative_to(verified_classes_dir).as_posix(): path.read_bytes() diff --git a/dev-tools/validation/account_current_join_required_cases.json b/dev-tools/validation/account_current_join_required_cases.json new file mode 100644 index 0000000000..96cd1d5e32 --- /dev/null +++ b/dev-tools/validation/account_current_join_required_cases.json @@ -0,0 +1,69 @@ +{ + "schema_version": 1, + "scope": "Current canonical Account JOIN component proof: storage10, scope11, firstJOIN29, paidJOIN5. Not literal donor2976 worker/expiry/conversion recovery or public runtime activation. Distinct from donor3097 hosted/Draft obligations.", + "required_cases": { + "integration.net.firedevops.firemud.accountservice.repository.AccountFirstJoinAuthorityStorageIntegrationTest": [ + "appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence()", + "callerRollbackRemovesAppendAndConcurrentExactRetriesShareOneSequence()", + "canonicalUpgradeWaitsForLegacyWriterAndPreservesItsUnverifiedIdentity()", + "databaseRejectsDeletingAHeadWithRetainedHistoryWithoutChangingEvidence()", + "databaseRejectsRetainedEventMutationAndStillAllowsExactAppendAndStreamAdvance()", + "databaseRejectsTruncatingOutboxHistoryAndPreservesEventsAndCheckpoint()", + "evidenceFactoryFailureRollsBackStreamCreationAndDoesNotAdvanceHead()", + "exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()", + "missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent()", + "v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSource()" + ], + "integration.net.firedevops.firemud.accountservice.repository.AccountCanonicalJoinScopePersistenceIntegrationTest": [ + "boundPendingUnavailableDiagnosticsNeverDowngradePolicyAndExactRecoveryOnlyClearsDiagnostics()", + "definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite[1] bound=false", + "definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite[2] bound=true", + "definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy()", + "expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch()", + "failedJournalRejectsConflictingCallerRequestAndRetainedScopeWithoutRewritingReceipt()", + "firstInvoiceAndCapacityUpgradeFromParent1036Through1041PreservesCanonicalRowsAndHistory()", + "journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction[1] bound=false", + "journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction[2] bound=true", + "migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrEvent()", + "sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerminalMutation()" + ], + "integration.net.firedevops.firemud.accountservice.service.AccountPaidCanonicalFirstJoinPostgresIntegrationTest": [ + "changedOperationPolicyCannotCommitAgainstAnOlderPaidReceipt()", + "expiredPaidReceiptIsUnavailableAndNeverSelectsDemo()", + "finalCommitFailureRollsBackMembershipRolesPairEventAuditAndTerminalReceipt()", + "paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo()", + "providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanRecover()" + ], + "integration.net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinEventIntegrationTest": [ + "[1] alreadyActive = false", + "[1] terminalState = \"COMMITTED\"", + "[2] alreadyActive = true", + "[2] terminalState = \"FAILED_UNBOUND\"", + "[3] terminalState = \"FAILED_BOUND\"", + "activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays()", + "activeNonAdmittingSnapshotWithoutPlayerRoleRemainsSuccessfulAndUnchanged()", + "browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommittedReceipt()", + "browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive()", + "canonicalLeaveAndIndependentSecurityChangeAdvanceOneCompositeFenceInBothOrders()", + "canonicalLeaveAndSecurityWriterSerializeAtTheAccountLockInBothOrders()", + "canonicalLeaveCommitsMembershipFenceWithoutAnySecurityMutationAndReplaysHistoricalReceipt()", + "canonicalLeaveCutoverPreservesExactLegacySecuritySourceAndEventBytes()", + "canonicalLeaveInvalidatesCapturedSourceWithoutChangingSecurityGeneration()", + "canonicalLeaveOfAbsentMembershipReturnsNoOpWithoutInitializingAuthority()", + "canonicalLeaveRejectsUnbackedFenceAdvanceAndWrongCausalEventWithFullRollback()", + "canonicalLeaveTerminalFailureRollsBackMembershipFenceRolesEventAuditAndIntent()", + "changedEntitlementPreventsAStalePendingJoinFromCommittingMembership()", + "closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot()", + "commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation()", + "concurrentExactTerminalAttemptsShareOneMembershipEventAuditAndReceipt()", + "directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwners()", + "inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration()", + "nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard()", + "pairCasFailureRollsBackMembershipAndTheActualOutboxAppend()", + "pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin()", + "restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit()", + "terminalCoordinatorCommitsAuditAndOperationWithTheFirstEventAndReplaysExactly()", + "terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether()" + ] + } +} diff --git a/dev-tools/validation/account_donor_required_cases.json b/dev-tools/validation/account_donor_required_cases.json new file mode 100644 index 0000000000..87965a532b --- /dev/null +++ b/dev-tools/validation/account_donor_required_cases.json @@ -0,0 +1,46 @@ +{ + "schema_version": 1, + "scope": "Donor 3097 current hosted terms and Draft owner-local physical proof only; not missing producer families or activation.", + "required_cases": { + "integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest": [ + "bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation()", + "boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline()", + "realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions()" + ], + "integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest": [ + "acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity()", + "futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly()", + "migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance()", + "ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent()", + "realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality()" + ], + "integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest": [ + "bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks()", + "changedCompleteBindingsConflictWithoutRewritingOriginal()", + "commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening()", + "concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering()", + "concurrentConflictingOwnerEvidenceRejectsRetryAndPreservesWinningBytes()", + "concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources()", + "concurrentExactConsumerRetriesReturnTheSameOriginalSettlement()", + "discoveryPagesOriginalPendingOperationsAndExcludesEverySettledVector()", + "distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource()", + "forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly()", + "inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage()", + "mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence()", + "originalBindingSurvivesRestartAndAbsenceRemainsUnknownUnderOwnerTransaction()", + "originalRecoveryRejectsMalformedBytesAndEveryConflictingIdentityColumn()", + "ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn()", + "rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation()", + "revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts()", + "revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation()", + "rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict()", + "twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry()", + "v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering()", + "v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback()", + "v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes()", + "v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners()", + "v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults()", + "worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks()" + ] + } +} diff --git a/dev-tools/validation/account_donor_required_cases.py b/dev-tools/validation/account_donor_required_cases.py new file mode 100644 index 0000000000..67272d0c66 --- /dev/null +++ b/dev-tools/validation/account_donor_required_cases.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Exact-case check after canonical partition provenance validation. + +This helper does not establish freshness, execution, artifact provenance, or +whole-donor consumption. The canonical caller must establish those separately. +No scheduling, selectors, or current required-CI decisions are changed here. +""" +from __future__ import annotations + +import json +import xml.etree.ElementTree as ET +from pathlib import Path + +CONTRACT = Path(__file__).with_suffix('.json') + + +def required_cases() -> dict[str, set[str]]: + required = {} + for contract in (CONTRACT, Path(__file__).with_name('account_current_join_required_cases.json')): + data = json.loads(contract.read_text()) + if data.get('schema_version') != 1: + raise ValueError('unsupported Account proof contract') + for name, cases in data['required_cases'].items(): + if name in required: + raise ValueError('Account proof contracts overlap') + required[name] = set(cases) + return required + + +def verify_partition(reports: Path, selected_classes: set[str]) -> set[str]: + """Require each selected obligated class's named cases exactly once and green. + + The caller must supply the already-verified integrationTest selector, not a + caller-invented partial universe. The aggregate must additionally require + every contract class to occur in the complete partition union. + """ + required = required_cases() + selected = selected_classes & required.keys() + seen: dict[str, set[str]] = {name: set() for name in selected} + suites_seen: set[str] = set() + for path in sorted(reports.glob('TEST-*.xml')): + root = ET.parse(path).getroot() + # Gradle emits namespace-free JUnit. Unsupported structures cannot + # establish a successful required outcome, even with zero totals. + if any(not isinstance(node.tag, str) or '{' in node.tag or ':' in node.tag + for node in root.iter()): + raise ValueError('unsupported namespaced JUnit structure') + name = root.get('name', '') + if name not in required: + continue + if name not in selected: + raise ValueError('required Account suite reported in wrong partition') + if root.tag != 'testsuite' or name in suites_seen: + raise ValueError('duplicate or invalid required Account suite') + suites_seen.add(name) + for attribute in ('failures', 'errors', 'skipped'): + if attribute not in root.attrib or int(root.attrib[attribute]) != 0: + raise ValueError('required Account suite is not wholly successful') + cases = root.findall('testcase') + if int(root.attrib.get('tests', '-1')) != len(cases): + raise ValueError('required Account suite count disagrees with cases') + for case in cases: + case_name = case.get('name', '') + if case.get('classname') != name or not case_name or case_name in seen[name]: + raise ValueError('duplicate or mismatched Account case identity') + if any(node.tag in ('skipped', 'failure', 'error') for node in case.iter()): + raise ValueError('required Account case did not pass') + seen[name].add(case_name) + if not required[name] <= seen[name]: + raise ValueError('required Account named cases missing') + if suites_seen != selected: + raise ValueError('required Account suite missing') + return suites_seen + + +def verify_complete_union(verified_partitions: list[set[str]]) -> None: + seen: set[str] = set() + for partition in verified_partitions: + if seen & partition: + raise ValueError('required Account suite appears in multiple partitions') + seen |= partition + if seen != required_cases().keys(): + raise ValueError('required Account proof missing from partition union') diff --git a/dev-tools/validation/slow_service_ci_test_partition.py b/dev-tools/validation/slow_service_ci_test_partition.py index 504a272f32..78b17ec6ab 100644 --- a/dev-tools/validation/slow_service_ci_test_partition.py +++ b/dev-tools/validation/slow_service_ci_test_partition.py @@ -5,6 +5,7 @@ import argparse import copy +import importlib.util import json import re import shutil @@ -15,6 +16,12 @@ from pathlib import Path from typing import Any +_ACCOUNT_SPEC = importlib.util.spec_from_file_location( + "account_donor_required_cases", Path(__file__).with_name("account_donor_required_cases.py") +) +ACCOUNT_PROOF = importlib.util.module_from_spec(_ACCOUNT_SPEC) +_ACCOUNT_SPEC.loader.exec_module(ACCOUNT_PROOF) + PLAN_PATH = Path(__file__).with_name("slow_service_ci_test_partition_plan.json") SERVICES = ("account-service", "game-session-service", "world-management-service") PARTITION_COUNTS = {"account-service": 4, "game-session-service": 4, "world-management-service": 2} @@ -844,6 +851,16 @@ def verify_aggregate( execution_data.extend(verify_artifact_reports(artifact_dir, manifests[partition])) if not execution_data: raise ValueError("aggregate has no JaCoCo execution data from any partition") + if module == "account-service": + verified_account_suites = [] + for partition in partitions_for(module): + integration = manifests[partition]["tasks"].get("integrationTest", {}) + verified_account_suites.append(ACCOUNT_PROOF.verify_partition( + artifact_directories[partition] / "test-results" / "integrationTest", + set(integration.get("selected_classes", [])), + )) + ACCOUNT_PROOF.verify_complete_union(verified_account_suites) + copy_verified_main_classes( artifact_directories[1] / "classes" / "java" / "main", measured_classes, diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index 8dbcb379de..b779bdfd0a 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -2325,6 +2325,16 @@ def test_join_pre_membership_contract_is_explicit(self): "caller_bound_after_validation", route["membership_creation"] ) + def test_account_join_routes_declare_invalid_scope_denial(self): + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) + for route_name in ( + "POST /auth/bootstrap/join", + "JoinPublicProductionMembership", + ): + with self.subTest(route_name=route_name): + route = route_for(document, "account-service", route_name) + self.assertIn("CONNECT_SCOPE_INVALID", route["canonical_errors"]["any_of"]) + def test_membership_writer_requires_current_account_state_and_pending_deletion_gate(self): baseline = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) self.assertNotIn( diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 873cbac3d9..f19e16dc6e 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -2090,57 +2090,70 @@ def test_identity_labels_survive_sanitize_injection_and_runtime_target(self): def test_mode_specific_policy_sets_and_rules_are_closed(self): hosted = self._policy_documents("hosted-controller") standalone = self._policy_documents("standalone") - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies( - standalone - + [ - self._policy_document( - "account-service-controller-ingress", {} - ) - ], - "standalone", - ) - missing_account = [ - document - for document in hosted - if document["metadata"]["name"] != "account-service-controller-ingress" - ] - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies(missing_account, "hosted-controller") - - missing_game_session = [ - document - for document in hosted - if document["metadata"]["name"] - != "game-session-service-controller-ingress" - ] - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies( - missing_game_session, "hosted-controller" - ) - - for field, value, message in ( - ( - "podSelector", - {"matchLabels": {"app": "account-service"}}, - "selects an unsafe workload", - ), - ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), - ("ingress", [], "has an unsafe exception"), + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", ): - with self.subTest(mode="hosted-controller", game_session_field=field): - malformed = copy.deepcopy(hosted) - policy = next( - document - for document in malformed - if document["metadata"]["name"] - == "game-session-service-controller-ingress" + with self.subTest(mode="standalone", workload=workload), self.assertRaisesRegex( + ValueError, "runtime NetworkPolicy set is not closed" + ): + self.validator.validate_network_policies( + standalone + + [ + self._policy_document( + f"{workload}-controller-ingress", {} + ) + ], + "standalone", ) - policy["spec"][field] = value - with self.assertRaisesRegex(ValueError, message): - self.validator.validate_network_policies( - malformed, "hosted-controller" + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + missing_policy = [ + document + for document in hosted + if document["metadata"]["name"] + != f"{workload}-controller-ingress" + ] + with self.subTest(mode="hosted-controller", missing=workload), self.assertRaisesRegex( + ValueError, "runtime NetworkPolicy set is not closed" + ): + self.validator.validate_network_policies( + missing_policy, "hosted-controller" + ) + + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + for field, value, message in ( + ( + "podSelector", + {"matchLabels": {"app": f"{workload}-other"}}, + "selects an unsafe workload", + ), + ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), + ("ingress", [], "has an unsafe exception"), + ): + with self.subTest( + mode="hosted-controller", workload=workload, field=field + ): + malformed = copy.deepcopy(hosted) + policy = next( + document + for document in malformed + if document["metadata"]["name"] + == f"{workload}-controller-ingress" ) + policy["spec"][field] = value + with self.assertRaisesRegex(ValueError, message): + self.validator.validate_network_policies( + malformed, "hosted-controller" + ) for mode in ("standalone", "hosted-controller"): with self.subTest(mode=mode, case="missing gateway egress"): @@ -2730,6 +2743,370 @@ def test_gateway_rejects_extra_env_from_reference(self): self.validator.validate_service_consumers([document], "pr-42") +class PreviewArtifactFrontendValidationTest(unittest.TestCase): + validator = VALIDATOR + + def _frontend_deployment(self): + return { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": {"name": "frontend"}, + "spec": { + "replicas": 1, + "selector": {"matchLabels": {"app": "frontend"}}, + "template": { + "metadata": {"labels": {"app": "frontend"}}, + "spec": { + "automountServiceAccountToken": False, + "securityContext": { + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "fsGroup": 101, + "fsGroupChangePolicy": "OnRootMismatch", + "seccompProfile": {"type": "RuntimeDefault"}, + }, + "imagePullSecrets": [{"name": "ghcr-preview-pull"}], + "containers": [ + { + "name": "frontend", + "image": "ghcr.io/benhook1013/web-client:pr-42-head-42", + "imagePullPolicy": "Always", + "securityContext": { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "capabilities": {"drop": ["ALL"]}, + }, + "ports": [ + { + "name": "http", + "containerPort": 8080, + "protocol": "TCP", + } + ], + "readinessProbe": { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 2, + "periodSeconds": 10, + }, + "livenessProbe": { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 5, + "periodSeconds": 20, + }, + "resources": copy.deepcopy( + self.validator.FRONTEND_RESOURCES + ), + "volumeMounts": [ + {"name": "nginx-tmp", "mountPath": "/tmp"} + ], + } + ], + "volumes": [ + { + "name": "nginx-tmp", + "emptyDir": {"sizeLimit": "16Mi"}, + } + ], + }, + }, + }, + } + + def _frontend_service(self): + return { + "apiVersion": "v1", + "kind": "Service", + "metadata": {"name": "frontend"}, + "spec": copy.deepcopy(self.validator.FRONTEND_SERVICE_SPEC), + } + + def _frontend_policy(self): + return { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": {"name": "frontend-static-host"}, + "spec": copy.deepcopy(self.validator.FRONTEND_NETWORK_POLICY_SPEC), + } + + def _frontend_middleware(self): + return { + "apiVersion": "traefik.io/v1alpha1", + "kind": "Middleware", + "metadata": {"name": "firemud-preview-auth-path-rewrite"}, + "spec": copy.deepcopy(self.validator.FRONTEND_MIDDLEWARE_SPEC), + } + + def _frontend_ingress(self): + return { + "apiVersion": "networking.k8s.io/v1", + "kind": "Ingress", + "metadata": { + "name": "firemud-preview", + "annotations": { + self.validator.FRONTEND_MIDDLEWARE_ANNOTATION: ( + "pr-42-firemud-preview-auth-path-rewrite@kubernetescrd" + ) + }, + }, + "spec": { + "ingressClassName": "traefik", + "tls": [ + { + "hosts": ["pr-42.preview.example.test"], + "secretName": "pr-42-tls", + } + ], + "rules": [ + { + "host": "pr-42.preview.example.test", + "http": {"paths": self.validator._frontend_ingress_paths()}, + } + ], + }, + } + + def test_opt_in_frontend_contract_is_exact_and_default_is_closed(self): + self.validator.validate_frontend_deployment( + self._frontend_deployment(), "pr-42-head-42" + ) + self.validator.validate_services( + [self._frontend_service()], "hosted-controller", True + ) + self.validator.validate_frontend_middleware( + self._frontend_middleware(), "pr-42" + ) + self.validator.validate_ingress( + self._frontend_ingress(), "pr-42", "pr-42.preview.example.test", True + ) + enabled = self.validator._expected_names_for_mode("hosted-controller", True) + disabled = self.validator._expected_names_for_mode("hosted-controller", False) + for kind, names in self.validator.FRONTEND_EXPECTED_NAMES.items(): + self.assertTrue(names <= enabled[kind]) + self.assertTrue(names.isdisjoint(disabled.get(kind, set()))) + + def test_sanitize_accepts_named_opt_in_objects_and_preserves_middleware(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_middleware(), + self._frontend_ingress(), + ] + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "render.yaml" + destination = Path(directory) / "sanitized.yaml" + source.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + self.validator.sanitize(source, destination) + sanitized = list(yaml.safe_load_all(destination.read_text(encoding="utf-8"))) + ingress = next(document for document in sanitized if document["kind"] == "Ingress") + self.assertEqual( + ingress["metadata"]["annotations"], + { + self.validator.FRONTEND_MIDDLEWARE_ANNOTATION: ( + "pr-42-firemud-preview-auth-path-rewrite@kubernetescrd" + ) + }, + ) + self.assertEqual( + {(document["kind"], document["metadata"]["name"]) for document in sanitized}, + { + ("Deployment", "frontend"), + ("Service", "frontend"), + ("NetworkPolicy", "frontend-static-host"), + ("Middleware", "firemud-preview-auth-path-rewrite"), + ("Ingress", "firemud-preview"), + }, + ) + + def test_validate_manifest_accepts_complete_opt_in_closed_set(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_middleware(), + self._frontend_ingress(), + ] + labels = self.validator._expected_object_labels("pr-42") + for document in documents: + document["metadata"]["labels"] = copy.deepcopy(labels) + expected_names = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, + "Ingress": {"firemud-preview"}, + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "manifest.yaml" + path.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + with ( + patch.object(self.validator, "EXPECTED_NAMES", expected_names), + patch.object(self.validator, "validate_services"), + patch.object(self.validator, "validate_network_policies"), + patch.object(self.validator, "validate_infrastructure_deployments"), + patch.object(self.validator, "validate_service_consumers"), + ): + self.validator.validate_manifest( + path, + "pr-42", + "pr-42-head-42", + "pr-42.preview.example.test", + ) + + def test_validate_manifest_rejects_missing_opt_in_object(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_ingress(), + ] + labels = self.validator._expected_object_labels("pr-42") + for document in documents: + document["metadata"]["labels"] = copy.deepcopy(labels) + expected_names = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, + "Ingress": {"firemud-preview"}, + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "manifest.yaml" + path.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + with ( + patch.object(self.validator, "EXPECTED_NAMES", expected_names), + self.assertRaisesRegex(ValueError, "object set is not closed"), + ): + self.validator.validate_manifest( + path, + "pr-42", + "pr-42-head-42", + "pr-42.preview.example.test", + ) + def test_frontend_deployment_rejects_mutated_security_or_image(self): + cases = ( + ( + "root filesystem", + lambda document: document["spec"]["template"]["spec"]["containers"][0][ + "securityContext" + ].__setitem__("readOnlyRootFilesystem", False), + ), + ( + "image repository", + lambda document: document["spec"]["template"]["spec"]["containers"][0].__setitem__( + "image", "ghcr.io/attacker/web-client:pr-42-head-42" + ), + ), + ( + "image digest", + lambda document: document["spec"]["template"]["spec"]["containers"][0].__setitem__( + "image", "ghcr.io/benhook1013/web-client@sha256:abc" + ), + ), + ) + for case, mutate in cases: + with self.subTest(case=case): + document = self._frontend_deployment() + mutate(document) + with self.assertRaises(ValueError): + self.validator.validate_frontend_deployment( + document, "pr-42-head-42" + ) + + def test_frontend_service_policy_and_middleware_reject_shape_changes(self): + service = self._frontend_service() + service["spec"]["ports"][0]["targetPort"] = 8081 + with self.assertRaisesRegex(ValueError, "unsafe frontend spec"): + self.validator.validate_services([service], "hosted-controller", True) + + policy = self._frontend_policy() + policy["spec"]["egress"] = [ + {"to": [{"ipBlock": {"cidr": "0.0.0.0/0"}}]} + ] + with self.assertRaisesRegex(ValueError, "frontend-static-host has an unsafe spec"): + self.validator.validate_frontend_network_policy(policy) + + middleware = self._frontend_middleware() + middleware["spec"]["replacePathRegex"]["replacement"] = "/api/account/login$1" + with self.assertRaisesRegex(ValueError, "unsafe spec"): + self.validator.validate_frontend_middleware(middleware, "pr-42") + + def test_frontend_ingress_rejects_missing_extra_and_misrouted_paths(self): + cases = ( + ( + "missing route", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].pop(), + ), + ( + "misrouted auth", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"][1][ + "backend" + ]["service"].__setitem__("name", "frontend"), + ), + ( + "extra route", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].append( + { + "path": "/admin", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + } + ), + ), + ( + "published assets routed through gateway", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].insert( + -1, + { + "path": "/assets", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + }, + ), + ), + ) + for case, mutate in cases: + with self.subTest(case=case): + ingress = self._frontend_ingress() + mutate(ingress) + with self.assertRaisesRegex(ValueError, "route"): + self.validator.validate_ingress( + ingress, "pr-42", "pr-42.preview.example.test", True + ) + + def test_frontend_policy_closed_set_rejects_missing_and_extra_objects(self): + expected = self.validator._expected_names_for_mode( + "hosted-controller", True + )["NetworkPolicy"] + for case, names in ( + ("missing", expected - {"frontend-static-host"}), + ("extra", expected | {"frontend-extra"}), + ): + with self.subTest(case=case): + documents = [ + {"kind": "NetworkPolicy", "metadata": {"name": name}} + for name in names + ] + with self.assertRaisesRegex(ValueError, "set is not closed"): + self.validator.validate_network_policies( + documents, "hosted-controller", True + ) + + class PreviewArtifactNetworkPolicyTest(unittest.TestCase): validator = VALIDATOR diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 8f737ad1eb..9ef5e92606 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -50,13 +50,14 @@ esac FIREMUD_SMOKE_ADMISSION_QUALIFICATION="${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" case "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" in baseline|held) - export FIREMUD_SMOKE_ADMISSION_QUALIFICATION ;; *) echo "FIREMUD_SMOKE_ADMISSION_QUALIFICATION must be baseline or held; refusing to run." >&2 exit 1 ;; esac +apply_pre_v1_waived_admission_qualification +export FIREMUD_SMOKE_ADMISSION_QUALIFICATION initialize_run_owned_compose_proof "$@" install_run_owned_compose_proof_traps diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index 71d985819b..3e5c9f7aa3 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -89,13 +89,14 @@ case "$SMOKE_MINIO_LOCAL_ONLY" in FIREMUD_SMOKE_ADMISSION_QUALIFICATION="${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" case "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" in baseline|held) - export FIREMUD_SMOKE_ADMISSION_QUALIFICATION ;; *) echo "FIREMUD_SMOKE_ADMISSION_QUALIFICATION must be baseline or held; refusing to run." >&2 exit 1 ;; esac +apply_pre_v1_waived_admission_qualification +export FIREMUD_SMOKE_ADMISSION_QUALIFICATION # The proof's mTLS profile must be last so it supersedes the ordinary local # plaintext override and all image/MinIO-specific overlays. diff --git a/k8s/account-jwt-materializer/README.md b/k8s/account-jwt-materializer/README.md new file mode 100644 index 0000000000..62ea5cf072 --- /dev/null +++ b/k8s/account-jwt-materializer/README.md @@ -0,0 +1,11 @@ +# Account JWT materializer source intake + +This module retains the bounded one-shot Account signer custodian from the original donor handoff. Account remains the lifecycle and promotion authority under [ADR 0014](../../design/architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md). The materializer accepts only protected binding and credential files, verifies Account and Kubernetes identities, and correlates each Secret observation with the exact Account operation before any key-generation or Secret-write step. It is not registered as a runtime service or deployed by this source intake. + +Focused local proof covers 23 boundary and 15 flow tests, including four observation-response substitutions in both entry modes that deny before any Secret PATCH or generation/promotion result. Enabled main/test Checkstyle and SpotBugs and formatting checks pass. These controlled tests do not prove deployed credentials, real Account/Kubernetes transport, signer rotation, readiness convergence, or production custody. + +The Account integration suite also composes the unchanged production materializer with the real Account materialization service and native PostgreSQL in `AccountPublicJwksWriterWindowPostgresIntegrationTest`. Its controlled Secret adapter simulates a lost patch acknowledgment; recreated materializer/client instances recover the original generation, remain blocked until owner readiness, and replay the private-promotion receipt after mount delivery without another Secret patch. The authenticated interceptor uses a controlled TLS peer, and Kubernetes, mount delivery, and readiness receivers remain test boundaries. This is component composition proof, not real network authentication, a deployed bootstrap fixture, or full signer activation. + +The optional readiness harness is excluded because its original `IssueReadinessProbes` protobuf is absent from the current Account API. The later bootstrap fixture is also excluded: its referenced `account-jwt-bootstrap-account.py` and `account-jwt-bootstrap-redis.py` helpers were not included in the donor snapshot or recovered history. This module does not substitute for those missing dependencies or complete the full bootstrap handoff. No Docker image, RBAC, workload, timer, credential, or activation asset is included. + +Validate the source with `bash dev-tools/validation/run-locked-gradle.sh :account-jwt-materializer:test :account-jwt-materializer:check -PfullCheck`. Running the packaged custodian against an environment remains a separate authorized deployment and custody qualification step. diff --git a/k8s/account-jwt-materializer/build.gradle.kts b/k8s/account-jwt-materializer/build.gradle.kts new file mode 100644 index 0000000000..3fb05ae339 --- /dev/null +++ b/k8s/account-jwt-materializer/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + application +} + +dependencies { + implementation(project(":common-platform-core")) + implementation(libs.protobuf.java) + implementation(libs.grpc.netty.shaded) + implementation(libs.grpc.protobuf) + implementation(libs.grpc.stub) + implementation("tools.jackson.core:jackson-databind") + + testImplementation(libs.spring.boot.starter.test) +} + +application { + mainClass.set("net.firedevops.firemud.accountjwtmaterializer.MaterializerMain") +} + +tasks.jar { + archiveFileName.set("account-jwt-materializer.jar") +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/AccountClient.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/AccountClient.java new file mode 100644 index 0000000000..e77b922ca8 --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/AccountClient.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import io.grpc.ManagedChannel; +import io.grpc.ProxyDetector; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import java.io.ByteArrayInputStream; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; + +/** Pinned mTLS client for only the Account signer materialization RPCs. */ +final class AccountClient implements AutoCloseable, Materializer.AccountOperations { + private static final long RPC_DEADLINE_SECONDS = 5; + private final ProtectedBinding.Snapshot snapshot; + private final java.nio.file.Path bindingPath; + private final ManagedChannel channel; + + AccountClient(ProtectedBinding.Snapshot snapshot, java.nio.file.Path bindingPath) { + this.snapshot = snapshot; + this.bindingPath = bindingPath; + ManagedChannel created = null; + try { + snapshot.requireUnchanged(bindingPath); + ProtectedBinding.Binding binding = snapshot.binding(); + String[] target = binding.accountTarget().split(":", -1); + if (target.length != 2 || !target[0].equals(binding.accountServerDnsName())) { + throw denied(); + } + int port = Integer.parseInt(target[1]); + var sslContext = + GrpcSslContexts.forClient() + .trustManager(serverTrustManager(binding)) + .keyManager( + binding.clientCertificatePath().toFile(), binding.clientPrivateKeyPath().toFile()) + .build(); + created = + NettyChannelBuilder.forAddress(target[0], port) + .overrideAuthority(binding.accountServerDnsName()) + .proxyDetector((ProxyDetector) address -> null) + .sslContext(sslContext) + .build(); + snapshot.requireUnchanged(bindingPath); + this.channel = created; + } catch (Exception ex) { + if (created != null) { + created.shutdownNow(); + } + throw denied(); + } + } + + @Override + public EnrollBootstrapResponse enrollBootstrap() { + return invoke( + () -> + stub() + .enrollBootstrap(EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build())); + } + + @Override + public GetCurrentGenerationRequestResponse getCurrentGenerationRequest() { + return invoke( + () -> + stub() + .getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build())); + } + + @Override + public GetCurrentGenerationRequestResponse recordSecretObservation( + String operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + return invoke( + () -> + stub() + .recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(operationId) + .setOperationDigest(operationDigest) + .setSecretUid(secretUid) + .setObservedResourceVersion(observedResourceVersion) + .build())); + } + + @Override + public RecordGenerationResultResponse recordGenerationResult( + String operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + return invoke( + () -> + stub() + .recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(operationId) + .setGenerationRequestDigest(generationRequestDigest) + .setSecretUid(secretUid) + .setExpectedPriorResourceVersion(expectedPriorResourceVersion) + .setObservedResourceVersion(observedResourceVersion) + .setPublicJwkJson(publicJwkJson) + .build())); + } + + @Override + public GetCurrentPromotionRequestResponse getCurrentPromotionRequest() { + return invoke( + () -> + stub() + .getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build())); + } + + @Override + public RecordPrivatePromotionResultResponse recordPrivatePromotionResult( + GetCurrentPromotionRequestResponse request, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + SignerKeyBundle.PublicIdentity current, + SignerKeyBundle.PublicIdentity previous, + List resultingSlots) { + RecordPrivatePromotionResultRequest.Builder builder = + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(request.getPromotionOperationId()) + .setPromotionRequestDigest(request.getPromotionRequestDigest()) + .setGenerationOperationId(request.getGenerationOperationId()) + .setGenerationOperationDigest(request.getGenerationOperationDigest()) + .setSecretUid(secretUid) + .setExpectedPriorResourceVersion(expectedPriorResourceVersion) + .setObservedResourceVersion(observedResourceVersion) + .setCurrent(toWire(current)); + if (previous != null) { + builder.setPrevious(toWire(previous)); + } + builder.addAllResultingSlots(resultingSlots); + return invoke(() -> stub().recordPrivatePromotionResult(builder.build())); + } + + private static PromotionPublicKeyIdentity toWire(SignerKeyBundle.PublicIdentity identity) { + return PromotionPublicKeyIdentity.newBuilder() + .setGeneration(identity.generation()) + .setKid(identity.kid()) + .setPublicKeyFingerprint(identity.fingerprint()) + .build(); + } + + private AccountJwtSignerMaterializationServiceGrpc + .AccountJwtSignerMaterializationServiceBlockingStub + stub() { + return AccountJwtSignerMaterializationServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS); + } + + private T invoke(RpcCall call) { + requireSnapshot(); + T result; + try { + result = call.run(); + } catch (RuntimeException ex) { + requireSnapshot(); + throw ex; + } + requireSnapshot(); + return result; + } + + private void requireSnapshot() { + try { + snapshot.requireUnchanged(bindingPath); + } catch (Exception ex) { + throw denied(); + } + } + + private static X509TrustManager serverTrustManager(ProtectedBinding.Binding binding) + throws Exception { + byte[] caBytes = ProtectedBinding.readCredential(binding.accountCaPath()); + try { + var certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(caBytes)); + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null); + int index = 0; + for (var certificate : certificates) { + trustStore.setCertificateEntry("account-ca-" + index++, certificate); + } + TrustManagerFactory factory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(trustStore); + X509TrustManager delegate = + java.util.Arrays.stream(factory.getTrustManagers()) + .filter(X509TrustManager.class::isInstance) + .map(X509TrustManager.class::cast) + .findFirst() + .orElseThrow(AccountClient::denied); + return new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws java.security.cert.CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws java.security.cert.CertificateException { + delegate.checkServerTrusted(chain, authType); + verifyServerIdentity(chain, binding); + } + }; + } finally { + java.util.Arrays.fill(caBytes, (byte) 0); + } + } + + private static void verifyServerIdentity( + X509Certificate[] chain, ProtectedBinding.Binding binding) + throws java.security.cert.CertificateException { + try { + if (chain == null || chain.length == 0) { + throw denied(); + } + X509Certificate leaf = chain[0]; + String spki = + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(leaf.getPublicKey().getEncoded())); + List uris = new java.util.ArrayList<>(); + var names = leaf.getSubjectAlternativeNames(); + if (names != null) { + for (List name : names) { + if (name.size() >= 2 + && Integer.valueOf(6).equals(name.get(0)) + && name.get(1) instanceof String uri) { + uris.add(uri); + } + } + } + if (!binding.accountServerSpkiSha256Pins().contains(spki) + || !uris.equals(List.of(binding.expectedAccountSpiffeUri()))) { + throw denied(); + } + } catch (java.security.GeneralSecurityException | RuntimeException ex) { + throw new java.security.cert.CertificateException("Account peer identity is not pinned"); + } + } + + @Override + public void close() { + channel.shutdownNow(); + try { + channel.awaitTermination(2, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Account materialization peer is unavailable or untrusted"); + } + + @FunctionalInterface + private interface RpcCall { + T run(); + } +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/KubernetesApi.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/KubernetesApi.java new file mode 100644 index 0000000000..6f7344dc95 --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/KubernetesApi.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import java.io.ByteArrayInputStream; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Flow; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Direct, bounded HTTPS client for the pre-created Secret and pinned incarnation reads only. */ +final class KubernetesApi implements Materializer.KubernetesOperations { + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(5); + private static final int MAX_IDENTITY_BYTES = 32 * 1024; + private static final int MAX_SECRET_BYTES = SecretState.MAX_SECRET_JSON_BYTES; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final ProtectedBinding.Snapshot snapshot; + private final java.nio.file.Path bindingPath; + private final URI apiBase; + private final HttpClient client; + + KubernetesApi(ProtectedBinding.Snapshot snapshot, java.nio.file.Path bindingPath) { + this.snapshot = snapshot; + this.bindingPath = bindingPath; + this.apiBase = snapshot.binding().kubernetesApiServerUri(); + try { + snapshot.requireUnchanged(bindingPath); + SSLParameters tlsParameters = new SSLParameters(); + tlsParameters.setEndpointIdentificationAlgorithm("HTTPS"); + this.client = + HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .proxy(new NoProxySelector()) + .sslContext(apiSslContext(snapshot.binding())) + .sslParameters(tlsParameters) + .version(HttpClient.Version.HTTP_1_1) + .build(); + } catch (Exception ex) { + throw denied(); + } + } + + @Override + public void verifyClusterIdentity() { + ProtectedBinding.Binding binding = snapshot.binding(); + JsonNode ownNamespace = + getJson("/api/v1/namespaces/" + binding.namespace(), MAX_IDENTITY_BYTES); + JsonNode systemNamespace = getJson("/api/v1/namespaces/kube-system", MAX_IDENTITY_BYTES); + JsonNode serviceAccount = + getJson( + "/api/v1/namespaces/" + + binding.namespace() + + "/serviceaccounts/" + + binding.expectedServiceAccountName(), + MAX_IDENTITY_BYTES); + if (!"v1".equals(text(ownNamespace, "apiVersion")) + || !"Namespace".equals(text(ownNamespace, "kind")) + || !binding.namespace().equals(metadataName(ownNamespace)) + || !"v1".equals(text(systemNamespace, "apiVersion")) + || !"Namespace".equals(text(systemNamespace, "kind")) + || !"kube-system".equals(metadataName(systemNamespace)) + || !"v1".equals(text(serviceAccount, "apiVersion")) + || !"ServiceAccount".equals(text(serviceAccount, "kind")) + || !binding.namespace().equals(metadataNamespace(serviceAccount)) + || !binding.expectedServiceAccountName().equals(metadataName(serviceAccount)) + || !binding.expectedNamespaceUid().equals(metadataUid(ownNamespace)) + || !binding.expectedKubeSystemNamespaceUid().equals(metadataUid(systemNamespace)) + || !binding.expectedClusterIncarnationUid().equals(metadataUid(systemNamespace)) + || !binding.expectedServiceAccountUid().equals(metadataUid(serviceAccount))) { + throw denied(); + } + } + + @Override + public SecretState getFixedSecret() { + byte[] response = + getBytes( + "/api/v1/namespaces/" + snapshot.binding().namespace() + "/secrets/" + SecretState.NAME, + MAX_SECRET_BYTES); + try { + return SecretState.parse(response, snapshot.binding().namespace()); + } finally { + java.util.Arrays.fill(response, (byte) 0); + } + } + + @Override + public void patchFixedSecret(SecretState before, byte[] mergePatch) { + try { + if (!before.uid().matches("[0-9a-fA-F-]{36}") + || mergePatch == null + || mergePatch.length == 0 + || mergePatch.length > MAX_SECRET_BYTES) { + throw denied(); + } + String path = + "/api/v1/namespaces/" + snapshot.binding().namespace() + "/secrets/" + SecretState.NAME; + byte[] response = + send("PATCH", path, mergePatch, "application/merge-patch+json", MAX_SECRET_BYTES); + java.util.Arrays.fill(response, (byte) 0); + } finally { + if (mergePatch != null) java.util.Arrays.fill(mergePatch, (byte) 0); + } + } + + private JsonNode getJson(String path, int maxBytes) { + byte[] response = getBytes(path, maxBytes); + try { + return JSON.readTree(response); + } catch (Exception ex) { + throw denied(); + } finally { + java.util.Arrays.fill(response, (byte) 0); + } + } + + private byte[] getBytes(String path, int maxBytes) { + return send("GET", path, null, null, maxBytes); + } + + private byte[] send( + String method, String path, byte[] requestBody, String contentType, int maxResponseBytes) { + requireSnapshot(); + String token = readBearerToken(); + try { + HttpRequest.Builder request = + HttpRequest.newBuilder(endpoint(path)) + .timeout(REQUEST_TIMEOUT) + .header("Accept", "application/json") + .header("Authorization", "Bearer " + token); + if (requestBody == null) { + request.method(method, HttpRequest.BodyPublishers.noBody()); + } else { + request.header("Content-Type", contentType); + request.method(method, HttpRequest.BodyPublishers.ofByteArray(requestBody)); + } + HttpResponse response = + client.send(request.build(), info -> new BoundedBodySubscriber(maxResponseBytes)); + requireSnapshot(); + int status = response.statusCode(); + if (status < 200 || status >= 300) { + java.util.Arrays.fill(response.body(), (byte) 0); + throw denied(); + } + return response.body(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw denied(); + } catch (Exception ex) { + requireSnapshot(); + throw denied(); + } finally { + token = null; + if (requestBody != null) { + java.util.Arrays.fill(requestBody, (byte) 0); + } + } + } + + private URI endpoint(String path) { + return URI.create( + apiBase.getScheme() + "://" + snapshot.binding().kubernetesApiAuthority() + path); + } + + private String readBearerToken() { + byte[] tokenBytes = null; + try { + tokenBytes = ProtectedBinding.readCredential(snapshot.binding().kubernetesTokenPath()); + String token = new String(tokenBytes, StandardCharsets.UTF_8).trim(); + if (token.isEmpty() || token.chars().anyMatch(Character::isWhitespace)) { + throw denied(); + } + return token; + } catch (java.io.IOException | RuntimeException ex) { + throw denied(); + } finally { + if (tokenBytes != null) java.util.Arrays.fill(tokenBytes, (byte) 0); + } + } + + private void requireSnapshot() { + try { + snapshot.requireUnchanged(bindingPath); + } catch (Exception ex) { + throw denied(); + } + } + + private static SSLContext apiSslContext(ProtectedBinding.Binding binding) throws Exception { + byte[] caBytes = ProtectedBinding.readCredential(binding.kubernetesApiCaPath()); + try { + var certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(caBytes)); + if (certificates.isEmpty()) { + throw denied(); + } + KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); + store.load(null); + int index = 0; + for (var certificate : certificates) { + store.setCertificateEntry("kubernetes-api-ca-" + index++, certificate); + } + TrustManagerFactory trust = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trust.init(store); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, trust.getTrustManagers(), null); + return context; + } finally { + java.util.Arrays.fill(caBytes, (byte) 0); + } + } + + private static String metadataUid(JsonNode root) { + JsonNode metadata = root == null ? null : root.get("metadata"); + JsonNode uid = metadata == null ? null : metadata.get("uid"); + if (uid == null || !uid.isTextual()) { + throw denied(); + } + return uid.textValue(); + } + + private static String metadataName(JsonNode root) { + return text(root, "metadata", "name"); + } + + private static String metadataNamespace(JsonNode root) { + return text(root, "metadata", "namespace"); + } + + private static String text(JsonNode root, String... path) { + JsonNode value = root; + for (String field : path) { + value = value == null ? null : value.get(field); + } + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw denied(); + } + return value.textValue(); + } + + private static IllegalStateException denied() { + return new IllegalStateException("Pinned Kubernetes API operation was denied or unavailable"); + } + + private static final class NoProxySelector extends ProxySelector { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, java.io.IOException failure) { + // No proxy is configured, so there is no proxy failure to recover from. + } + } + + private static final class BoundedBodySubscriber implements HttpResponse.BodySubscriber { + private final int maximumBytes; + private byte[] bytes; + private int length; + private final CompletableFuture result = new CompletableFuture<>(); + private Flow.Subscription subscription; + + BoundedBodySubscriber(int maximumBytes) { + this.maximumBytes = maximumBytes; + this.bytes = new byte[maximumBytes]; + } + + @Override + public CompletionStage getBody() { + return result.minimalCompletionStage(); + } + + @Override + public void onSubscribe(Flow.Subscription subscription) { + this.subscription = subscription; + subscription.request(1); + } + + @Override + public void onNext(List buffers) { + try { + if (bytes == null || result.isDone()) { + subscription.cancel(); + return; + } + for (ByteBuffer buffer : buffers) { + int count = buffer.remaining(); + if (count > maximumBytes - length) { + subscription.cancel(); + java.util.Arrays.fill(bytes, (byte) 0); + bytes = null; + result.completeExceptionally(denied()); + return; + } + buffer.get(bytes, length, count); + length += count; + } + subscription.request(1); + } catch (RuntimeException ex) { + subscription.cancel(); + result.completeExceptionally(denied()); + } + } + + @Override + public void onError(Throwable failure) { + if (bytes != null) { + java.util.Arrays.fill(bytes, (byte) 0); + bytes = null; + } + result.completeExceptionally(denied()); + } + + @Override + public void onComplete() { + if (bytes == null || result.isDone()) { + return; + } + byte[] response = java.util.Arrays.copyOf(bytes, length); + java.util.Arrays.fill(bytes, (byte) 0); + bytes = null; + result.complete(response); + } + } +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/Materializer.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/Materializer.java new file mode 100644 index 0000000000..d30b576cf8 --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/Materializer.java @@ -0,0 +1,850 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; + +/** One bounded reconciliation pass. Account remains the lifecycle and promotion authority. */ +final class Materializer { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern CONFIG_REVISION = + Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private final ProtectedBinding.Snapshot snapshot; + private final AccountOperations account; + private final KubernetesOperations kubernetes; + + Materializer( + ProtectedBinding.Snapshot snapshot, + AccountOperations account, + KubernetesOperations kubernetes) { + this.snapshot = snapshot; + this.account = account; + this.kubernetes = kubernetes; + } + + Outcome reconcileOnce() { + kubernetes.verifyClusterIdentity(); + validateEnrollment(account.enrollBootstrap()); + GetCurrentPromotionRequestResponse promotion = currentPromotionOrNull(); + if (promotion != null) { + return promote(promotion); + } + + Outcome generationOutcome = generateOrObserve(); + promotion = currentPromotionOrNull(); + if (promotion != null) { + return promote(promotion); + } + return generationOutcome; + } + + Outcome observeSecretOnce() { + kubernetes.verifyClusterIdentity(); + validateEnrollment(account.enrollBootstrap()); + if (currentPromotionOrNull() != null) { + throw denied(); + } + + GetCurrentGenerationRequestResponse request = account.getCurrentGenerationRequest(); + validateGenerationRequest(request, false); + if (request.getPhase() != GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET + || request.hasExpectedActive() + || request.hasExpectedPublishedActive()) { + throw denied(); + } + SecretState observed = kubernetes.getFixedSecret(); + validateObservedActiveSigner(request, observed); + if (!observed.signerSlots().isEmpty() + || observed.hasAnnotation(SecretState.GENERATION_OPERATION) + || observed.hasAnnotation(SecretState.GENERATION_REQUEST) + || observed.hasAnnotation(SecretState.GENERATION_PRIOR_RV) + || observed.hasAnnotation(SecretState.PROMOTION_OPERATION) + || observed.hasAnnotation(SecretState.PROMOTION_REQUEST) + || observed.hasAnnotation(SecretState.PROMOTION_PRIOR_RV)) { + throw denied(); + } + + GetCurrentGenerationRequestResponse next = + account.recordSecretObservation( + request.getOperationId(), + request.getOperationDigest(), + observed.uid(), + observed.resourceVersion()); + requireObservationCorrelation(request, observed, next); + return Outcome.SECRET_OBSERVATION_RECORDED; + } + + private void requireObservationCorrelation( + GetCurrentGenerationRequestResponse request, + SecretState observed, + GetCurrentGenerationRequestResponse next) { + validateGenerationRequest(next, true); + if (next.getPhase() != GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING + || !request.getOperationId().equals(next.getOperationId()) + || !request.getOperationDigest().equals(next.getOperationDigest()) + || !observed.uid().equals(next.getSecretUid()) + || !observed.resourceVersion().equals(next.getExpectedSecretResourceVersion())) { + throw denied(); + } + } + + private void validateEnrollment(EnrollBootstrapResponse acknowledgement) { + ProtectedBinding.Binding binding = snapshot.binding(); + if (acknowledgement == null + || !acknowledgement.getUnknownFields().asMap().isEmpty() + || acknowledgement.getSchemaVersion() != 1 + || !binding.environmentId().equals(acknowledgement.getEnvironmentId()) + || !binding.clusterId().equals(acknowledgement.getClusterId()) + || !binding.namespace().equals(acknowledgement.getNamespace()) + || !binding + .expectedClusterIncarnationUid() + .equals(acknowledgement.getExpectedClusterIncarnationUid()) + || !binding.expectedNamespaceUid().equals(acknowledgement.getExpectedNamespaceUid()) + || !binding + .accountTrustBindingDigest() + .equals(acknowledgement.getMaterializerTrustBindingDigest()) + || !binding.configRevision().equals(acknowledgement.getMaterializerTrustConfigRevision()) + || !sha256(acknowledgement.getApiBindingDigest()) + || !CONFIG_REVISION.matcher(acknowledgement.getApiConfigRevision()).matches() + || !validApiIdentity(acknowledgement) + || !SecretState.NAME.equals(acknowledgement.getPrivateSecretName()) + || !"jwt-jwks".equals(acknowledgement.getPublicConfigMapName()) + || !canonicalUuid(acknowledgement.getPublicConfigMapUid()) + || !resourceVersion(acknowledgement.getPublicConfigMapResourceVersion()) + || !sha256(acknowledgement.getPublicConfigMapSnapshotDigest())) { + throw denied(); + } + } + + private boolean validApiIdentity(EnrollBootstrapResponse acknowledgement) { + try { + String apiServerUrl = acknowledgement.getApiServerUrl(); + String tlsServerName = acknowledgement.getApiTlsServerName(); + if (apiServerUrl.length() > 512 || tlsServerName.length() > 253) { + return false; + } + java.net.URI api = java.net.URI.create(apiServerUrl); + return "https".equals(api.getScheme()) + && api.getHost() != null + && api.getRawUserInfo() == null + && api.getRawQuery() == null + && api.getRawFragment() == null + && (api.getRawPath() == null + || api.getRawPath().isEmpty() + || "/".equals(api.getRawPath())) + && api.getHost().equals(tlsServerName) + && sha256(acknowledgement.getApiServingCaSha256()) + && ("system:serviceaccount:" + snapshot.binding().namespace() + ":account-service") + .equals(acknowledgement.getApiExpectedUsername()); + } catch (RuntimeException malformed) { + return false; + } + } + + private static boolean canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + return (parsed.getLeastSignificantBits() != 0L || parsed.getMostSignificantBits() != 0L) + && parsed.toString().equals(value); + } catch (RuntimeException malformed) { + return false; + } + } + + private Outcome generateOrObserve() { + GetCurrentGenerationRequestResponse request = account.getCurrentGenerationRequest(); + validateGenerationRequest(request, false); + if (request.getPhase() == GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET) { + SecretState observed = kubernetes.getFixedSecret(); + validateObservedActiveSigner(request, observed); + GetCurrentGenerationRequestResponse next = + account.recordSecretObservation( + request.getOperationId(), + request.getOperationDigest(), + observed.uid(), + observed.resourceVersion()); + requireObservationCorrelation(request, observed, next); + request = next; + } + if (request.getPhase() == GetCurrentGenerationRequestResponse.Phase.GENERATION_RECORDED) { + return Outcome.GENERATION_ALREADY_RECORDED; + } + if (request.getPhase() != GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING) { + throw denied(); + } + return generatePending(request); + } + + private Outcome generatePending(GetCurrentGenerationRequestResponse request) { + ProtectedBinding.Binding binding = snapshot.binding(); + SecretState before = kubernetes.getFixedSecret(); + requireSecretIdentity(before.uid(), request.getSecretUid()); + requireResourceVersion(request.getExpectedSecretResourceVersion()); + String operationId = request.getOperationId(); + String requestDigest = request.getGenerationRequestDigest(); + String priorResourceVersion = request.getExpectedSecretResourceVersion(); + boolean exactMarker = + before.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + operationId, + requestDigest, + priorResourceVersion); + + SignerKeyBundle.PublicIdentity identity; + String publicJwk; + if (exactMarker) { + if (before.resourceVersion().equals(priorResourceVersion)) { + throw denied(); + } + byte[] storedPending = before.slotBytes(SecretState.PENDING); + try { + identity = + SignerKeyBundle.verify( + storedPending, + binding, + operationId, + request.getTargetGeneration(), + request.getTargetKid(), + null); + publicJwk = + SignerKeyBundle.publicJwkForBundle( + storedPending, + binding, + operationId, + request.getTargetGeneration(), + request.getTargetKid(), + identity.fingerprint()); + } finally { + wipe(storedPending); + } + validateObservedActiveSigner(request, before); + } else { + boolean sameOperationMarker = + operationId.equals(before.annotation(SecretState.GENERATION_OPERATION)) + || requestDigest.equals(before.annotation(SecretState.GENERATION_REQUEST)) + || priorResourceVersion.equals(before.annotation(SecretState.GENERATION_PRIOR_RV)); + if (sameOperationMarker + || before.containsSlot(SecretState.PENDING) + || !before.resourceVersion().equals(priorResourceVersion)) { + throw denied(); + } + validateObservedActiveSigner(request, before); + try (SignerKeyBundle.Generated generated = + SignerKeyBundle.generate( + binding, operationId, request.getTargetGeneration(), request.getTargetKid())) { + byte[] bundle = generated.bundleBytes().clone(); + try { + byte[] patch = + before.generationPatch(bundle, operationId, requestDigest, priorResourceVersion); + try { + kubernetes.patchFixedSecret(before, patch); + } catch (RuntimeException ambiguousWrite) { + // Read-only recovery is permitted only if the exact non-secret marker and pending + // bundle now read back. This path never retries or replaces an ambiguous write. + } + SecretState after = kubernetes.getFixedSecret(); + requireSecretIdentity(after.uid(), request.getSecretUid()); + requireChangedResourceVersion(priorResourceVersion, after.resourceVersion()); + requireGenerationMarker(after, request); + before.requireUnchangedExcept( + Set.of(SecretState.PENDING), + Set.of( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV), + after); + byte[] readback = after.slotBytes(SecretState.PENDING); + try { + identity = + SignerKeyBundle.verify( + readback, + binding, + operationId, + request.getTargetGeneration(), + request.getTargetKid(), + generated.identity().fingerprint()); + } finally { + wipe(readback); + } + publicJwk = generated.publicJwkJson(); + validateObservedActiveSigner(request, after); + return recordGeneration(request, after, identity, publicJwk); + } finally { + wipe(bundle); + } + } + } + SecretState readback = kubernetes.getFixedSecret(); + requireSecretIdentity(readback.uid(), request.getSecretUid()); + requireChangedResourceVersion(priorResourceVersion, readback.resourceVersion()); + requireGenerationMarker(readback, request); + byte[] persisted = readback.slotBytes(SecretState.PENDING); + try { + SignerKeyBundle.verify( + persisted, + binding, + operationId, + request.getTargetGeneration(), + request.getTargetKid(), + identity.fingerprint()); + } finally { + wipe(persisted); + } + validateObservedActiveSigner(request, readback); + return recordGeneration(request, readback, identity, publicJwk); + } + + private Outcome recordGeneration( + GetCurrentGenerationRequestResponse request, + SecretState secret, + SignerKeyBundle.PublicIdentity identity, + String publicJwk) { + var receipt = + account.recordGenerationResult( + request.getOperationId(), + request.getGenerationRequestDigest(), + secret.uid(), + request.getExpectedSecretResourceVersion(), + secret.resourceVersion(), + publicJwk); + requireGenerationReceipt(request, secret, identity, publicJwk, receipt); + return Outcome.GENERATION_RECORDED; + } + + private Outcome promote(GetCurrentPromotionRequestResponse request) { + validatePromotionRequest(request); + ProtectedBinding.Binding binding = snapshot.binding(); + SecretState before = kubernetes.getFixedSecret(); + requireSecretIdentity(before.uid(), request.getExpectedSecretUid()); + requireResourceVersion(request.getExpectedSecretResourceVersion()); + String operationId = request.getPromotionOperationId(); + String requestDigest = request.getPromotionRequestDigest(); + String priorResourceVersion = request.getExpectedSecretResourceVersion(); + boolean exactMarker = + before.operationMarkerMatches( + SecretState.PROMOTION_OPERATION, + SecretState.PROMOTION_REQUEST, + SecretState.PROMOTION_PRIOR_RV, + operationId, + requestDigest, + priorResourceVersion); + if (exactMarker) { + if (before.resourceVersion().equals(priorResourceVersion)) { + throw denied(); + } + VerifiedPromotion state = verifyPromotedState(before, request); + return recordPromotion(request, before, state.current(), state.previous()); + } + boolean sameOperationMarker = + operationId.equals(before.annotation(SecretState.PROMOTION_OPERATION)) + || requestDigest.equals(before.annotation(SecretState.PROMOTION_REQUEST)) + || priorResourceVersion.equals(before.annotation(SecretState.PROMOTION_PRIOR_RV)); + if (sameOperationMarker || !before.resourceVersion().equals(priorResourceVersion)) { + throw denied(); + } + byte[] pending = before.slotBytes(SecretState.PENDING); + byte[] oldCurrent = before.slotBytes(SecretState.CURRENT); + try { + SignerKeyBundle.PublicIdentity target = + SignerKeyBundle.verify( + pending, + binding, + request.getGenerationOperationId(), + request.getTargetGeneration(), + request.getTargetKid(), + request.getTargetPublicKeyFingerprint()); + SignerKeyBundle.PublicIdentity previous = verifyPriorCurrent(oldCurrent, request, binding); + byte[] patch = + before.promotionPatch( + pending, + previous == null ? null : oldCurrent, + operationId, + requestDigest, + priorResourceVersion); + try { + kubernetes.patchFixedSecret(before, patch); + } catch (RuntimeException ambiguousWrite) { + // The only retry path is exact, operation-bound readback; never issue another PATCH here. + } + SecretState after = kubernetes.getFixedSecret(); + requireSecretIdentity(after.uid(), request.getExpectedSecretUid()); + requireChangedResourceVersion(priorResourceVersion, after.resourceVersion()); + requirePromotionMarker(after, request); + before.requireUnchangedExcept( + Set.of(SecretState.CURRENT, SecretState.PENDING, SecretState.PREVIOUS), + Set.of( + SecretState.PROMOTION_OPERATION, + SecretState.PROMOTION_REQUEST, + SecretState.PROMOTION_PRIOR_RV), + after); + VerifiedPromotion readback = verifyPromotedState(after, request); + if (!target.equals(readback.current()) + || !java.util.Objects.equals(previous, readback.previous())) { + throw denied(); + } + return recordPromotion(request, after, readback.current(), readback.previous()); + } finally { + wipe(pending); + wipe(oldCurrent); + } + } + + private Outcome recordPromotion( + GetCurrentPromotionRequestResponse request, + SecretState after, + SignerKeyBundle.PublicIdentity current, + SignerKeyBundle.PublicIdentity previous) { + var receipt = + account.recordPrivatePromotionResult( + request, + after.uid(), + request.getExpectedSecretResourceVersion(), + after.resourceVersion(), + current, + previous, + previous == null ? List.of("current") : List.of("current", "previous")); + if (receipt.getUnknownFields().asMap().isEmpty() == false + || receipt.getSchemaVersion() != 1 + || !request.getPromotionOperationId().equals(receipt.getPromotionOperationId()) + || !request.getGenerationOperationId().equals(receipt.getGenerationOperationId()) + || !after.resourceVersion().equals(receipt.getObservedResourceVersion()) + || !SHA256.matcher(receipt.getPublicReceiptDigest()).matches()) { + throw denied(); + } + return Outcome.PRIVATE_PROMOTION_RECEIPT_RECORDED; + } + + private VerifiedPromotion verifyPromotedState( + SecretState secret, GetCurrentPromotionRequestResponse request) { + if (!secret.operationMarkerMatches( + SecretState.PROMOTION_OPERATION, + SecretState.PROMOTION_REQUEST, + SecretState.PROMOTION_PRIOR_RV, + request.getPromotionOperationId(), + request.getPromotionRequestDigest(), + request.getExpectedSecretResourceVersion()) + || secret.containsSlot(SecretState.PENDING)) { + throw denied(); + } + byte[] currentBytes = secret.slotBytes(SecretState.CURRENT); + byte[] previousBytes = secret.slotBytes(SecretState.PREVIOUS); + try { + SignerKeyBundle.PublicIdentity current = + SignerKeyBundle.verify( + currentBytes, + snapshot.binding(), + request.getGenerationOperationId(), + request.getTargetGeneration(), + request.getTargetKid(), + request.getTargetPublicKeyFingerprint()); + SignerKeyBundle.PublicIdentity previous = verifyPreviousBundle(previousBytes, request); + Set expectedSlots = + previous == null + ? Set.of(SecretState.CURRENT) + : Set.of(SecretState.CURRENT, SecretState.PREVIOUS); + if (!secret.signerSlots().equals(expectedSlots)) { + throw denied(); + } + return new VerifiedPromotion(current, previous); + } finally { + wipe(currentBytes); + wipe(previousBytes); + } + } + + private SignerKeyBundle.PublicIdentity verifyPreviousBundle( + byte[] previousBytes, GetCurrentPromotionRequestResponse request) { + if (request.getExpectedPreviousGeneration().isEmpty() + && request.getExpectedPreviousKid().isEmpty() + && request.getExpectedPreviousPublicKeyFingerprint().isEmpty()) { + if (previousBytes != null) throw denied(); + return null; + } + return SignerKeyBundle.verify( + previousBytes, + snapshot.binding(), + null, + request.getExpectedPreviousGeneration(), + request.getExpectedPreviousKid(), + request.getExpectedPreviousPublicKeyFingerprint()); + } + + private SignerKeyBundle.PublicIdentity verifyPriorCurrent( + byte[] currentBytes, + GetCurrentPromotionRequestResponse request, + ProtectedBinding.Binding binding) { + boolean expectedPresent = + !request.getExpectedPreviousGeneration().isEmpty() + || !request.getExpectedPreviousKid().isEmpty() + || !request.getExpectedPreviousPublicKeyFingerprint().isEmpty(); + if (!expectedPresent) { + if (currentBytes != null) throw denied(); + return null; + } + return SignerKeyBundle.verify( + currentBytes, + binding, + null, + request.getExpectedPreviousGeneration(), + request.getExpectedPreviousKid(), + request.getExpectedPreviousPublicKeyFingerprint()); + } + + private GetCurrentPromotionRequestResponse currentPromotionOrNull() { + try { + GetCurrentPromotionRequestResponse request = account.getCurrentPromotionRequest(); + validatePromotionRequest(request); + return request; + } catch (StatusRuntimeException ex) { + if (Status.fromThrowable(ex).getCode() == Status.Code.NOT_FOUND) { + return null; + } + throw denied(); + } + } + + private void validateGenerationRequest( + GetCurrentGenerationRequestResponse request, boolean requiresObservedSecret) { + ProtectedBinding.Binding binding = snapshot.binding(); + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || !validUuidV4(request.getOperationId()) + || !sha256(request.getOperationDigest()) + || !binding.environmentId().equals(request.getEnvironmentId()) + || !binding.clusterId().equals(request.getClusterId()) + || !binding.namespace().equals(request.getNamespace()) + || !binding + .expectedClusterIncarnationUid() + .equals(request.getExpectedClusterIncarnationUid()) + || !binding.expectedNamespaceUid().equals(request.getExpectedNamespaceUid()) + || !binding.accountTrustBindingDigest().equals(request.getTrustBindingDigest()) + || !binding.configRevision().equals(request.getTrustConfigRevision()) + || !SecretState.NAME.equals(request.getPrivateSecretName()) + || !"RS256".equals(request.getTargetAlgorithm()) + || !"MATERIALIZE_PENDING".equals(request.getOperationAction()) + || !request.getAllowedPrivateSlotsList().equals(List.of("pending")) + || !GENERATION.matcher(request.getTargetGeneration()).matches() + || !KID.matcher(request.getTargetKid()).matches() + || !positiveDecimal(request.getDesiredStateVersion())) { + throw denied(); + } + if (request.hasExpectedActive()) { + validateActive( + request.getExpectedActive().getGeneration(), request.getExpectedActive().getKid()); + if (!request.getExpectedActive().getUnknownFields().asMap().isEmpty()) throw denied(); + } + if (request.hasExpectedPublishedActive()) { + validateActive( + request.getExpectedPublishedActive().getGeneration(), + request.getExpectedPublishedActive().getKid()); + if (!request.getExpectedPublishedActive().getUnknownFields().asMap().isEmpty()) + throw denied(); + } + switch (request.getPhase()) { + case OBSERVE_PRIVATE_SECRET -> { + if (requiresObservedSecret + || !request.getGenerationRequestDigest().isEmpty() + || !request.getSecretUid().isEmpty() + || !request.getExpectedSecretResourceVersion().isEmpty() + || !request.getGenerationReceiptDigest().isEmpty() + || !request.getPublicKeyFingerprint().isEmpty() + || !request.getPublicJwkJson().isEmpty() + || !request.getObservedSecretResourceVersion().isEmpty()) { + throw denied(); + } + } + case GENERATE_PENDING -> { + if (!sha256(request.getGenerationRequestDigest()) + || !uuid(request.getSecretUid()) + || !resourceVersion(request.getExpectedSecretResourceVersion()) + || !request.getGenerationReceiptDigest().isEmpty() + || !request.getPublicKeyFingerprint().isEmpty() + || !request.getPublicJwkJson().isEmpty() + || !request.getObservedSecretResourceVersion().isEmpty()) { + throw denied(); + } + } + case GENERATION_RECORDED -> { + if (!sha256(request.getGenerationRequestDigest()) + || !uuid(request.getSecretUid()) + || !resourceVersion(request.getExpectedSecretResourceVersion()) + || !sha256(request.getGenerationReceiptDigest()) + || !sha256(request.getPublicKeyFingerprint()) + || !resourceVersion(request.getObservedSecretResourceVersion()) + || request.getPublicJwkJson().isBlank()) { + throw denied(); + } + } + default -> throw denied(); + } + } + + private void validatePromotionRequest(GetCurrentPromotionRequestResponse request) { + ProtectedBinding.Binding binding = snapshot.binding(); + boolean expectedPrevious = + !request.getExpectedPreviousGeneration().isEmpty() + || !request.getExpectedPreviousKid().isEmpty() + || !request.getExpectedPreviousPublicKeyFingerprint().isEmpty(); + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || !validUuidV4(request.getPromotionOperationId()) + || !sha256(request.getPromotionRequestDigest()) + || !validUuidV4(request.getGenerationOperationId()) + || !sha256(request.getGenerationOperationDigest()) + || !sha256(request.getGenerationReceiptDigest()) + || !binding.environmentId().equals(request.getEnvironmentId()) + || !binding.clusterId().equals(request.getClusterId()) + || !binding.namespace().equals(request.getNamespace()) + || !binding + .expectedClusterIncarnationUid() + .equals(request.getExpectedClusterIncarnationUid()) + || !binding.expectedNamespaceUid().equals(request.getExpectedNamespaceUid()) + || !binding.accountTrustBindingDigest().equals(request.getTrustBindingDigest()) + || !binding.configRevision().equals(request.getTrustConfigRevision()) + || !SecretState.NAME.equals(request.getPrivateSecretName()) + || !sha256(request.getTargetPublicKeyFingerprint()) + || !GENERATION.matcher(request.getTargetGeneration()).matches() + || !KID.matcher(request.getTargetKid()).matches() + || !"RS256".equals(request.getTargetAlgorithm()) + || !uuid(request.getExpectedSecretUid()) + || !resourceVersion(request.getExpectedSecretResourceVersion()) + || !"PROMOTE_PENDING".equals(request.getOperationAction()) + || !request + .getAllowedPrivateSlotsList() + .equals(List.of(SecretState.CURRENT, SecretState.PENDING, SecretState.PREVIOUS))) { + throw denied(); + } + if (expectedPrevious) { + if (!GENERATION.matcher(request.getExpectedPreviousGeneration()).matches() + || !KID.matcher(request.getExpectedPreviousKid()).matches() + || !sha256(request.getExpectedPreviousPublicKeyFingerprint())) { + throw denied(); + } + } else if (!request.getExpectedPreviousGeneration().isEmpty() + || !request.getExpectedPreviousKid().isEmpty() + || !request.getExpectedPreviousPublicKeyFingerprint().isEmpty()) { + throw denied(); + } + } + + private void validateObservedActiveSigner( + GetCurrentGenerationRequestResponse request, SecretState secret) { + byte[] current = secret.slotBytes(SecretState.CURRENT); + try { + if (!request.hasExpectedActive()) { + if (current != null) throw denied(); + return; + } + SignerKeyBundle.verify( + current, + snapshot.binding(), + null, + request.getExpectedActive().getGeneration(), + request.getExpectedActive().getKid(), + null); + } finally { + wipe(current); + } + } + + private void validateGenerationReceipt( + GetCurrentGenerationRequestResponse request, + SecretState secret, + SignerKeyBundle.PublicIdentity identity, + String publicJwk, + net.firedevops.firemud.account.v1.RecordGenerationResultResponse receipt) { + ProtectedBinding.Binding binding = snapshot.binding(); + if (!receipt.getUnknownFields().asMap().isEmpty() + || receipt.getSchemaVersion() != 1 + || !request.getOperationId().equals(receipt.getOperationId()) + || !request.getOperationDigest().equals(receipt.getOperationDigest()) + || !request.getGenerationRequestDigest().equals(receipt.getGenerationRequestDigest()) + || !sha256(receipt.getGenerationReceiptDigest()) + || !positiveDecimal(receipt.getDesiredStateVersion()) + || !binding.environmentId().equals(receipt.getEnvironmentId()) + || !binding.clusterId().equals(receipt.getClusterId()) + || !binding.namespace().equals(receipt.getNamespace()) + || !binding + .expectedClusterIncarnationUid() + .equals(receipt.getExpectedClusterIncarnationUid()) + || !binding.expectedNamespaceUid().equals(receipt.getExpectedNamespaceUid()) + || !binding.accountTrustBindingDigest().equals(receipt.getTrustBindingDigest()) + || !binding.configRevision().equals(receipt.getTrustConfigRevision()) + || !SecretState.NAME.equals(receipt.getPrivateSecretName()) + || !secret.uid().equals(receipt.getSecretUid()) + || !request + .getExpectedSecretResourceVersion() + .equals(receipt.getExpectedPriorResourceVersion()) + || !secret.resourceVersion().equals(receipt.getObservedResourceVersion()) + || !request.getTargetGeneration().equals(receipt.getTargetGeneration()) + || !request.getTargetKid().equals(receipt.getTargetKid()) + || !"RS256".equals(receipt.getTargetAlgorithm()) + || !identity.fingerprint().equals(receipt.getPublicKeyFingerprint()) + || !publicJwk.equals(receipt.getPublicJwkJson())) { + throw denied(); + } + } + + private void requireGenerationReceipt( + GetCurrentGenerationRequestResponse request, + SecretState secret, + SignerKeyBundle.PublicIdentity identity, + String publicJwk, + net.firedevops.firemud.account.v1.RecordGenerationResultResponse receipt) { + validateGenerationReceipt(request, secret, identity, publicJwk, receipt); + } + + private void requireGenerationMarker( + SecretState secret, GetCurrentGenerationRequestResponse request) { + if (!secret.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + request.getOperationId(), + request.getGenerationRequestDigest(), + request.getExpectedSecretResourceVersion())) { + throw denied(); + } + } + + private void requirePromotionMarker( + SecretState secret, GetCurrentPromotionRequestResponse request) { + if (!secret.operationMarkerMatches( + SecretState.PROMOTION_OPERATION, + SecretState.PROMOTION_REQUEST, + SecretState.PROMOTION_PRIOR_RV, + request.getPromotionOperationId(), + request.getPromotionRequestDigest(), + request.getExpectedSecretResourceVersion())) { + throw denied(); + } + } + + private static void validateActive(String generation, String kid) { + if (!GENERATION.matcher(generation).matches() || !KID.matcher(kid).matches()) { + throw denied(); + } + } + + private static boolean validUuidV4(String value) { + try { + UUID parsed = UUID.fromString(value); + return parsed.version() == 4 && parsed.variant() == 2 && parsed.toString().equals(value); + } catch (RuntimeException ex) { + return false; + } + } + + private static boolean uuid(String value) { + try { + return java.util.UUID.fromString(value).toString().equals(value); + } catch (RuntimeException ex) { + return false; + } + } + + private static boolean sha256(String value) { + return SHA256.matcher(value).matches(); + } + + private static boolean resourceVersion(String value) { + return RESOURCE_VERSION.matcher(value).matches(); + } + + private static boolean positiveDecimal(String value) { + return value.matches("[1-9][0-9]{0,18}"); + } + + private static void requireSecretIdentity(String observedUid, String expectedUid) { + if (!observedUid.equals(expectedUid)) throw denied(); + } + + private static void requireChangedResourceVersion(String before, String after) { + if (!resourceVersion(after) || before.equals(after)) throw denied(); + } + + private static void requireResourceVersion(String value) { + if (!resourceVersion(value)) throw denied(); + } + + private static void wipe(byte[] bytes) { + if (bytes != null) java.util.Arrays.fill(bytes, (byte) 0); + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Account-authorized JWT materialization could not be reconciled"); + } + + enum Outcome { + SECRET_OBSERVATION_RECORDED("secret_observation_recorded"), + GENERATION_RECORDED("generation_recorded"), + GENERATION_ALREADY_RECORDED("generation_already_recorded"), + PRIVATE_PROMOTION_RECEIPT_RECORDED("private_promotion_receipt_recorded"); + + private final String publicName; + + Outcome(String publicName) { + this.publicName = publicName; + } + + String publicName() { + return publicName; + } + } + + private record VerifiedPromotion( + SignerKeyBundle.PublicIdentity current, SignerKeyBundle.PublicIdentity previous) {} + + interface AccountOperations { + EnrollBootstrapResponse enrollBootstrap(); + + GetCurrentGenerationRequestResponse getCurrentGenerationRequest(); + + GetCurrentGenerationRequestResponse recordSecretObservation( + String operationId, + String operationDigest, + String secretUid, + String observedResourceVersion); + + RecordGenerationResultResponse recordGenerationResult( + String operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson); + + GetCurrentPromotionRequestResponse getCurrentPromotionRequest(); + + RecordPrivatePromotionResultResponse recordPrivatePromotionResult( + GetCurrentPromotionRequestResponse request, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + SignerKeyBundle.PublicIdentity current, + SignerKeyBundle.PublicIdentity previous, + List resultingSlots); + } + + interface KubernetesOperations { + void verifyClusterIdentity(); + + SecretState getFixedSecret(); + + void patchFixedSecret(SecretState before, byte[] mergePatch); + } +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerMain.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerMain.java new file mode 100644 index 0000000000..1dd31ae0fe --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerMain.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +/** One-shot process entry point. Output contains only a bounded public outcome token. */ +public final class MaterializerMain { + private MaterializerMain() {} + + public static void main(String[] args) { + boolean observeOnly; + if (args.length == 0) { + observeOnly = false; + } else if (args.length == 1 && "--observe-only".equals(args[0])) { + observeOnly = true; + } else { + deny(); + return; + } + try { + ProtectedBinding.Snapshot snapshot = ProtectedBinding.loadDefault(); + try (AccountClient account = new AccountClient(snapshot, ProtectedBinding.DEFAULT_PATH)) { + KubernetesApi kubernetes = new KubernetesApi(snapshot, ProtectedBinding.DEFAULT_PATH); + Materializer materializer = new Materializer(snapshot, account, kubernetes); + Materializer.Outcome outcome = + observeOnly ? materializer.observeSecretOnce() : materializer.reconcileOnce(); + System.out.println("{\"schemaVersion\":1,\"outcome\":\"" + outcome.publicName() + "\"}"); + } + } catch (java.io.IOException | RuntimeException ignored) { + deny(); + } + } + + private static void deny() { + System.out.println("{\"schemaVersion\":1,\"outcome\":\"denied\"}"); + System.exit(2); + } +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/ProtectedBinding.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/ProtectedBinding.java new file mode 100644 index 0000000000..24f03500ee --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/ProtectedBinding.java @@ -0,0 +1,597 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +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.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Reads the protected, read-only trust and endpoint snapshot for one custodian invocation. */ +final class ProtectedBinding { + static final Path DEFAULT_PATH = Path.of("/etc/firemud/account-jwt-materializer/binding.json"); + static final int MAX_BINDING_BYTES = 8 * 1024; + private static final int MAX_CREDENTIAL_BYTES = 64 * 1024; + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set FIELDS = + Set.of( + "schemaVersion", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedKubeSystemNamespaceUid", + "expectedServiceAccountName", + "expectedServiceAccountUid", + "expectedMaterializerSpiffeUri", + "materializerSpkiSha256", + "materializerSpkiSha256Pins", + "accountTarget", + "accountServerDnsName", + "expectedAccountSpiffeUri", + "accountServerSpkiSha256Pins", + "accountCaPath", + "clientCertificatePath", + "clientPrivateKeyPath", + "kubernetesApiServerUri", + "kubernetesApiCaPath", + "kubernetesTokenPath"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private ProtectedBinding() {} + + static Snapshot loadDefault() throws IOException { + return load(DEFAULT_PATH); + } + + static Snapshot load(Path bindingPath) throws IOException { + byte[] bindingBytes = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + Binding binding = parse(bindingBytes); + Map fileDigests = new LinkedHashMap<>(); + fileDigests.put( + binding.accountCaPath(), digestFile(binding.accountCaPath(), MAX_CREDENTIAL_BYTES)); + fileDigests.put( + binding.clientCertificatePath(), + digestFile(binding.clientCertificatePath(), MAX_CREDENTIAL_BYTES)); + fileDigests.put( + binding.clientPrivateKeyPath(), + digestFile(binding.clientPrivateKeyPath(), MAX_CREDENTIAL_BYTES)); + fileDigests.put( + binding.kubernetesApiCaPath(), + digestFile(binding.kubernetesApiCaPath(), MAX_CREDENTIAL_BYTES)); + byte[] token = readProtectedFile(binding.kubernetesTokenPath(), 16 * 1024); + try { + validateServiceAccountToken(token, binding); + fileDigests.put(binding.kubernetesTokenPath(), digest(token)); + } finally { + java.util.Arrays.fill(token, (byte) 0); + } + validateCertificates(binding); + byte[] bindingReadback = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + try { + if (!MessageDigest.isEqual(bindingBytes, bindingReadback)) { + throw denied(); + } + } finally { + java.util.Arrays.fill(bindingReadback, (byte) 0); + } + for (Map.Entry entry : fileDigests.entrySet()) { + if (!entry.getValue().equals(digestFile(entry.getKey(), MAX_CREDENTIAL_BYTES))) { + throw denied(); + } + } + Map snapshotFields = new LinkedHashMap<>(); + snapshotFields.put("binding", digest(bindingBytes)); + fileDigests.forEach((path, fileDigest) -> snapshotFields.put(path.toString(), fileDigest)); + return new Snapshot(binding, digest(canonicalJson(snapshotFields))); + } + + static Binding parse(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw denied(); + } + try { + JsonNode root = JSON.readTree(bytes); + requireExactObject(root, FIELDS); + if (integer(root, "schemaVersion") != 1 || !bool(root, "enabled")) { + throw denied(); + } + String revision = text(root, "configRevision", 128); + String environment = text(root, "environmentId", 63); + String cluster = text(root, "clusterId", 128); + String namespace = text(root, "namespace", 63); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environment).matches() + || !CLUSTER.matcher(cluster).matches() + || !ENVIRONMENT.matcher(namespace).matches()) { + throw denied(); + } + String clusterUid = uuid(text(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = uuid(text(root, "expectedNamespaceUid", 36)); + String kubeSystemUid = uuid(text(root, "expectedKubeSystemNamespaceUid", 36)); + if (!clusterUid.equals(kubeSystemUid)) { + throw denied(); + } + String serviceAccount = text(root, "expectedServiceAccountName", 63); + String serviceAccountUid = uuid(text(root, "expectedServiceAccountUid", 36)); + if (!"account-jwt-materializer".equals(serviceAccount) + || !ENVIRONMENT.matcher(serviceAccount).matches()) { + throw denied(); + } + String materializerUri = text(root, "expectedMaterializerSpiffeUri", 256); + String expectedMaterializerUri = "spiffe://firemud/ns/" + namespace + "/sa/" + serviceAccount; + if (!expectedMaterializerUri.equals(materializerUri)) { + throw denied(); + } + String clientSpki = hex(text(root, "materializerSpkiSha256", 64)); + List clientPins = pins(root.get("materializerSpkiSha256Pins")); + if (!clientPins.contains(clientSpki)) { + throw denied(); + } + + String accountTarget = text(root, "accountTarget", 256); + String accountDns = text(root, "accountServerDnsName", 253); + String accountUri = text(root, "expectedAccountSpiffeUri", 256); + if (!accountTarget.matches("[A-Za-z0-9.-]+:[1-9][0-9]{0,4}") + || !accountTarget.substring(0, accountTarget.lastIndexOf(':')).equals(accountDns) + || Integer.parseInt(accountTarget.substring(accountTarget.lastIndexOf(':') + 1)) > 65535 + || accountDns.isBlank() + || !accountUri.equals("spiffe://firemud/ns/" + namespace + "/sa/account-service")) { + throw denied(); + } + List accountPins = pins(root.get("accountServerSpkiSha256Pins")); + Path accountCa = absolutePath(text(root, "accountCaPath", 512)); + Path clientCertificate = absolutePath(text(root, "clientCertificatePath", 512)); + Path clientPrivateKey = absolutePath(text(root, "clientPrivateKeyPath", 512)); + URIValue apiUri = apiUri(text(root, "kubernetesApiServerUri", 512)); + Path apiCa = absolutePath(text(root, "kubernetesApiCaPath", 512)); + Path token = absolutePath(text(root, "kubernetesTokenPath", 512)); + String digest = + computeAccountTrustDigest( + revision, + environment, + cluster, + namespace, + clusterUid, + namespaceUid, + materializerUri, + clientPins); + if (digest.isBlank()) { + throw denied(); + } + return new Binding( + revision, + environment, + cluster, + namespace, + clusterUid, + namespaceUid, + kubeSystemUid, + serviceAccount, + serviceAccountUid, + materializerUri, + clientSpki, + clientPins, + digest, + accountTarget, + accountDns, + accountUri, + accountPins, + accountCa, + clientCertificate, + clientPrivateKey, + apiUri.uri(), + apiUri.authority(), + apiCa, + token); + } catch (RuntimeException ex) { + throw denied(); + } + } + + private static String computeAccountTrustDigest( + String revision, + String environment, + String cluster, + String namespace, + String clusterUid, + String namespaceUid, + String peerUri, + List pins) { + Map fields = new LinkedHashMap<>(); + fields.put("digestVersion", "account-jwt-signer-materializer-binding/v1"); + fields.put("configRevision", revision); + fields.put("environmentId", environment); + fields.put("clusterId", cluster); + fields.put("namespace", namespace); + fields.put("expectedClusterIncarnationUid", clusterUid); + fields.put("expectedNamespaceUid", namespaceUid); + fields.put("expectedPeerUri", peerUri); + fields.put("peerSpkiSha256Pins", List.copyOf(pins)); + return digest(canonicalJson(fields)); + } + + private static void validateCertificates(Binding binding) throws IOException { + byte[] clientBytes = readProtectedFile(binding.clientCertificatePath(), MAX_CREDENTIAL_BYTES); + try { + X509Certificate leaf = firstCertificate(clientBytes); + if (!leaf.getPublicKey().getAlgorithm().equalsIgnoreCase("RSA") + && !leaf.getPublicKey().getAlgorithm().equalsIgnoreCase("EC")) { + throw denied(); + } + if (!binding.materializerSpkiSha256().equals(digest(leaf.getPublicKey().getEncoded()))) { + throw denied(); + } + Set uris = new LinkedHashSet<>(); + for (List name : + leaf.getSubjectAlternativeNames() == null + ? List.>of() + : leaf.getSubjectAlternativeNames()) { + if (name.size() >= 2 + && Integer.valueOf(6).equals(name.get(0)) + && name.get(1) instanceof String uri) { + uris.add(uri); + } + } + if (!uris.equals(Set.of(binding.expectedMaterializerSpiffeUri()))) { + throw denied(); + } + } catch (Exception ex) { + throw denied(); + } finally { + java.util.Arrays.fill(clientBytes, (byte) 0); + } + validateCaFile(binding.accountCaPath()); + validateCaFile(binding.kubernetesApiCaPath()); + } + + static X509Certificate firstCertificate(byte[] pem) throws Exception { + var certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new java.io.ByteArrayInputStream(pem)); + return certificates.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .findFirst() + .orElseThrow(ProtectedBinding::denied); + } + + private static void validateCaFile(Path path) throws IOException { + byte[] bytes = readProtectedFile(path, MAX_CREDENTIAL_BYTES); + try { + var certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new java.io.ByteArrayInputStream(bytes)); + if (certificates.isEmpty()) { + throw denied(); + } + } catch (java.security.cert.CertificateException | RuntimeException ex) { + throw denied(); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + } + } + + private static void validateServiceAccountToken(byte[] tokenBytes, Binding binding) { + try { + String token = decodeUtf8(tokenBytes).trim(); + String[] segments = token.split("\\.", -1); + if (segments.length != 3 || segments[1].isEmpty()) { + throw denied(); + } + byte[] payload = Base64.getUrlDecoder().decode(segments[1]); + try { + JsonNode claims = JSON.readTree(payload); + String expectedSubject = + "system:serviceaccount:" + + binding.namespace() + + ":" + + binding.expectedServiceAccountName(); + JsonNode kubernetes = claims.get("kubernetes.io"); + JsonNode serviceAccount = kubernetes == null ? null : kubernetes.get("serviceaccount"); + if (!expectedSubject.equals(text(claims, "sub", 256)) + || !binding.namespace().equals(text(kubernetes, "namespace", 63)) + || !binding.expectedServiceAccountName().equals(text(serviceAccount, "name", 63)) + || !binding.expectedServiceAccountUid().equals(text(serviceAccount, "uid", 36))) { + throw denied(); + } + } finally { + java.util.Arrays.fill(payload, (byte) 0); + } + } catch (RuntimeException ex) { + throw denied(); + } + } + + static byte[] readProtectedFile(Path path, int maximumBytes) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (!absolute.equals(path) || Files.isSymbolicLink(absolute)) { + throw denied(); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > maximumBytes) { + throw denied(); + } + requireRootOwnedReadOnly(absolute); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw denied(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw denied(); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + java.util.Arrays.fill(bytes, (byte) 0); + throw denied(); + } + requireRootOwnedReadOnly(absolute); + return bytes; + } + + static byte[] readCredential(Path path) throws IOException { + return readProtectedFile(path, MAX_CREDENTIAL_BYTES); + } + + private static String digestFile(Path path, int maximumBytes) throws IOException { + byte[] bytes = readProtectedFile(path, maximumBytes); + try { + return digest(bytes); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + } + } + + private static void requireRootOwnedReadOnly(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file) || !parent.toRealPath().equals(parent)) { + throw denied(); + } + Object fileUid = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object parentUid = + Files.getAttribute(parent.toRealPath(), "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set filePermissions = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set parentPermissions = Files.getPosixFilePermissions(parent.toRealPath()); + if (!(fileUid instanceof Number owner) + || owner.longValue() != 0 + || !(parentUid instanceof Number parentOwner) + || parentOwner.longValue() != 0 + || writable(filePermissions) + || writable(parentPermissions)) { + throw denied(); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static URIValue apiUri(String value) { + try { + java.net.URI uri = java.net.URI.create(value); + if (!"https".equals(uri.getScheme()) + || uri.getHost() == null + || uri.getUserInfo() != null + || uri.getQuery() != null + || uri.getFragment() != null + || (uri.getPath() != null && !uri.getPath().isEmpty() && !"/".equals(uri.getPath())) + || uri.getPort() < 1 + || uri.getPort() > 65535) { + throw denied(); + } + return new URIValue(uri, uri.getRawAuthority()); + } catch (RuntimeException ex) { + throw denied(); + } + } + + private static Path absolutePath(String value) { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.normalize().equals(path) || path.toString().contains("..")) { + throw denied(); + } + return path; + } + + private static List pins(JsonNode node) { + if (node == null || !node.isArray() || node.size() == 0 || node.size() > 8) { + throw denied(); + } + List pins = new ArrayList<>(); + for (JsonNode entry : node) { + String pin = hex(entry.isTextual() ? entry.textValue() : ""); + if (pins.contains(pin)) { + throw denied(); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static String uuid(String value) { + java.util.UUID uuid = java.util.UUID.fromString(value); + if (!uuid.toString().equals(value) || uuid.equals(new java.util.UUID(0L, 0L))) { + throw denied(); + } + return value; + } + + private static String hex(String value) { + if (!SHA256.matcher(value).matches()) { + throw denied(); + } + return value; + } + + private static void requireExactObject(JsonNode node, Set fields) { + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw denied(); + } + for (Map.Entry field : node.properties()) { + if (!fields.contains(field.getKey())) { + throw denied(); + } + } + } + + private static String text(JsonNode object, String name, int maxLength) { + JsonNode value = object == null ? null : object.get(name); + if (value == null || !value.isTextual()) { + throw denied(); + } + String result = value.textValue(); + if (result.isEmpty() || result.length() > maxLength || containsControl(result)) { + throw denied(); + } + return result; + } + + private static int integer(JsonNode object, String name) { + JsonNode value = object.get(name); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw denied(); + } + return value.intValue(); + } + + private static boolean bool(JsonNode object, String name) { + JsonNode value = object.get(name); + if (value == null || !value.isBoolean()) { + throw denied(); + } + return value.booleanValue(); + } + + private static boolean containsControl(String value) { + return value.chars().anyMatch(Character::isISOControl); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw denied(); + } + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw denied(); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw denied(); + } + } + + private static RuntimeException denied() { + return new IllegalArgumentException("Protected materializer binding is unavailable"); + } + + record Binding( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedKubeSystemNamespaceUid, + String expectedServiceAccountName, + String expectedServiceAccountUid, + String expectedMaterializerSpiffeUri, + String materializerSpkiSha256, + List materializerSpkiSha256Pins, + String accountTrustBindingDigest, + String accountTarget, + String accountServerDnsName, + String expectedAccountSpiffeUri, + List accountServerSpkiSha256Pins, + Path accountCaPath, + Path clientCertificatePath, + Path clientPrivateKeyPath, + java.net.URI kubernetesApiServerUri, + String kubernetesApiAuthority, + Path kubernetesApiCaPath, + Path kubernetesTokenPath) { + Binding { + materializerSpkiSha256Pins = List.copyOf(materializerSpkiSha256Pins); + accountServerSpkiSha256Pins = List.copyOf(accountServerSpkiSha256Pins); + } + } + + record Snapshot(Binding binding, String digest) { + Snapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(digest); + } + + void requireUnchanged(Path bindingPath) throws IOException { + Snapshot current = load(bindingPath); + if (!digest.equals(current.digest())) { + throw denied(); + } + } + } + + private record URIValue(java.net.URI uri, String authority) {} +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SecretState.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SecretState.java new file mode 100644 index 0000000000..da61923e8a --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SecretState.java @@ -0,0 +1,266 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Strict, bounded view of the one pre-created Kubernetes Secret. */ +final class SecretState { + static final String NAME = "jwt-signing-keys"; + static final String CURRENT = "current.key"; + static final String PENDING = "pending.key"; + static final String PREVIOUS = "previous.key"; + static final String GENERATION_OPERATION = "firemud.dev/jwt-generation-operation-id"; + static final String GENERATION_REQUEST = "firemud.dev/jwt-generation-request-digest"; + static final String GENERATION_PRIOR_RV = "firemud.dev/jwt-generation-expected-prior-rv"; + static final String PROMOTION_OPERATION = "firemud.dev/jwt-promotion-operation-id"; + static final String PROMOTION_REQUEST = "firemud.dev/jwt-promotion-request-digest"; + static final String PROMOTION_PRIOR_RV = "firemud.dev/jwt-promotion-expected-prior-rv"; + static final int MAX_SECRET_JSON_BYTES = 2 * 1024 * 1024; + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final String namespace; + private final String uid; + private final String resourceVersion; + private final Map data; + private final Map annotations; + + private SecretState( + String namespace, + String uid, + String resourceVersion, + Map data, + Map annotations) { + this.namespace = namespace; + this.uid = uid; + this.resourceVersion = resourceVersion; + this.data = Collections.unmodifiableMap(new LinkedHashMap<>(data)); + this.annotations = Collections.unmodifiableMap(new LinkedHashMap<>(annotations)); + } + + static SecretState parse(byte[] bytes, String expectedNamespace) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_SECRET_JSON_BYTES) { + throw denied(); + } + try { + JsonNode root = JSON.readTree(bytes); + if (root == null + || !"v1".equals(text(root, "apiVersion")) + || !"Secret".equals(text(root, "kind")) + || !NAME.equals(text(root, "metadata", "name")) + || !expectedNamespace.equals(text(root, "metadata", "namespace")) + || !"Opaque".equals(text(root, "type"))) { + throw denied(); + } + String uid = text(root, "metadata", "uid"); + java.util.UUID parsedUid = java.util.UUID.fromString(uid); + String resourceVersion = text(root, "metadata", "resourceVersion"); + if (!parsedUid.toString().equals(uid) + || !RESOURCE_VERSION.matcher(resourceVersion).matches()) { + throw denied(); + } + return new SecretState( + expectedNamespace, + uid, + resourceVersion, + stringMap(root.get("data")), + stringMap(child(root, "metadata", "annotations"))); + } catch (RuntimeException ex) { + throw denied(); + } + } + + String namespace() { + return namespace; + } + + String uid() { + return uid; + } + + String resourceVersion() { + return resourceVersion; + } + + Map annotations() { + return annotations; + } + + Set signerSlots() { + Set slots = new LinkedHashSet<>(); + if (data.containsKey(CURRENT)) slots.add(CURRENT); + if (data.containsKey(PENDING)) slots.add(PENDING); + if (data.containsKey(PREVIOUS)) slots.add(PREVIOUS); + return Set.copyOf(slots); + } + + boolean containsSlot(String slot) { + return data.containsKey(slot); + } + + byte[] slotBytes(String slot) { + String encoded = data.get(slot); + if (encoded == null || encoded.isEmpty()) { + return null; + } + try { + return Base64.getDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw denied(); + } + } + + String encodedSlot(String slot) { + return data.get(slot); + } + + boolean hasAnnotation(String key) { + return annotations.containsKey(key); + } + + String annotation(String key) { + return annotations.get(key); + } + + byte[] generationPatch( + byte[] pendingBundle, + String operationId, + String requestDigest, + String expectedPriorResourceVersion) { + Map dataChanges = new LinkedHashMap<>(); + dataChanges.put(PENDING, Base64.getEncoder().encodeToString(pendingBundle)); + Map annotationChanges = + Map.of( + GENERATION_OPERATION, operationId, + GENERATION_REQUEST, requestDigest, + GENERATION_PRIOR_RV, expectedPriorResourceVersion); + return patchBody(dataChanges, annotationChanges); + } + + byte[] promotionPatch( + byte[] targetBundle, + byte[] priorCurrentBundle, + String operationId, + String requestDigest, + String expectedPriorResourceVersion) { + Map dataChanges = new LinkedHashMap<>(); + dataChanges.put(CURRENT, Base64.getEncoder().encodeToString(targetBundle)); + dataChanges.put(PENDING, null); + dataChanges.put( + PREVIOUS, + priorCurrentBundle == null ? null : Base64.getEncoder().encodeToString(priorCurrentBundle)); + Map annotationChanges = + Map.of( + PROMOTION_OPERATION, operationId, + PROMOTION_REQUEST, requestDigest, + PROMOTION_PRIOR_RV, expectedPriorResourceVersion); + return patchBody(dataChanges, annotationChanges); + } + + boolean operationMarkerMatches( + String idKey, + String digestKey, + String priorRvKey, + String operationId, + String digest, + String priorRv) { + return operationId.equals(annotations.get(idKey)) + && digest.equals(annotations.get(digestKey)) + && priorRv.equals(annotations.get(priorRvKey)); + } + + void requireUnchangedExcept( + Set changedSlots, Set changedAnnotations, SecretState after) { + if (!uid.equals(after.uid) || !namespace.equals(after.namespace)) { + throw denied(); + } + for (Map.Entry entry : data.entrySet()) { + if (!changedSlots.contains(entry.getKey()) + && !entry.getValue().equals(after.data.get(entry.getKey()))) { + throw denied(); + } + } + for (String key : after.data.keySet()) { + if (!changedSlots.contains(key) && !data.containsKey(key)) { + throw denied(); + } + } + for (Map.Entry entry : annotations.entrySet()) { + if (!changedAnnotations.contains(entry.getKey()) + && !entry.getValue().equals(after.annotations.get(entry.getKey()))) { + throw denied(); + } + } + for (String key : after.annotations.keySet()) { + if (!changedAnnotations.contains(key) && !annotations.containsKey(key)) { + throw denied(); + } + } + } + + private byte[] patchBody(Map dataChanges, Map annotationChanges) { + Map metadata = new LinkedHashMap<>(); + metadata.put("uid", uid); + metadata.put("resourceVersion", resourceVersion); + metadata.put("annotations", annotationChanges); + Map body = new LinkedHashMap<>(); + body.put("metadata", metadata); + body.put("data", dataChanges); + try { + return JSON.writeValueAsString(body).getBytes(StandardCharsets.UTF_8); + } catch (Exception ex) { + throw denied(); + } + } + + private static Map stringMap(JsonNode node) { + if (node == null || node.isNull()) { + return Map.of(); + } + if (!node.isObject()) { + throw denied(); + } + Map values = new LinkedHashMap<>(); + for (Map.Entry entry : node.properties()) { + if (!entry.getValue().isTextual()) { + throw denied(); + } + values.put(entry.getKey(), entry.getValue().textValue()); + } + return values; + } + + private static JsonNode child(JsonNode root, String... path) { + JsonNode current = root; + for (String field : path) { + current = current == null ? null : current.get(field); + } + return current; + } + + private static String text(JsonNode root, String... path) { + JsonNode node = child(root, path); + if (node == null || !node.isTextual() || node.textValue().isBlank()) { + throw denied(); + } + return node.textValue(); + } + + private static IllegalArgumentException denied() { + return new IllegalArgumentException("Fixed JWT Secret state is unavailable"); + } +} diff --git a/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SignerKeyBundle.java b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SignerKeyBundle.java new file mode 100644 index 0000000000..dcbf9d5c6d --- /dev/null +++ b/k8s/account-jwt-materializer/src/main/java/net/firedevops/firemud/accountjwtmaterializer/SignerKeyBundle.java @@ -0,0 +1,398 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Private-key bundle v1 codec; no signing operation is exposed. */ +final class SignerKeyBundle { + static final int MAX_BUNDLE_BYTES = 64 * 1024; + private static final int MAX_DER_BYTES = 16 * 1024; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_RSA_BITS = 16_384; + private static final String ALGORITHM = "RS256"; + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set BUNDLE_FIELDS = + Set.of( + "version", + "environmentId", + "clusterId", + "namespace", + "operationId", + "generation", + "kid", + "algorithm", + "privateKeyPkcs8", + "publicKeyFingerprint"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private SignerKeyBundle() {} + + static Generated generate( + ProtectedBinding.Binding binding, String operationId, String generation, String kid) { + validateIdentity(binding, operationId, generation, kid); + byte[] privateDer = null; + byte[] bundleBytes = null; + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3_072, RSAKeyGenParameterSpec.F4)); + KeyPair pair = generator.generateKeyPair(); + RSAPrivateCrtKey privateKey = requireStrongKey(pair.getPrivate()); + RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); + if (publicKey.getModulus().bitLength() != 3_072 + || !BigInteger.valueOf(65_537).equals(publicKey.getPublicExponent()) + || !publicKey.getModulus().equals(privateKey.getModulus())) { + throw denied(); + } + privateDer = privateKey.getEncoded(); + if (privateDer == null || privateDer.length == 0 || privateDer.length > MAX_DER_BYTES) { + throw denied(); + } + String fingerprint = fingerprint(publicKey); + String publicJwk = publicJwk(publicKey, kid); + Map fields = new LinkedHashMap<>(); + fields.put("version", 1); + fields.put("environmentId", binding.environmentId()); + fields.put("clusterId", binding.clusterId()); + fields.put("namespace", binding.namespace()); + fields.put("operationId", operationId); + fields.put("generation", generation); + fields.put("kid", kid); + fields.put("algorithm", ALGORITHM); + fields.put( + "privateKeyPkcs8", Base64.getUrlEncoder().withoutPadding().encodeToString(privateDer)); + fields.put("publicKeyFingerprint", fingerprint); + bundleBytes = canonicalJson(fields); + if (bundleBytes.length > MAX_BUNDLE_BYTES) { + throw denied(); + } + return new Generated( + bundleBytes, publicJwk, new PublicIdentity(generation, kid, fingerprint, operationId)); + } catch (java.security.GeneralSecurityException | RuntimeException ex) { + wipe(bundleBytes); + throw denied(); + } finally { + wipe(privateDer); + } + } + + static PublicIdentity verify( + byte[] bundleBytes, + ProtectedBinding.Binding binding, + String expectedOperationId, + String expectedGeneration, + String expectedKid, + String expectedFingerprint) { + byte[] privateDer = null; + try { + if (bundleBytes == null || bundleBytes.length == 0 || bundleBytes.length > MAX_BUNDLE_BYTES) { + throw denied(); + } + JsonNode root = JSON.readTree(bundleBytes); + requireExactObject(root, BUNDLE_FIELDS); + JsonNode version = root.get("version"); + if (version == null || !version.isIntegralNumber() || version.intValue() != 1) { + throw denied(); + } + String environment = text(root, "environmentId", 63); + String cluster = text(root, "clusterId", 128); + String namespace = text(root, "namespace", 63); + String operation = canonicalUuidV4(text(root, "operationId", 36)); + String generation = text(root, "generation", 64); + String kid = text(root, "kid", 64); + String algorithm = text(root, "algorithm", 8); + String declaredFingerprint = text(root, "publicKeyFingerprint", 64); + String privateKeyEncoded = text(root, "privateKeyPkcs8", 24 * 1024); + if (!binding.environmentId().equals(environment) + || !binding.clusterId().equals(cluster) + || !binding.namespace().equals(namespace) + || (expectedOperationId != null && !expectedOperationId.equals(operation)) + || (expectedGeneration != null && !expectedGeneration.equals(generation)) + || (expectedKid != null && !expectedKid.equals(kid)) + || (expectedFingerprint != null && !expectedFingerprint.equals(declaredFingerprint)) + || !ALGORITHM.equals(algorithm) + || !GENERATION.matcher(generation).matches() + || !KID.matcher(kid).matches() + || !SHA256.matcher(declaredFingerprint).matches()) { + throw denied(); + } + validateIdentity(binding, operation, generation, kid); + privateDer = decodeCanonicalBase64Url(privateKeyEncoded, MAX_DER_BYTES); + PrivateKey parsed = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + RSAPrivateCrtKey privateKey = requireStrongKey(parsed); + byte[] canonicalDer = privateKey.getEncoded(); + try { + if (canonicalDer == null || !MessageDigest.isEqual(privateDer, canonicalDer)) { + throw denied(); + } + } finally { + wipe(canonicalDer); + } + RSAPublicKey publicKey = publicKey(privateKey); + if (!declaredFingerprint.equals(fingerprint(publicKey))) { + throw denied(); + } + return new PublicIdentity(generation, kid, declaredFingerprint, operation); + } catch (RuntimeException | java.security.GeneralSecurityException ex) { + throw denied(); + } finally { + wipe(privateDer); + } + } + + static String publicJwkForBundle( + byte[] bundleBytes, + ProtectedBinding.Binding binding, + String expectedOperationId, + String expectedGeneration, + String expectedKid, + String expectedFingerprint) { + byte[] privateDer = null; + try { + PublicIdentity identity = + verify( + bundleBytes, + binding, + expectedOperationId, + expectedGeneration, + expectedKid, + expectedFingerprint); + JsonNode root = JSON.readTree(bundleBytes); + privateDer = + decodeCanonicalBase64Url(text(root, "privateKeyPkcs8", 24 * 1024), MAX_DER_BYTES); + PrivateKey parsed = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + return publicJwk(publicKey(requireStrongKey(parsed)), identity.kid()); + } catch (java.security.GeneralSecurityException | RuntimeException ex) { + throw denied(); + } finally { + wipe(privateDer); + } + } + + static String fingerprint(RSAPublicKey publicKey) { + Map thumbprint = new LinkedHashMap<>(); + thumbprint.put("e", unsignedBase64Url(publicKey.getPublicExponent())); + thumbprint.put("kty", "RSA"); + thumbprint.put("n", unsignedBase64Url(publicKey.getModulus())); + return sha256(canonicalJson(thumbprint)); + } + + private static String publicJwk(RSAPublicKey publicKey, String kid) { + Map jwk = new LinkedHashMap<>(); + jwk.put("kty", "RSA"); + jwk.put("use", "sig"); + jwk.put("alg", ALGORITHM); + jwk.put("kid", kid); + jwk.put("key_ops", java.util.List.of("verify")); + jwk.put("n", unsignedBase64Url(publicKey.getModulus())); + jwk.put("e", unsignedBase64Url(publicKey.getPublicExponent())); + return new String(canonicalJson(jwk), StandardCharsets.UTF_8); + } + + private static String unsignedBase64Url(BigInteger value) { + byte[] encoded = value.toByteArray(); + try { + int start = encoded.length > 1 && encoded[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(Arrays.copyOfRange(encoded, start, encoded.length)); + } finally { + wipe(encoded); + } + } + + private static RSAPublicKey publicKey(RSAPrivateCrtKey privateKey) + throws java.security.GeneralSecurityException { + return (RSAPublicKey) + KeyFactory.getInstance("RSA") + .generatePublic( + new java.security.spec.RSAPublicKeySpec( + privateKey.getModulus(), privateKey.getPublicExponent())); + } + + private static RSAPrivateCrtKey requireStrongKey(PrivateKey key) { + if (!(key instanceof RSAPrivateCrtKey rsa) + || !"RSA".equalsIgnoreCase(key.getAlgorithm()) + || rsa.getModulus().bitLength() < MIN_RSA_BITS + || rsa.getModulus().bitLength() > MAX_RSA_BITS + || !BigInteger.valueOf(65_537).equals(rsa.getPublicExponent()) + || !positive(rsa.getPrivateExponent()) + || !positive(rsa.getPrimeP()) + || !positive(rsa.getPrimeQ()) + || rsa.getPrimeP().equals(rsa.getPrimeQ()) + || !positive(rsa.getPrimeExponentP()) + || !positive(rsa.getPrimeExponentQ()) + || !positive(rsa.getCrtCoefficient())) { + throw denied(); + } + BigInteger pMinusOne = rsa.getPrimeP().subtract(BigInteger.ONE); + BigInteger qMinusOne = rsa.getPrimeQ().subtract(BigInteger.ONE); + BigInteger lambda = pMinusOne.divide(pMinusOne.gcd(qMinusOne)).multiply(qMinusOne); + if (!rsa.getPrimeP().multiply(rsa.getPrimeQ()).equals(rsa.getModulus()) + || !rsa.getPrivateExponent() + .multiply(rsa.getPublicExponent()) + .mod(lambda) + .equals(BigInteger.ONE) + || !rsa.getPrivateExponent().mod(pMinusOne).equals(rsa.getPrimeExponentP()) + || !rsa.getPrivateExponent().mod(qMinusOne).equals(rsa.getPrimeExponentQ()) + || !rsa.getPrimeQ().modInverse(rsa.getPrimeP()).equals(rsa.getCrtCoefficient())) { + throw denied(); + } + return rsa; + } + + private static boolean positive(BigInteger value) { + return value != null && value.signum() > 0; + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maximumBytes) { + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (RuntimeException ex) { + throw denied(); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean canonicalEncoding = canonical.length == encoded.length(); + for (int index = 0; canonicalEncoding && index < canonical.length; index++) { + canonicalEncoding = Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + wipe(canonical); + if (decoded.length == 0 || decoded.length > maximumBytes || !canonicalEncoding) { + wipe(decoded); + throw denied(); + } + return decoded; + } + + private static void validateIdentity( + ProtectedBinding.Binding binding, String operationId, String generation, String kid) { + canonicalUuidV4(operationId); + if (generation == null + || !GENERATION.matcher(generation).matches() + || kid == null + || !KID.matcher(kid).matches() + || binding == null) { + throw denied(); + } + } + + private static String canonicalUuidV4(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || uuid.version() != 4 || uuid.variant() != 2) { + throw denied(); + } + return value; + } + + private static void requireExactObject(JsonNode node, Set fields) { + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw denied(); + } + for (Map.Entry entry : node.properties()) { + if (!fields.contains(entry.getKey())) { + throw denied(); + } + } + } + + private static String text(JsonNode node, String name, int maxLength) { + JsonNode value = node == null ? null : node.get(name); + if (value == null || !value.isTextual()) { + throw denied(); + } + String text = value.textValue(); + if (text.isEmpty() + || text.length() > maxLength + || text.chars().anyMatch(Character::isISOControl)) { + throw denied(); + } + return text; + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw denied(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw denied(); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) Arrays.fill(bytes, (byte) 0); + } + + private static IllegalArgumentException denied() { + return new IllegalArgumentException("JWT signing Secret state is malformed or unauthorized"); + } + + static final class Generated implements AutoCloseable { + private byte[] bundleBytes; + private final String publicJwkJson; + private final PublicIdentity identity; + + Generated(byte[] bundleBytes, String publicJwkJson, PublicIdentity identity) { + this.bundleBytes = bundleBytes; + this.publicJwkJson = publicJwkJson; + this.identity = identity; + } + + byte[] bundleBytes() { + if (bundleBytes == null) throw denied(); + return bundleBytes; + } + + String publicJwkJson() { + return publicJwkJson; + } + + PublicIdentity identity() { + return identity; + } + + @Override + public void close() { + wipe(bundleBytes); + bundleBytes = null; + } + } + + record PublicIdentity(String generation, String kid, String fingerprint, String operationId) {} +} diff --git a/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerBoundaryTest.java b/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerBoundaryTest.java new file mode 100644 index 0000000000..8145de58f7 --- /dev/null +++ b/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerBoundaryTest.java @@ -0,0 +1,469 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class MaterializerBoundaryTest { + private static final String CLUSTER_UID = "8e265cfe-fda2-4c54-9ab6-8fc17fb4052c"; + private static final String NAMESPACE_UID = "120b32b7-5582-4220-9906-b241e776d10b"; + private static final String ACCOUNT_SA_UID = "63be9f06-06cc-4877-9d7f-8ca63581ddbb"; + private static final String OPERATION_ID = "00000000-0000-4000-8000-000000000001"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PRIOR_RV = "42"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Test + void protectedBindingParsesExactIdentityAndAccountTrustDigest() throws Exception { + ProtectedBinding.Binding parsed = ProtectedBinding.parse(bindingJson()); + assertEquals("dev", parsed.environmentId()); + assertEquals("account", parsed.namespace()); + assertEquals( + "spiffe://firemud/ns/account/sa/account-jwt-materializer", + parsed.expectedMaterializerSpiffeUri()); + assertTrue(parsed.accountTrustBindingDigest().matches("[0-9a-f]{64}")); + } + + @Test + void protectedBindingRejectsUnknownField() throws Exception { + Map fields = bindingFields(); + fields.put("fallbackKubeconfig", "/tmp/kubeconfig"); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsDisabledConfiguration() throws Exception { + Map fields = bindingFields(); + fields.put("enabled", false); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsDifferentClusterIncarnation() throws Exception { + Map fields = bindingFields(); + fields.put("expectedKubeSystemNamespaceUid", NAMESPACE_UID); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsWrongMaterializerSpiffeIdentity() throws Exception { + Map fields = bindingFields(); + fields.put( + "expectedMaterializerSpiffeUri", "spiffe://firemud/ns/other/sa/account-jwt-materializer"); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsAccountDnsAndTargetMismatch() throws Exception { + Map fields = bindingFields(); + fields.put("accountTarget", "other.account.svc:9090"); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsHttpApiEndpoint() throws Exception { + Map fields = bindingFields(); + fields.put("kubernetesApiServerUri", "http://kubernetes.default.svc:6443"); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsApiEndpointWithPathOrQuery() throws Exception { + Map fields = bindingFields(); + fields.put("kubernetesApiServerUri", "https://kubernetes.default.svc:6443/api?discover=true"); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void protectedBindingRejectsDuplicateClientPins() throws Exception { + Map fields = bindingFields(); + fields.put("materializerSpkiSha256Pins", java.util.List.of("0".repeat(64), "0".repeat(64))); + assertThrows(IllegalArgumentException.class, () -> ProtectedBinding.parse(json(fields))); + } + + @Test + void secretParserRequiresFixedPrecreatedSecretName() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> SecretState.parse(secretJson("other-secret", "account", "Opaque", "42"), "account")); + } + + @Test + void secretParserRequiresPinnedNamespace() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> SecretState.parse(secretJson(SecretState.NAME, "other", "Opaque", "42"), "account")); + } + + @Test + void secretParserRequiresOpaqueSecret() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> + SecretState.parse( + secretJson(SecretState.NAME, "account", "kubernetes.io/tls", "42"), "account")); + } + + @Test + void secretParserRejectsMalformedResourceVersion() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> + SecretState.parse(secretJson(SecretState.NAME, "account", "Opaque", "\n"), "account")); + } + + @Test + void generationPatchIsResourceVersionUidGuardedAndTouchesOnlyPendingSlot() throws Exception { + SecretState before = secretWithUnrelatedDataAndAnnotation(); + byte[] patch = + before.generationPatch(new byte[] {1, 2, 3}, OPERATION_ID, REQUEST_DIGEST, PRIOR_RV); + JsonNode root = JSON.readTree(patch); + assertEquals(before.uid(), root.get("metadata").get("uid").textValue()); + assertEquals(PRIOR_RV, root.get("metadata").get("resourceVersion").textValue()); + assertTrue(root.get("data").has(SecretState.PENDING)); + assertEquals(1, root.get("data").size()); + assertEquals( + Set.of( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV), + fieldNames(root.get("metadata").get("annotations"))); + } + + @Test + void generationRecoveryMarkerRequiresExactAuthenticatedOperationRequestAndPriorVersion() + throws Exception { + SecretState state = secretWithGenerationMarker(OPERATION_ID, REQUEST_DIGEST, PRIOR_RV); + assertTrue( + state.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + OPERATION_ID, + REQUEST_DIGEST, + PRIOR_RV)); + assertFalse( + state.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + OPERATION_ID, + "b".repeat(64), + PRIOR_RV)); + assertFalse( + state.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + OPERATION_ID, + REQUEST_DIGEST, + "43")); + } + + @Test + void readbackRequiresUnrelatedSecretDataAndAnnotationsToRemainUnchanged() throws Exception { + SecretState before = secretWithUnrelatedDataAndAnnotation(); + SecretState exactReadback = secretWithGenerationReadback("opaque-value"); + before.requireUnchangedExcept( + Set.of(SecretState.PENDING), + Set.of( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV), + exactReadback); + SecretState alteredReadback = secretWithGenerationReadback("changed"); + assertThrows( + IllegalArgumentException.class, + () -> + before.requireUnchangedExcept( + Set.of(SecretState.PENDING), + Set.of( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV), + alteredReadback)); + } + + @Test + void promotionPatchChangesOnlyTheThreeAccountAuthorizedSlots() throws Exception { + SecretState before = secretWithUnrelatedDataAndAnnotation(); + byte[] patch = + before.promotionPatch( + new byte[] {1, 2}, new byte[] {3, 4}, OPERATION_ID, REQUEST_DIGEST, PRIOR_RV); + JsonNode root = JSON.readTree(patch); + JsonNode data = root.get("data"); + assertEquals( + Set.of(SecretState.CURRENT, SecretState.PENDING, SecretState.PREVIOUS), fieldNames(data)); + assertTrue(data.get(SecretState.PENDING).isNull()); + assertEquals(before.uid(), root.get("metadata").get("uid").textValue()); + assertEquals(PRIOR_RV, root.get("metadata").get("resourceVersion").textValue()); + assertTrue(root.get("metadata").get("annotations").has(SecretState.PROMOTION_OPERATION)); + } + + @Test + void promotionPatchRemovesPreviousWhenAccountHasNoPriorCurrentSigner() throws Exception { + SecretState before = secretWithUnrelatedDataAndAnnotation(); + JsonNode patch = + JSON.readTree( + before.promotionPatch(new byte[] {1}, null, OPERATION_ID, REQUEST_DIGEST, PRIOR_RV)); + assertTrue(patch.get("data").get(SecretState.PREVIOUS).isNull()); + } + + @Test + void signerGenerationUsesOnlyRsa3072Exponent65537AndPublicOnlyReceipt() throws Exception { + try (SignerKeyBundle.Generated generated = + SignerKeyBundle.generate(binding(), OPERATION_ID, "7", "kid_7")) { + assertEquals(64, generated.identity().fingerprint().length()); + JsonNode jwk = JSON.readTree(generated.publicJwkJson()); + assertEquals("RSA", jwk.get("kty").textValue()); + assertEquals("RS256", jwk.get("alg").textValue()); + assertEquals("kid_7", jwk.get("kid").textValue()); + assertEquals(Set.of("alg", "e", "key_ops", "kid", "kty", "n", "use"), fieldNames(jwk)); + assertFalse(jwk.has("d")); + byte[] bytes = generated.bundleBytes(); + SignerKeyBundle.PublicIdentity parsed = + SignerKeyBundle.verify( + bytes, binding(), OPERATION_ID, "7", "kid_7", generated.identity().fingerprint()); + assertEquals(generated.identity(), parsed); + JsonNode privateBundle = JSON.readTree(bytes); + byte[] privateDer = + Base64.getUrlDecoder().decode(privateBundle.get("privateKeyPkcs8").textValue()); + try { + RSAPrivateCrtKey privateKey = + (RSAPrivateCrtKey) + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + assertEquals(3_072, privateKey.getModulus().bitLength()); + assertEquals(java.math.BigInteger.valueOf(65_537), privateKey.getPublicExponent()); + } finally { + java.util.Arrays.fill(privateDer, (byte) 0); + } + } + } + + @Test + void signerBundleRejectsAnotherOperationIdentity() throws Exception { + try (SignerKeyBundle.Generated generated = + SignerKeyBundle.generate(binding(), OPERATION_ID, "8", "kid_8")) { + assertThrows( + IllegalArgumentException.class, + () -> + SignerKeyBundle.verify( + generated.bundleBytes(), + binding(), + "00000000-0000-4000-8000-000000000002", + "8", + "kid_8", + null)); + } + } + + @Test + void signerBundleRejectsPaddedNonCanonicalPrivateKeyEncoding() throws Exception { + try (SignerKeyBundle.Generated generated = + SignerKeyBundle.generate(binding(), OPERATION_ID, "9", "kid_9")) { + JsonNode root = JSON.readTree(generated.bundleBytes()); + Map fields = new LinkedHashMap<>(); + for (Map.Entry entry : root.properties()) { + fields.put( + entry.getKey(), + entry.getValue().isIntegralNumber() + ? entry.getValue().intValue() + : entry.getValue().textValue()); + } + fields.put("privateKeyPkcs8", fields.get("privateKeyPkcs8") + "="); + assertThrows( + IllegalArgumentException.class, + () -> SignerKeyBundle.verify(json(fields), binding(), OPERATION_ID, "9", "kid_9", null)); + } + } + + @Test + void generatedBundleUsesCanonicalJsonAndCanonicalUrlBase64() throws Exception { + try (SignerKeyBundle.Generated generated = + SignerKeyBundle.generate(binding(), OPERATION_ID, "10", "kid_10")) { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8( + new String(generated.bundleBytes(), StandardCharsets.UTF_8)); + assertTrue(java.util.Arrays.equals(canonical, generated.bundleBytes())); + JsonNode root = JSON.readTree(generated.bundleBytes()); + String encoded = root.get("privateKeyPkcs8").textValue(); + assertFalse(encoded.contains("=")); + assertTrue(Base64.getUrlDecoder().decode(encoded).length > 0); + } + } + + @Test + void secretStateDoesNotExposeDataInToString() throws Exception { + SecretState state = secretWithUnrelatedDataAndAnnotation(); + assertFalse(state.toString().contains("private")); + assertFalse(state.toString().contains("opaque-value")); + } + + private static byte[] bindingJson() throws Exception { + return json(bindingFields()); + } + + private static Map bindingFields() { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", 1); + fields.put("enabled", true); + fields.put("configRevision", "rev-1"); + fields.put("environmentId", "dev"); + fields.put("clusterId", "local-cluster"); + fields.put("namespace", "account"); + fields.put("expectedClusterIncarnationUid", CLUSTER_UID); + fields.put("expectedNamespaceUid", NAMESPACE_UID); + fields.put("expectedKubeSystemNamespaceUid", CLUSTER_UID); + fields.put("expectedServiceAccountName", "account-jwt-materializer"); + fields.put("expectedServiceAccountUid", ACCOUNT_SA_UID); + fields.put( + "expectedMaterializerSpiffeUri", "spiffe://firemud/ns/account/sa/account-jwt-materializer"); + fields.put("materializerSpkiSha256", "0".repeat(64)); + fields.put("materializerSpkiSha256Pins", java.util.List.of("0".repeat(64))); + fields.put("accountTarget", "account.account.svc:9090"); + fields.put("accountServerDnsName", "account.account.svc"); + fields.put("expectedAccountSpiffeUri", "spiffe://firemud/ns/account/sa/account-service"); + fields.put("accountServerSpkiSha256Pins", java.util.List.of("1".repeat(64))); + fields.put("accountCaPath", "/etc/firemud/account-jwt-materializer/account-ca.pem"); + fields.put("clientCertificatePath", "/etc/firemud/account-jwt-materializer/client.pem"); + fields.put("clientPrivateKeyPath", "/etc/firemud/account-jwt-materializer/client-key.pem"); + fields.put("kubernetesApiServerUri", "https://kubernetes.default.svc:6443"); + fields.put("kubernetesApiCaPath", "/etc/firemud/account-jwt-materializer/kubernetes-ca.pem"); + fields.put("kubernetesTokenPath", "/etc/firemud/account-jwt-materializer/token.jwt"); + return fields; + } + + static ProtectedBinding.Binding binding() { + return ProtectedBinding.parse(bindingUnchecked()); + } + + private static byte[] bindingUnchecked() { + try { + return bindingJson(); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static byte[] secretJson(String name, String namespace, String type, String rv) + throws Exception { + Map metadata = new LinkedHashMap<>(); + metadata.put("name", name); + metadata.put("namespace", namespace); + metadata.put("uid", "d1d5a1cb-31f7-4b87-a542-00cbd52fba92"); + metadata.put("resourceVersion", rv); + Map secret = new LinkedHashMap<>(); + secret.put("apiVersion", "v1"); + secret.put("kind", "Secret"); + secret.put("metadata", metadata); + secret.put("type", type); + secret.put("data", Map.of()); + return json(secret); + } + + private static SecretState secretWithUnrelatedDataAndAnnotation() throws Exception { + Map metadata = new LinkedHashMap<>(); + metadata.put("name", SecretState.NAME); + metadata.put("namespace", "account"); + metadata.put("uid", "d1d5a1cb-31f7-4b87-a542-00cbd52fba92"); + metadata.put("resourceVersion", PRIOR_RV); + metadata.put("annotations", Map.of("operator.example/keep", "retained")); + Map secret = new LinkedHashMap<>(); + secret.put("apiVersion", "v1"); + secret.put("kind", "Secret"); + secret.put("metadata", metadata); + secret.put("type", "Opaque"); + secret.put( + "data", + Map.of( + "unrelated", + Base64.getEncoder().encodeToString("opaque-value".getBytes(StandardCharsets.UTF_8)))); + return SecretState.parse(json(secret), "account"); + } + + private static SecretState secretWithGenerationMarker(String operation, String digest, String rv) + throws Exception { + Map metadata = new LinkedHashMap<>(); + metadata.put("name", SecretState.NAME); + metadata.put("namespace", "account"); + metadata.put("uid", "d1d5a1cb-31f7-4b87-a542-00cbd52fba92"); + metadata.put("resourceVersion", "43"); + metadata.put( + "annotations", + Map.of( + SecretState.GENERATION_OPERATION, operation, + SecretState.GENERATION_REQUEST, digest, + SecretState.GENERATION_PRIOR_RV, rv)); + Map secret = new LinkedHashMap<>(); + secret.put("apiVersion", "v1"); + secret.put("kind", "Secret"); + secret.put("metadata", metadata); + secret.put("type", "Opaque"); + secret.put("data", Map.of()); + return SecretState.parse(json(secret), "account"); + } + + private static SecretState secretWithGenerationReadback(String unrelatedValue) throws Exception { + Map metadata = new LinkedHashMap<>(); + metadata.put("name", SecretState.NAME); + metadata.put("namespace", "account"); + metadata.put("uid", "d1d5a1cb-31f7-4b87-a542-00cbd52fba92"); + metadata.put("resourceVersion", "43"); + metadata.put( + "annotations", + Map.of( + "operator.example/keep", + "retained", + SecretState.GENERATION_OPERATION, + OPERATION_ID, + SecretState.GENERATION_REQUEST, + REQUEST_DIGEST, + SecretState.GENERATION_PRIOR_RV, + PRIOR_RV)); + Map secret = new LinkedHashMap<>(); + secret.put("apiVersion", "v1"); + secret.put("kind", "Secret"); + secret.put("metadata", metadata); + secret.put("type", "Opaque"); + secret.put( + "data", + Map.of( + "unrelated", + Base64.getEncoder().encodeToString(unrelatedValue.getBytes(StandardCharsets.UTF_8)), + SecretState.PENDING, + Base64.getEncoder().encodeToString(new byte[] {1, 2, 3}))); + return SecretState.parse(json(secret), "account"); + } + + private static Set fieldNames(JsonNode object) { + Set names = new java.util.LinkedHashSet<>(); + for (Map.Entry entry : object.properties()) { + names.add(entry.getKey()); + } + return Set.copyOf(names); + } + + private static byte[] json(Object value) throws Exception { + return JSON.writeValueAsString(value).getBytes(StandardCharsets.UTF_8); + } +} diff --git a/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerFlowTest.java b/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerFlowTest.java new file mode 100644 index 0000000000..faf58ba367 --- /dev/null +++ b/k8s/account-jwt-materializer/src/test/java/net/firedevops/firemud/accountjwtmaterializer/MaterializerFlowTest.java @@ -0,0 +1,738 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class MaterializerFlowTest { + private static final String SECRET_UID = "d1d5a1cb-31f7-4b87-a542-00cbd52fba92"; + private static final String OPERATION_ID = "00000000-0000-4000-8000-000000000001"; + private static final String PROMOTION_ID = "00000000-0000-4000-8000-000000000002"; + private static final String OPERATION_DIGEST = "a".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "b".repeat(64); + private static final String GENERATION_RECEIPT_DIGEST = "c".repeat(64); + private static final String PROMOTION_DIGEST = "d".repeat(64); + private static final String PRIOR_RV = "42"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Test + void ambiguousGenerationPatchRecoversExactStoredKeyAndReportsOnlyItsPublicJwk() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + secret.throwAfterApply = true; + MemoryAccount account = new MemoryAccount(snapshot.binding()); + + Materializer.Outcome outcome = new Materializer(snapshot, account, secret).reconcileOnce(); + + assertEquals(Materializer.Outcome.GENERATION_RECORDED, outcome); + assertEquals(1, secret.patchCount); + assertEquals(1, account.observationCount); + assertEquals(1, account.generationResultCount); + assertEquals(1, account.enrollmentCount); + assertEquals(1, account.generationRequestCount); + assertEquals(2, account.promotionNotFoundCount); + assertEquals(List.of("enroll", "promotion", "generation", "promotion"), account.events); + assertTrue(account.publicJwk.contains("\"kty\":\"RSA\"")); + assertFalse(account.publicJwk.contains("\"d\"")); + assertFalse(outcome.publicName().contains("privateKey")); + SecretState readback = secret.read(); + assertTrue(readback.containsSlot(SecretState.PENDING)); + assertTrue( + readback.operationMarkerMatches( + SecretState.GENERATION_OPERATION, + SecretState.GENERATION_REQUEST, + SecretState.GENERATION_PRIOR_RV, + OPERATION_ID, + GENERATION_REQUEST_DIGEST, + PRIOR_RV)); + } + + @Test + void observationOnlyRecordsTheExactEmptySecretAndStopsBeforeGenerationOrPromotion() { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + + Materializer.Outcome outcome = new Materializer(snapshot, account, secret).observeSecretOnce(); + + assertEquals(Materializer.Outcome.SECRET_OBSERVATION_RECORDED, outcome); + assertEquals("secret_observation_recorded", outcome.publicName()); + assertEquals(1, account.enrollmentCount); + assertEquals(1, account.promotionNotFoundCount); + assertEquals(1, account.generationRequestCount); + assertEquals(1, account.observationCount); + assertEquals(0, account.generationResultCount); + assertEquals(0, account.promotionReceiptCount); + assertEquals(0, secret.patchCount); + assertEquals(PRIOR_RV, secret.read().resourceVersion()); + assertTrue(secret.read().signerSlots().isEmpty()); + } + + @Test + void substitutedObservationResponseDeniesBothModesBeforePatchOrResult() { + ProtectedBinding.Snapshot snapshot = snapshot(); + var valid = generationRequest(snapshot.binding(), true); + var substitutions = + List.of( + valid.toBuilder().setOperationId(PROMOTION_ID).build(), + valid.toBuilder().setOperationDigest("e".repeat(64)).build(), + valid.toBuilder().setSecretUid("d1d5a1cb-31f7-4b87-a542-00cbd52fba93").build(), + valid.toBuilder().setExpectedSecretResourceVersion("43").build()); + for (var response : substitutions) { + for (boolean observeOnly : List.of(false, true)) { + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.observationResponse = response; + Materializer materializer = new Materializer(snapshot, account, secret); + assertThrows( + IllegalStateException.class, + () -> { + if (observeOnly) materializer.observeSecretOnce(); + else materializer.reconcileOnce(); + }); + assertEquals(1, account.observationCount); + assertEquals(0, secret.patchCount); + assertEquals(0, account.generationResultCount); + assertEquals(0, account.promotionReceiptCount); + assertEquals(PRIOR_RV, secret.read().resourceVersion()); + assertTrue(secret.read().signerSlots().isEmpty()); + } + } + } + + @Test + void observationOnlyRejectsExistingOrMixedSignerMaterialBeforeRecording() { + ProtectedBinding.Snapshot snapshot = snapshot(); + List> nonemptyData = + List.of( + Map.of(SecretState.CURRENT, Base64.getEncoder().encodeToString(new byte[] {1})), + Map.of(SecretState.PENDING, Base64.getEncoder().encodeToString(new byte[] {1})), + Map.of( + SecretState.CURRENT, + Base64.getEncoder().encodeToString(new byte[] {1}), + SecretState.PENDING, + Base64.getEncoder().encodeToString(new byte[] {2}))); + + for (Map data : nonemptyData) { + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, data, Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).observeSecretOnce()); + + assertEquals(0, account.observationCount); + assertEquals(0, account.generationResultCount); + assertEquals(0, secret.patchCount); + assertEquals(PRIOR_RV, secret.read().resourceVersion()); + } + } + + @Test + void enrollmentAcknowledgmentMismatchDeniesBeforeAnySecretMutationOrGenerationRead() { + ProtectedBinding.Snapshot snapshot = snapshot(); + EnrollBootstrapResponse valid = enrollmentResponse(snapshot.binding()); + List mismatches = + List.of( + valid.toBuilder().setEnvironmentId("other-env").build(), + valid.toBuilder().setClusterId("other-cluster").build(), + valid.toBuilder().setNamespace("other-namespace").build(), + valid.toBuilder().setExpectedClusterIncarnationUid("other-cluster-uid").build(), + valid.toBuilder().setExpectedNamespaceUid("other-namespace-uid").build(), + valid.toBuilder().setMaterializerTrustBindingDigest("d".repeat(64)).build(), + valid.toBuilder().setMaterializerTrustConfigRevision("other-revision").build()); + + for (EnrollBootstrapResponse acknowledgement : mismatches) { + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.enrollmentResponse = acknowledgement; + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(1, account.enrollmentCount); + assertEquals(0, account.generationRequestCount); + assertEquals(List.of("enroll"), account.events); + assertEquals(0, secret.patchCount); + } + } + + @Test + void enrollmentAcknowledgmentRejectsNoncanonicalAndNilConfigMapUids() { + ProtectedBinding.Snapshot snapshot = snapshot(); + for (String uid : + List.of("33333333-3333-4333-8333-33333333333A", "00000000-0000-0000-0000-000000000000")) { + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.enrollmentResponse = + account.enrollmentResponse.toBuilder().setPublicConfigMapUid(uid).build(); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(1, account.enrollmentCount); + assertEquals(0, account.generationRequestCount); + assertEquals(List.of("enroll"), account.events); + assertEquals(0, secret.patchCount); + } + } + + @Test + void generationConflictIsDeniedWithoutPatchRetryOrAccountReceipt() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + secret.rejectPatch = true; + MemoryAccount account = new MemoryAccount(snapshot.binding()); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(1, secret.patchCount); + assertEquals(0, account.generationResultCount); + assertEquals(PRIOR_RV, secret.read().resourceVersion()); + } + + @Test + void generationRejectsExistingPendingMaterialWithoutOverwritingIt() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + Map data = + Map.of(SecretState.PENDING, Base64.getEncoder().encodeToString(new byte[] {1, 2, 3})); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, data, Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(0, secret.patchCount); + assertEquals(0, account.generationResultCount); + } + + @Test + void generationRejectsRequestTrustMismatchBeforeSecretWrite() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.generationRequest = + generationRequest(snapshot.binding(), false).toBuilder() + .setTrustBindingDigest("e".repeat(64)) + .build(); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(0, secret.patchCount); + assertEquals(0, account.observationCount); + } + + @Test + void generationRejectsStaleAccountResourceVersionWithoutWriting() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.observationResourceVersion = "41"; + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(0, secret.patchCount); + assertEquals(0, account.generationResultCount); + } + + @Test + void generationRejectsMalformedAllowedSlotsAndNeverInventsAnAccountReceipt() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, Map.of(), Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.generationRequest = + generationRequest(snapshot.binding(), false).toBuilder() + .clearAllowedPrivateSlots() + .addAllowedPrivateSlots("current") + .build(); + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(0, secret.patchCount); + assertEquals(0, account.generationResultCount); + } + + @Test + void promotionMovesOnlyAuthorizedPrivateSlotsAndReportsAccountSlotNames() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + try (SignerKeyBundle.Generated target = + SignerKeyBundle.generate(snapshot.binding(), OPERATION_ID, "7", "kid_7")) { + Map data = + Map.of(SecretState.PENDING, Base64.getEncoder().encodeToString(target.bundleBytes())); + MemorySecretApi secret = new MemorySecretApi(secret(PRIOR_RV, data, Map.of("keep", "yes"))); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.promotionRequest = promotionRequest(snapshot.binding(), target.identity()); + + Materializer.Outcome outcome = new Materializer(snapshot, account, secret).reconcileOnce(); + + assertEquals(Materializer.Outcome.PRIVATE_PROMOTION_RECEIPT_RECORDED, outcome); + assertEquals(1, secret.patchCount); + assertEquals(List.of("current"), account.resultingSlots); + assertEquals(1, account.promotionReceiptCount); + assertEquals(1, account.enrollmentCount); + assertEquals(0, account.generationRequestCount); + assertEquals(List.of("enroll", "promotion"), account.events); + SecretState readback = secret.read(); + assertTrue(readback.containsSlot(SecretState.CURRENT)); + assertFalse(readback.containsSlot(SecretState.PENDING)); + assertFalse(readback.containsSlot(SecretState.PREVIOUS)); + assertEquals("yes", readback.annotation("keep")); + } + } + + @Test + void ambiguousPromotionPatchRecoversExactTransitionWithoutRepeatingPatch() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + try (SignerKeyBundle.Generated target = + SignerKeyBundle.generate(snapshot.binding(), OPERATION_ID, "7", "kid_7")) { + MemorySecretApi secret = + new MemorySecretApi( + secret( + PRIOR_RV, + Map.of( + SecretState.PENDING, + Base64.getEncoder().encodeToString(target.bundleBytes())), + Map.of())); + secret.throwAfterApply = true; + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.promotionRequest = promotionRequest(snapshot.binding(), target.identity()); + + Materializer.Outcome outcome = new Materializer(snapshot, account, secret).reconcileOnce(); + + assertEquals(Materializer.Outcome.PRIVATE_PROMOTION_RECEIPT_RECORDED, outcome); + assertEquals(1, secret.patchCount); + assertEquals(1, account.promotionReceiptCount); + assertEquals(List.of("current"), account.resultingSlots); + } + } + + @Test + void promotionReceiptRetryUsesStoredTransitionWithoutAnotherPatch() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + try (SignerKeyBundle.Generated target = + SignerKeyBundle.generate(snapshot.binding(), OPERATION_ID, "7", "kid_7")) { + MemorySecretApi secret = + new MemorySecretApi( + secret( + PRIOR_RV, + Map.of( + SecretState.PENDING, + Base64.getEncoder().encodeToString(target.bundleBytes())), + Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.promotionRequest = promotionRequest(snapshot.binding(), target.identity()); + account.failFirstPromotionReceipt = true; + + assertThrows( + IllegalStateException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + Materializer.Outcome retry = new Materializer(snapshot, account, secret).reconcileOnce(); + + assertEquals(Materializer.Outcome.PRIVATE_PROMOTION_RECEIPT_RECORDED, retry); + assertEquals(1, secret.patchCount); + assertEquals(2, account.promotionReceiptCount); + assertEquals(0, account.generationRequestCount); + assertEquals(List.of("enroll", "promotion", "enroll", "promotion"), account.events); + } + } + + @Test + void promotionRejectsTargetMismatchWithoutPrivateSlotMutation() throws Exception { + ProtectedBinding.Snapshot snapshot = snapshot(); + try (SignerKeyBundle.Generated target = + SignerKeyBundle.generate(snapshot.binding(), OPERATION_ID, "7", "kid_7")) { + MemorySecretApi secret = + new MemorySecretApi( + secret( + PRIOR_RV, + Map.of( + SecretState.PENDING, + Base64.getEncoder().encodeToString(target.bundleBytes())), + Map.of())); + MemoryAccount account = new MemoryAccount(snapshot.binding()); + account.promotionRequest = + promotionRequest(snapshot.binding(), target.identity()).toBuilder() + .setTargetKid("kid_other") + .build(); + + assertThrows( + IllegalArgumentException.class, + () -> new Materializer(snapshot, account, secret).reconcileOnce()); + + assertEquals(0, secret.patchCount); + assertTrue(secret.read().containsSlot(SecretState.PENDING)); + } + } + + private static ProtectedBinding.Snapshot snapshot() { + return new ProtectedBinding.Snapshot(MaterializerBoundaryTest.binding(), "test-snapshot"); + } + + private static Map secret( + String resourceVersion, Map data, Map annotations) { + Map metadata = new LinkedHashMap<>(); + metadata.put("name", SecretState.NAME); + metadata.put("namespace", "account"); + metadata.put("uid", SECRET_UID); + metadata.put("resourceVersion", resourceVersion); + metadata.put("annotations", new LinkedHashMap<>(annotations)); + Map secret = new LinkedHashMap<>(); + secret.put("apiVersion", "v1"); + secret.put("kind", "Secret"); + secret.put("metadata", metadata); + secret.put("type", "Opaque"); + secret.put("data", new LinkedHashMap<>(data)); + return secret; + } + + private static GetCurrentGenerationRequestResponse generationRequest( + ProtectedBinding.Binding binding, boolean observed) { + var builder = + GetCurrentGenerationRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPhase( + observed + ? GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING + : GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET) + .setOperationId(OPERATION_ID) + .setOperationDigest(OPERATION_DIGEST) + .setDesiredStateVersion("2") + .setEnvironmentId(binding.environmentId()) + .setClusterId(binding.clusterId()) + .setNamespace(binding.namespace()) + .setExpectedClusterIncarnationUid(binding.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(binding.expectedNamespaceUid()) + .setTrustBindingDigest(binding.accountTrustBindingDigest()) + .setTrustConfigRevision(binding.configRevision()) + .setPrivateSecretName(SecretState.NAME) + .setTargetGeneration("7") + .setTargetKid("kid_7") + .setTargetAlgorithm("RS256") + .setOperationAction("MATERIALIZE_PENDING") + .addAllowedPrivateSlots("pending"); + if (observed) { + builder + .setGenerationRequestDigest(GENERATION_REQUEST_DIGEST) + .setSecretUid(SECRET_UID) + .setExpectedSecretResourceVersion(PRIOR_RV); + } + return builder.build(); + } + + private static GetCurrentPromotionRequestResponse promotionRequest( + ProtectedBinding.Binding binding, SignerKeyBundle.PublicIdentity target) { + return GetCurrentPromotionRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(PROMOTION_ID) + .setPromotionRequestDigest(PROMOTION_DIGEST) + .setGenerationOperationId(target.operationId()) + .setGenerationOperationDigest(OPERATION_DIGEST) + .setGenerationReceiptDigest(GENERATION_RECEIPT_DIGEST) + .setEnvironmentId(binding.environmentId()) + .setClusterId(binding.clusterId()) + .setNamespace(binding.namespace()) + .setExpectedClusterIncarnationUid(binding.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(binding.expectedNamespaceUid()) + .setTrustBindingDigest(binding.accountTrustBindingDigest()) + .setTrustConfigRevision(binding.configRevision()) + .setPrivateSecretName(SecretState.NAME) + .setTargetGeneration(target.generation()) + .setTargetKid(target.kid()) + .setTargetAlgorithm("RS256") + .setTargetPublicKeyFingerprint(target.fingerprint()) + .setExpectedSecretUid(SECRET_UID) + .setExpectedSecretResourceVersion(PRIOR_RV) + .setOperationAction("PROMOTE_PENDING") + .addAllowedPrivateSlots(SecretState.CURRENT) + .addAllowedPrivateSlots(SecretState.PENDING) + .addAllowedPrivateSlots(SecretState.PREVIOUS) + .build(); + } + + private static String thumbprint(String jwkJson) throws Exception { + JsonNode jwk = JSON.readTree(jwkJson); + Map thumbprint = new LinkedHashMap<>(); + thumbprint.put("e", jwk.get("e").textValue()); + thumbprint.put("kty", "RSA"); + thumbprint.put("n", jwk.get("n").textValue()); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(thumbprint)); + try { + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } finally { + java.util.Arrays.fill(canonical, (byte) 0); + } + } + + private static byte[] json(Object value) { + try { + return JSON.writeValueAsString(value).getBytes(StandardCharsets.UTF_8); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static final class MemorySecretApi implements Materializer.KubernetesOperations { + private final Map resource; + private int patchCount; + private boolean throwAfterApply; + private boolean rejectPatch; + + MemorySecretApi(Map resource) { + this.resource = resource; + } + + @Override + public void verifyClusterIdentity() {} + + @Override + public SecretState getFixedSecret() { + return read(); + } + + SecretState read() { + return SecretState.parse(json(resource), "account"); + } + + @Override + @SuppressWarnings("unchecked") + public void patchFixedSecret(SecretState before, byte[] mergePatch) { + patchCount++; + try { + if (rejectPatch) { + throw new IllegalStateException("simulated resourceVersion conflict"); + } + JsonNode patch; + try { + patch = JSON.readTree(mergePatch); + } catch (RuntimeException ex) { + throw new IllegalStateException("simulated malformed patch"); + } + JsonNode metadataPatch = patch.get("metadata"); + if (!before.uid().equals(metadataPatch.get("uid").textValue()) + || !before.resourceVersion().equals(metadataPatch.get("resourceVersion").textValue())) { + throw new IllegalStateException("simulated stale Secret precondition"); + } + Map metadata = (Map) resource.get("metadata"); + Map annotations = (Map) metadata.get("annotations"); + if (annotations == null) { + annotations = new LinkedHashMap<>(); + metadata.put("annotations", annotations); + } + JsonNode annotationPatch = metadataPatch.get("annotations"); + for (Map.Entry entry : annotationPatch.properties()) { + annotations.put(entry.getKey(), entry.getValue().textValue()); + } + Map data = (Map) resource.get("data"); + for (Map.Entry entry : patch.get("data").properties()) { + if (entry.getValue().isNull()) { + data.remove(entry.getKey()); + } else { + data.put(entry.getKey(), entry.getValue().textValue()); + } + } + int next = Integer.parseInt(before.resourceVersion()) + 1; + metadata.put("resourceVersion", Integer.toString(next)); + if (throwAfterApply) { + throw new IllegalStateException("simulated lost patch response"); + } + } finally { + java.util.Arrays.fill(mergePatch, (byte) 0); + } + } + } + + private static final class MemoryAccount implements Materializer.AccountOperations { + private final ProtectedBinding.Binding binding; + private EnrollBootstrapResponse enrollmentResponse; + private GetCurrentGenerationRequestResponse generationRequest; + private GetCurrentPromotionRequestResponse promotionRequest; + private String observationResourceVersion = PRIOR_RV; + private GetCurrentGenerationRequestResponse observationResponse; + private String publicJwk; + private int observationCount; + private int generationResultCount; + private int enrollmentCount; + private int generationRequestCount; + private int promotionNotFoundCount; + private int promotionReceiptCount; + private boolean failFirstPromotionReceipt; + private List resultingSlots = List.of(); + private final List events = new java.util.ArrayList<>(); + + MemoryAccount(ProtectedBinding.Binding binding) { + this.binding = binding; + this.enrollmentResponse = enrollmentResponse(binding); + this.generationRequest = generationRequest(binding, false); + } + + @Override + public EnrollBootstrapResponse enrollBootstrap() { + enrollmentCount++; + events.add("enroll"); + return enrollmentResponse; + } + + @Override + public GetCurrentGenerationRequestResponse getCurrentGenerationRequest() { + generationRequestCount++; + events.add("generation"); + if (generationRequest == null) { + throw new StatusRuntimeException(Status.FAILED_PRECONDITION); + } + return generationRequest; + } + + @Override + public GetCurrentGenerationRequestResponse recordSecretObservation( + String operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + observationCount++; + if (!OPERATION_ID.equals(operationId) + || !OPERATION_DIGEST.equals(operationDigest) + || !SECRET_UID.equals(secretUid)) { + throw new IllegalStateException("simulated Account observation mismatch"); + } + if (observationResponse != null) return observationResponse; + return generationRequest(binding, true).toBuilder() + .setExpectedSecretResourceVersion(observationResourceVersion) + .build(); + } + + @Override + public RecordGenerationResultResponse recordGenerationResult( + String operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + generationResultCount++; + this.publicJwk = publicJwkJson; + try { + return RecordGenerationResultResponse.newBuilder() + .setSchemaVersion(1) + .setOperationId(operationId) + .setOperationDigest(OPERATION_DIGEST) + .setGenerationRequestDigest(generationRequestDigest) + .setGenerationReceiptDigest(GENERATION_RECEIPT_DIGEST) + .setDesiredStateVersion("3") + .setEnvironmentId(binding.environmentId()) + .setClusterId(binding.clusterId()) + .setNamespace(binding.namespace()) + .setExpectedClusterIncarnationUid(binding.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(binding.expectedNamespaceUid()) + .setTrustBindingDigest(binding.accountTrustBindingDigest()) + .setTrustConfigRevision(binding.configRevision()) + .setPrivateSecretName(SecretState.NAME) + .setSecretUid(secretUid) + .setExpectedPriorResourceVersion(expectedPriorResourceVersion) + .setObservedResourceVersion(observedResourceVersion) + .setTargetGeneration("7") + .setTargetKid("kid_7") + .setTargetAlgorithm("RS256") + .setPublicKeyFingerprint(thumbprint(publicJwkJson)) + .setPublicJwkJson(publicJwkJson) + .build(); + } catch (Exception ex) { + throw new IllegalStateException("simulated Account generation receipt error"); + } + } + + @Override + public GetCurrentPromotionRequestResponse getCurrentPromotionRequest() { + events.add("promotion"); + if (promotionRequest == null) { + promotionNotFoundCount++; + throw new StatusRuntimeException( + Status.NOT_FOUND.withDescription("No Account-authorized signer promotion is pending")); + } + return promotionRequest; + } + + @Override + public RecordPrivatePromotionResultResponse recordPrivatePromotionResult( + GetCurrentPromotionRequestResponse request, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + SignerKeyBundle.PublicIdentity current, + SignerKeyBundle.PublicIdentity previous, + List resultingSlots) { + promotionReceiptCount++; + this.resultingSlots = List.copyOf(resultingSlots); + if (failFirstPromotionReceipt && promotionReceiptCount == 1) { + throw new IllegalStateException("simulated lost Account receipt response"); + } + return RecordPrivatePromotionResultResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(request.getPromotionOperationId()) + .setGenerationOperationId(request.getGenerationOperationId()) + .setObservedResourceVersion(observedResourceVersion) + .setPublicReceiptDigest("f".repeat(64)) + .build(); + } + } + + private static EnrollBootstrapResponse enrollmentResponse(ProtectedBinding.Binding binding) { + return EnrollBootstrapResponse.newBuilder() + .setSchemaVersion(1) + .setEnvironmentId(binding.environmentId()) + .setClusterId(binding.clusterId()) + .setNamespace(binding.namespace()) + .setExpectedClusterIncarnationUid(binding.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(binding.expectedNamespaceUid()) + .setMaterializerTrustBindingDigest(binding.accountTrustBindingDigest()) + .setMaterializerTrustConfigRevision(binding.configRevision()) + .setApiBindingDigest("a".repeat(64)) + .setApiConfigRevision("api-revision-1") + .setApiServerUrl("https://kubernetes.default.svc:6443") + .setApiTlsServerName("kubernetes.default.svc") + .setApiServingCaSha256("b".repeat(64)) + .setApiExpectedUsername("system:serviceaccount:" + binding.namespace() + ":account-service") + .setPrivateSecretName(SecretState.NAME) + .setPublicConfigMapName("jwt-jwks") + .setPublicConfigMapUid("33333333-3333-4333-8333-333333333333") + .setPublicConfigMapResourceVersion("41") + .setPublicConfigMapSnapshotDigest("c".repeat(64)) + .build(); + } +} diff --git a/k8s/helm/firemud/templates/frontend.yaml b/k8s/helm/firemud/templates/frontend.yaml new file mode 100644 index 0000000000..4a02d32014 --- /dev/null +++ b/k8s/helm/firemud/templates/frontend.yaml @@ -0,0 +1,124 @@ +{{- $frontend := .Values.previewStack.frontend | default dict }} +{{- if and .Values.previewStack.enabled ($frontend.enabled | default false) }} +{{- $frontendImage := $frontend.image | default dict }} +{{- $imageRepository := required "previewStack.frontend.image.repository is required when the frontend is enabled" (get $frontendImage "repository" | default "") }} +{{- $imageTag := required "previewStack.frontend.image.tag or previewStack.defaultImageTag is required when the frontend is enabled" (default $.Values.previewStack.defaultImageTag (get $frontendImage "tag")) }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: frontend + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + replicas: {{ default 1 $frontend.replicaCount }} + selector: + matchLabels: + app: frontend + template: + metadata: + labels: + app: frontend + spec: + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 101 + runAsGroup: 101 + fsGroup: 101 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + {{- with $.Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: frontend + image: "{{ $imageRepository }}:{{ $imageTag }}" + imagePullPolicy: Always + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 101 + runAsGroup: 101 + capabilities: + drop: + - ALL + ports: + - name: http + containerPort: 8080 + protocol: TCP + readinessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 2 + periodSeconds: 10 + livenessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 5 + periodSeconds: 20 + resources: +{{ toYaml $frontend.resources | indent 12 }} + volumeMounts: + - name: nginx-tmp + mountPath: /tmp + volumes: + - name: nginx-tmp + emptyDir: + sizeLimit: 16Mi +--- +apiVersion: v1 +kind: Service +metadata: + name: frontend + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + type: ClusterIP + selector: + app: frontend + ports: + - name: http + port: 80 + targetPort: http + protocol: TCP +{{- if .Values.previewStack.networkPolicies.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: frontend-static-host + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: frontend + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 8080 + egress: [] +{{- end }} +{{- end }} diff --git a/k8s/helm/firemud/templates/ingress.yaml b/k8s/helm/firemud/templates/ingress.yaml index 5e96c81f61..4496ee99a2 100644 --- a/k8s/helm/firemud/templates/ingress.yaml +++ b/k8s/helm/firemud/templates/ingress.yaml @@ -1,3 +1,5 @@ +{{- $frontend := .Values.previewStack.frontend | default dict }} +{{- $frontendEnabled := $frontend.enabled | default false }} {{- if and .Values.previewStack.enabled .Values.previewStack.ingress.enabled }} {{- $hostedControllerMode := include "firemud.hostedControllerMode" . | trim }} apiVersion: networking.k8s.io/v1 @@ -6,9 +8,14 @@ metadata: name: firemud-preview labels: {{ include "firemud.commonLabels" . | indent 4 }} - {{- if ne $hostedControllerMode "true" }} + {{- if or (ne $hostedControllerMode "true") $frontendEnabled }} annotations: + {{- if ne $hostedControllerMode "true" }} cert-manager.io/cluster-issuer: {{ .Values.previewStack.ingress.clusterIssuer | quote }} + {{- end }} + {{- if $frontendEnabled }} + traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-firemud-preview-auth-path-rewrite@kubernetescrd" .Release.Namespace | quote }} + {{- end }} {{- end }} spec: ingressClassName: {{ .Values.previewStack.ingress.className | quote }} @@ -20,6 +27,43 @@ spec: - host: {{ .Values.preview.hostname | quote }} http: paths: + {{- if $frontendEnabled }} + - path: /frontend-assets + pathType: Prefix + backend: + service: + name: frontend + port: + number: 80 + - path: /auth + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: /api + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: /ws/game + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: / + pathType: Prefix + backend: + service: + name: frontend + port: + number: 80 + {{- else }} - path: / pathType: Prefix backend: @@ -27,4 +71,18 @@ spec: name: spring-cloud-gateway port: number: 80 + {{- end }} +{{- end }} +{{- if and .Values.previewStack.enabled .Values.previewStack.ingress.enabled $frontendEnabled }} +--- +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: firemud-preview-auth-path-rewrite + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + replacePathRegex: + regex: ^/auth(/.*)?$ + replacement: /api/account/auth$1 {{- end }} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 880ddb6e8b..f1e838a333 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -14,3 +14,17 @@ previewStack: clusterIssuer: firemud-ca-issuer # Hosted preview and dev-demo values must select their canonical trust environment explicitly. trustEnvironment: pr-preview + # Keep the static host and its public routes disabled until its image is + # published and the hosted preview values select that immutable release. + frontend: + enabled: false + image: + repository: "" + tag: "" + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 250m + memory: 128Mi diff --git a/protos/account/v1/account_issuer_authority_source.proto b/protos/account/v1/account_issuer_authority_source.proto new file mode 100644 index 0000000000..fac22669e0 --- /dev/null +++ b/protos/account/v1/account_issuer_authority_source.proto @@ -0,0 +1,57 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Source-only, unregistered owner read. The receiving Account service authenticates the exact +// same-namespace Game Session mTLS peer before opening its issuer-source snapshot. +service AccountIssuerAuthoritySourceService { + rpc ReadCurrentIssuerAuthoritySource(ReadCurrentIssuerAuthoritySourceRequest) + returns (AccountIssuerAuthoritySourceSnapshot); + rpc ReadExactIssuerAuthorityEvent(ReadExactIssuerAuthorityEventRequest) + returns (ExactIssuerAuthorityEventReadback); +} + +message ReadCurrentIssuerAuthoritySourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string reconciliation_operation_id = 3; + string issuer_id = 4; + optional AccountIssuerAuthoritySourceSnapshot expected_source = 5; +} + +// Closed issuer source carrier. Decimal counters remain strings to preserve exact precision. +// Sequence zero is the original enrollment checkpoint and has no source_event. Positive +// sequences carry the unchanged canonical issuer variant of the Account authority source event. +message AccountIssuerAuthoritySourceSnapshot { + uint32 schema_version = 1; + string target_namespace = 2; + string caller_workload = 3; + string reconciliation_operation_id = 4; + string issuer_id = 5; + string issuer_auth_generation = 6; + string source_version = 7; + string outbox_stream_key = 8; + string last_committed_outbox_sequence = 9; + optional bytes source_event = 10; +} + +// Selects one immutable retained event at an exact positive issuer stream position. +message ReadExactIssuerAuthorityEventRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string reconciliation_operation_id = 3; + string issuer_id = 4; + string outbox_sequence = 5; + string expected_event_id = 6; + string expected_event_digest = 7; +} + +// The current snapshot and the selected canonical issuer event come from one owner transaction. +message ExactIssuerAuthorityEventReadback { + uint32 schema_version = 1; + AccountIssuerAuthoritySourceSnapshot current_snapshot = 2; + bytes selected_event = 3; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 6829e91311..1fb2af27d9 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -108,6 +108,7 @@ dependencies { integrationTestImplementation(libs.spring.boot.starter.webflux) integrationTestImplementation(libs.spring.boot.starter.data.redis.reactive) integrationTestImplementation(testFixtures(project(":account-service"))) + integrationTestImplementation(project(":account-jwt-materializer")) integrationTestImplementation(testFixtures(project(":logging-admin-service"))) } @@ -228,11 +229,13 @@ val accountOriginalOrderProofJar by tasks.registering(Jar::class) { include("redis/lua/account-game-session-delegation-pending-register.lua") include("redis/lua/account-game-session-delegation-activate-committed.lua") include("redis/lua/account-game-session-delegation-authority-project.lua") + include("redis/lua/account-game-session-delegation-authority-project-v2.lua") include("redis/lua/account-initial-gameplay-login-dispose.lua") include("redis/account_generation_projection_cas.lua") include("redis/scripts/account-game-session-delegation-pending-register.json") include("redis/scripts/account-game-session-delegation-activate-committed.json") include("redis/scripts/account-game-session-delegation-authority-project-issuer.json") + include("redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json") include("redis/scripts/account-initial-gameplay-login-dispose.json") include("redis/scripts/account-generation-projection-cas.json") include("redis/scripts/account-selected-tenant-generation-projection.json") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationBindings.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationBindings.java new file mode 100644 index 0000000000..b25a76a94a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationBindings.java @@ -0,0 +1,326 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import io.grpc.Status; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetSnapshot; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Exact receiving checks for Account's creation delegation; none authenticate owner content. */ +final class AccountCharacterCreateDelegationBindings { + static final int MAX_ACCOUNT_ORIGINAL_BYTES = 36 * 1024 * 1024; + static final int MAX_ACCOUNT_PROTECTION_BYTES = 40 * 1024 * 1024; + static final int MAX_PROTECTION_BYTES = 48 * 1024 * 1024; + static final int MAX_TERMINAL_BYTES = 192 * 1024 * 1024; + private static final int MAX_TARGET_EVIDENCE_BYTES = 2_105_344; + private static final int MAX_WORLD_LIFECYCLE_EVIDENCE_BYTES = 4 * 1024 * 1024; + + private AccountCharacterCreateDelegationBindings() {} + + static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Creation owner calls require no ambient Account transaction"); + } + } + + static String namespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + return namespace; + } + + static ReadOriginalCharacterCreateProtectionResponse account( + String namespace, + AccountCharacterCreateIntent intent, + AccountCharacterCreateRepository.Protection protection) { + Objects.requireNonNull(intent); + Objects.requireNonNull(protection); + if (!namespace.equals(intent.targetNamespace()) || !intent.sameBinding(protection.intent())) + throw invalid(); + var original = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(namespace) + .setOperationId(intent.operationId().toString()) + .setCreateCharacterRequestId(intent.createCharacterRequestId().toString()) + .setConnectScopeId(intent.connectScopeId()) + .setAuthenticatedAccountId(intent.accountId().toString()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(intent.actionBytes())) + .setMutationDigest(intent.mutationDigest()) + .setOriginalSourceReadback(ByteString.copyFrom(intent.originalSourceReadback())) + .build(); + var result = + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(original) + .setAccountProtectionId(protection.protectionId().toString()) + .setAccountProtectionFence(protection.protectionFence()) + .setAcquiredAt(protection.acquiredAt().toString()) + .setOriginalMembershipSnapshot(ByteString.copyFrom(protection.membershipSnapshot())) + .setOriginalEntitlementSnapshot(ByteString.copyFrom(protection.entitlementSnapshot())) + .build(); + requireAccount(namespace, result); + return result; + } + + static void requireAccount( + String namespace, ReadOriginalCharacterCreateProtectionResponse account) { + exact(account, MAX_ACCOUNT_PROTECTION_BYTES); + if (!account.hasOriginal()) throw invalid(); + var original = account.getOriginal(); + exact(original, MAX_ACCOUNT_ORIGINAL_BYTES); + id(original.getOperationId()); + id(original.getCreateCharacterRequestId()); + AccountCharacterCreateIntent.requireConnectScope(original.getConnectScopeId()); + id(original.getAuthenticatedAccountId()); + id(account.getAccountProtectionId()); + instant(account.getAcquiredAt()); + if (!namespace.equals(original.getTargetNamespace()) + || !"CHARACTER_CREATE".equals(original.getPurpose()) + || account.getAccountProtectionFence() <= 0 + || account.getOriginalMembershipSnapshot().isEmpty() + || account.getOriginalMembershipSnapshot().size() > 1048576 + || account.getOriginalEntitlementSnapshot().isEmpty() + || account.getOriginalEntitlementSnapshot().size() > 65536 + || original.getOriginalAction().isEmpty() + || original.getOriginalAction().size() > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || original.getOriginalSourceReadback().isEmpty() + || original.getOriginalSourceReadback().size() + > AccountCharacterCreateIntent.MAX_SOURCE_READBACK_BYTES) throw invalid(); + var bytes = original.getOriginalAction().toByteArray(); + var action = CharacterCreateOperatorActionCodec.decode(bytes); + if (!Arrays.equals(bytes, CharacterCreateOperatorActionCodec.encode(action)) + || !namespace.equals(action.scope().targetNamespace()) + || !original.getAuthenticatedAccountId().equals(action.target().accountId()) + || !original + .getMutationDigest() + .equals(CharacterCreateOperatorActionCodec.mutationDigest(action))) throw invalid(); + } + + static ReadOriginalCharacterCreateRequest original( + ReadOriginalCharacterCreateProtectionResponse account) { + return ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(account.getOriginal().getTargetNamespace()) + .setOperationId(account.getOriginal().getOperationId()) + .setMutationDigest(account.getOriginal().getMutationDigest()) + .build(); + } + + static ReadOriginalCharacterCreateProtectionRequest selector( + ReadOriginalCharacterCreateProtectionResponse account) { + return ReadOriginalCharacterCreateProtectionRequest.newBuilder() + .setOriginal(original(account)) + .setAccountProtectionId(account.getAccountProtectionId()) + .setAccountProtectionFence(account.getAccountProtectionFence()) + .build(); + } + + static void gameSession( + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target) { + exact(target, MAX_PROTECTION_BYTES); + if (!target.hasAccountProtection() + || !account.equals(target.getAccountProtection()) + || target.getGameSessionProtectionFence() <= 0 + || target.getOriginalTargetEvidence().isEmpty() + || target.getOriginalTargetEvidence().size() > MAX_TARGET_EVIDENCE_BYTES) throw invalid(); + id(target.getGameSessionProtectionId()); + instant(target.getAcquiredAt()); + try { + var snapshot = CharacterCreateTargetSnapshot.parseFrom(target.getOriginalTargetEvidence()); + exact(snapshot, MAX_TARGET_EVIDENCE_BYTES); + var action = + CharacterCreateOperatorActionCodec.decode( + account.getOriginal().getOriginalAction().toByteArray()); + if (!snapshot.toByteString().equals(target.getOriginalTargetEvidence()) + || snapshot.getSchemaVersion() != 1 + || !account.getOriginal().getOriginalAction().equals(snapshot.getOriginalAction()) + || !account.getOriginal().getTargetNamespace().equals(snapshot.getTargetNamespace()) + || !account.getOriginal().getOperationId().equals(snapshot.getOperationId()) + || !account.getOriginal().getMutationDigest().equals(snapshot.getMutationDigest()) + || !action.scope().tenantId().equals(snapshot.getCanonicalTenantId()) + || !action.target().realmId().equals(snapshot.getRealmId()) + || !action.target().gameInstanceId().equals(snapshot.getCanonicalGameInstanceId()) + || !action.target().versionId().equals(snapshot.getCanonicalVersionId()) + || !action + .scope() + .playableStateNamespaceId() + .equals(snapshot.getPlayableStateNamespaceId()) + || !action + .expectedVersion() + .catalogRevision() + .equals(Long.toString(snapshot.getCatalogRevision())) + || !action + .expectedVersion() + .pointerVersion() + .equals(Long.toString(snapshot.getPointerVersion())) + || !action + .expectedVersion() + .activeLifecycleEpoch() + .equals(Long.toString(snapshot.getActiveWorldEpoch())) + || !snapshot.getCatalogReceiptDigest().matches("sha256:[0-9a-f]{64}") + || !snapshot.getInitialAdmissionOwnerProofDigest().matches("sha256:[0-9a-f]{64}") + || !snapshot.getAdmissionPointerSnapshotDigest().matches("[0-9a-f]{64}") + || snapshot.getInitialAdmissionRequestId().isBlank() + || snapshot.getInitialAdmissionRequestId().length() > 1024 + || !snapshot + .getInitialAdmissionRequestId() + .equals(snapshot.getInitialAdmissionRequestId().strip())) throw invalid(); + } catch (InvalidProtocolBufferException malformed) { + throw invalid(); + } + } + + static void world( + ReadOriginalCharacterCreateProtectionResponse account, + WorldCharacterCreateLifecycleProtection world) { + exact(world, MAX_PROTECTION_BYTES); + if (!world.hasAccountProtection() + || !account.equals(world.getAccountProtection()) + || world.getWorldProtectionFence() <= 0 + || world.getOriginalLifecycleEvidence().isEmpty() + || world.getOriginalLifecycleEvidence().size() > MAX_WORLD_LIFECYCLE_EVIDENCE_BYTES) + throw invalid(); + id(world.getWorldProtectionId()); + instant(world.getAcquiredAt()); + var action = + CharacterCreateOperatorActionCodec.decode( + account.getOriginal().getOriginalAction().toByteArray()); + var lifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + world.getOriginalLifecycleEvidence().toByteArray()); + var target = lifecycle.request(); + var source = action.mutation().authoredSource(); + var launch = lifecycle.launchBinding(); + if (!account.getOriginal().getOperationId().equals(target.readRequestId().toString()) + || !action.scope().targetNamespace().equals(target.targetNamespace()) + || !action.scope().tenantId().equals(target.canonicalTenantId().toString()) + || !action + .scope() + .playableStateNamespaceId() + .equals(target.playableStateNamespaceId().toString()) + || !action.mutation().catalog().stateScope().equals(target.playableStateScope()) + || !action.target().gameInstanceId().equals(target.canonicalGameInstanceId().toString()) + || !action.target().versionId().equals(target.canonicalVersionId().toString()) + || !action.target().worldSlug().equals(target.worldSlug()) + || !target.publicProduction() + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || !action + .expectedVersion() + .activeLifecycleEpoch() + .equals(Long.toString(lifecycle.lifecycleEpoch())) + || !source + .worldSourceOperationId() + .equals(launch.descriptor().authoredWorldSourceOperationId().toString()) + || !source + .worldSourceEvidenceDigest() + .equals(launch.descriptor().authoredWorldSourceEvidenceDigest()) + || !source.selectedCommitId().equals(launch.releaseAttestation().commitId()) + || !source.publicationWorkflowId().equals(launch.releaseAttestation().publishWorkflowId())) + throw invalid(); + } + + static CommitProtectedCharacterCreateRequest request( + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target, + WorldCharacterCreateLifecycleProtection world) { + return CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(original(account)) + .setAccountProtection( + reference(account.getAccountProtectionId(), account.getAccountProtectionFence())) + .setGameSessionProtection( + reference(target.getGameSessionProtectionId(), target.getGameSessionProtectionFence())) + .setWorldProtection( + reference(world.getWorldProtectionId(), world.getWorldProtectionFence())) + .build(); + } + + static void terminal( + CommitProtectedCharacterCreateRequest request, + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target, + WorldCharacterCreateLifecycleProtection world, + EntityCharacterCreateTerminal terminal) { + exact(terminal, MAX_TERMINAL_BYTES); + if (!terminal.hasOriginalRequest() + || !request.equals(terminal.getOriginalRequest()) + || !terminal.hasAccountOriginal() + || !account.getOriginal().equals(terminal.getAccountOriginal()) + || !account.toByteString().equals(terminal.getOriginalAccountProtection()) + || !target.toByteString().equals(terminal.getOriginalGameSessionProtection()) + || !world.toByteString().equals(terminal.getOriginalWorldProtection()) + || terminal.getTerminalFence() <= 0 + || !terminal.getEntitySourceReceiptDigest().matches("sha256:[0-9a-f]{64}")) throw invalid(); + // Equality to the already-checked original request and carriers includes every nested field, + // full retained source bytes, protection identifier/fence and acquisition timestamp. + id(terminal.getEntityIntakeRequestId()); + id(terminal.getTerminalId()); + instant(terminal.getCompletedAt()); + if (terminal.getOutcome() + == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) { + id(terminal.getCharacterId()); + if (!terminal.getAbortRequestId().isEmpty()) throw invalid(); + } else if (terminal.getOutcome() + == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED) { + id(terminal.getAbortRequestId()); + if (!terminal.getCharacterId().isEmpty()) throw invalid(); + } else throw invalid(); + } + + static void exact(Message message, int maximum) { + if (message == null + || !message.getUnknownFields().asMap().isEmpty() + || message.getSerializedSize() > maximum) throw invalid(); + } + + static void id(String value) { + if (value == null) throw invalid(); + try { + var id = UUID.fromString(value); + if (!id.toString().equals(value) || id.equals(new UUID(0, 0))) throw invalid(); + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + static void instant(String value) { + try { + if (!Instant.parse(value).toString().equals(value)) throw invalid(); + } catch (java.time.DateTimeException malformed) { + throw invalid(); + } + } + + private static CharacterCreateProtectionReference reference(String id, long fence) { + id(id); + if (fence <= 0) throw invalid(); + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(id) + .setProtectionFence(fence) + .build(); + } + + static RuntimeException invalid() { + return Status.FAILED_PRECONDITION + .withDescription("Exact original CHARACTER_CREATE owner binding required") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClients.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClients.java new file mode 100644 index 0000000000..5dac3b87df --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClients.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; + +/** + * Manually composed Account delegation. Source resolution remains the explicit existing dependency; + * use AccountCharacterCreateOwnerClients.unavailable() until its genuine selected-source and + * player-bootstrap chain is qualified. These clients neither supply that authority nor register it. + */ +public final class AccountCharacterCreateDelegationClients + implements AccountCharacterCreateOwnerClients { + private final String namespace; + private final AccountCharacterCreateOwnerClients sourceResolver; + private final AccountCharacterCreateGameSessionClient gameSession; + private final AccountCharacterCreateWorldClient world; + private final AccountCharacterCreateEntityClient entity; + + public AccountCharacterCreateDelegationClients( + String namespace, + AccountCharacterCreateOwnerClients sourceResolver, + AccountCharacterCreateGameSessionClient gameSession, + AccountCharacterCreateWorldClient world, + AccountCharacterCreateEntityClient entity) { + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + this.sourceResolver = Objects.requireNonNull(sourceResolver); + this.gameSession = Objects.requireNonNull(gameSession); + this.world = Objects.requireNonNull(world); + this.entity = Objects.requireNonNull(entity); + } + + @Override + public ResolvedSource resolvePublicProduction( + String requestedNamespace, AccountCharacterCreatePrincipal principal, String connectScope) { + AccountCharacterCreateDelegationBindings.outsideSql(); + if (!namespace.equals(requestedNamespace)) + throw AccountCharacterCreateDelegationBindings.invalid(); + return sourceResolver.resolvePublicProduction(namespace, principal, connectScope); + } + + @Override + public void requireExactOriginalSource(AccountCharacterCreateIntent intent) { + AccountCharacterCreateDelegationBindings.outsideSql(); + if (!namespace.equals(intent.targetNamespace())) + throw AccountCharacterCreateDelegationBindings.invalid(); + sourceResolver.requireExactOriginalSource(intent); + } + + @Override + public void delegateProtected( + AccountCharacterCreateIntent intent, AccountCharacterCreateRepository.Protection protection) { + submitProtected(intent, protection); + } + + /** + * Only independently read Entity terminal content is returned. On failure every acquired owner + * protection remains retained. Retrying repeats the exact Account selector; each owner's durable + * first acquisition supplies the same reference, including after an ambiguous prior RPC outcome. + * There is no abort, release, refresh, lease renewal or request-identity allocation here. + */ + public EntityCharacterCreateTerminal submitProtected( + AccountCharacterCreateIntent intent, AccountCharacterCreateRepository.Protection protection) { + AccountCharacterCreateDelegationBindings.outsideSql(); + var account = AccountCharacterCreateDelegationBindings.account(namespace, intent, protection); + var target = gameSession.acquireAndReadOriginal(account); + var lifecycle = world.acquireAndReadOriginal(account); + return entity.commitAndReadOriginal(account, target, lifecycle); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateEntityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateEntityClient.java new file mode 100644 index 0000000000..4a261a641c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateEntityClient.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; + +/** + * Unregistered certificate-only Account client; every call uses its exact owner server identity. + */ +public final class AccountCharacterCreateEntityClient + extends AbstractReloadingBlockingGrpcClient< + EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceBlockingStub> { + private final String namespace; + + public AccountCharacterCreateEntityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account CHARACTER_CREATE Entity terminal"), + channels, + AccountCharacterCreateEntityClient.class); + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + } + + public void init() throws IOException { + initOnce( + "Creation Entity terminal client is closed", + "Creation Entity terminal client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceBlockingStub buildStub( + ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return EntityCharacterCreateServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public EntityCharacterCreateTerminal commitAndReadOriginal( + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target, + WorldCharacterCreateLifecycleProtection world) { + requireNoAmbientSql("Entity creation calls require no ambient Account transaction"); + AccountCharacterCreateDelegationBindings.requireAccount(namespace, account); + AccountCharacterCreateDelegationBindings.gameSession(account, target); + AccountCharacterCreateDelegationBindings.world(account, world); + var request = AccountCharacterCreateDelegationBindings.request(account, target, world); + var committed = calls().commitProtectedCharacterCreate(request); + AccountCharacterCreateDelegationBindings.terminal(request, account, target, world, committed); + var readback = readOriginalTerminal(account, target, world); + if (!committed.equals(readback)) throw AccountCharacterCreateDelegationBindings.invalid(); + return readback; + } + + /** Lookup-only reconciliation after an ambiguous commit; absence is never an abort. */ + public EntityCharacterCreateTerminal readOriginalTerminal( + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target, + WorldCharacterCreateLifecycleProtection world) { + requireNoAmbientSql("Entity creation calls require no ambient Account transaction"); + AccountCharacterCreateDelegationBindings.requireAccount(namespace, account); + AccountCharacterCreateDelegationBindings.gameSession(account, target); + AccountCharacterCreateDelegationBindings.world(account, world); + var request = AccountCharacterCreateDelegationBindings.request(account, target, world); + var terminal = + calls() + .readEntityCharacterCreateTerminal( + ReadEntityCharacterCreateTerminalRequest.newBuilder() + .setOriginal(request.getOriginal()) + .build()); + AccountCharacterCreateDelegationBindings.terminal(request, account, target, world, terminal); + return terminal; + } + + private EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceBlockingStub calls() { + return requireInitializedStub("Creation Entity terminal client is not initialized") + .withMaxInboundMessageSize(AccountCharacterCreateDelegationBindings.MAX_TERMINAL_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } + + /** + * Reads a terminal independently for Account's own original hold. The immutable terminal names + * the other protections; this lookup never acquires them or attempts a new commit. + */ + public VerifiedTerminal readVerifiedOriginalTerminal( + ReadOriginalCharacterCreateProtectionResponse account) { + requireNoAmbientSql("Entity creation calls require no ambient Account transaction"); + AccountCharacterCreateDelegationBindings.requireAccount(namespace, account); + var terminal = + calls() + .readEntityCharacterCreateTerminal( + ReadEntityCharacterCreateTerminalRequest.newBuilder() + .setOriginal(AccountCharacterCreateDelegationBindings.original(account)) + .build()); + AccountCharacterCreateDelegationBindings.exact( + terminal, AccountCharacterCreateDelegationBindings.MAX_TERMINAL_BYTES); + try { + var target = + CharacterCreateTargetProtection.parseFrom(terminal.getOriginalGameSessionProtection()); + var lifecycle = + WorldCharacterCreateLifecycleProtection.parseFrom(terminal.getOriginalWorldProtection()); + AccountCharacterCreateDelegationBindings.gameSession(account, target); + AccountCharacterCreateDelegationBindings.world(account, lifecycle); + var request = AccountCharacterCreateDelegationBindings.request(account, target, lifecycle); + AccountCharacterCreateDelegationBindings.terminal( + request, account, target, lifecycle, terminal); + return new VerifiedTerminal(account, terminal); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw AccountCharacterCreateDelegationBindings.invalid(); + } + } + + /** Constructed only after this client's exact authenticated original-terminal read. */ + public static final class VerifiedTerminal { + private final ReadOriginalCharacterCreateProtectionResponse account; + private final EntityCharacterCreateTerminal terminal; + + private VerifiedTerminal( + ReadOriginalCharacterCreateProtectionResponse account, + EntityCharacterCreateTerminal terminal) { + this.account = account; + this.terminal = terminal; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable values and cannot expose mutable state.") + public ReadOriginalCharacterCreateProtectionResponse account() { + return account; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable values and cannot expose mutable state.") + public EntityCharacterCreateTerminal terminal() { + return terminal; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGameSessionClient.java new file mode 100644 index 0000000000..232eab9a32 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGameSessionClient.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.v1.AcquireCharacterCreateTargetProtectionRequest; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalCharacterCreateTargetProtectionRequest; + +/** + * Unregistered certificate-only Account client; every call uses its exact owner server identity. + */ +public final class AccountCharacterCreateGameSessionClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub> { + private final String namespace; + + public AccountCharacterCreateGameSessionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account CHARACTER_CREATE target"), + channels, + AccountCharacterCreateGameSessionClient.class); + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + } + + public void init() throws IOException { + initOnce("Creation target client is closed", "Creation target client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub buildStub( + ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + return CharacterCreateTargetServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public CharacterCreateTargetProtection acquireAndReadOriginal( + ReadOriginalCharacterCreateProtectionResponse account) { + requireNoAmbientSql("Game Session creation calls require no ambient Account transaction"); + AccountCharacterCreateDelegationBindings.requireAccount(namespace, account); + var selector = AccountCharacterCreateDelegationBindings.selector(account); + var acquired = + calls() + .acquireCharacterCreateTargetProtection( + AcquireCharacterCreateTargetProtectionRequest.newBuilder() + .setAccountProtection(selector) + .build()); + AccountCharacterCreateDelegationBindings.gameSession(account, acquired); + var readback = + calls() + .readOriginalCharacterCreateTargetProtection( + ReadOriginalCharacterCreateTargetProtectionRequest.newBuilder() + .setAccountProtection(selector) + .setGameSessionProtectionId(acquired.getGameSessionProtectionId()) + .setGameSessionProtectionFence(acquired.getGameSessionProtectionFence()) + .build()); + AccountCharacterCreateDelegationBindings.gameSession(account, readback); + if (!acquired.equals(readback)) throw AccountCharacterCreateDelegationBindings.invalid(); + return readback; + } + + private CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub calls() { + return requireInitializedStub("Creation target client is not initialized") + .withMaxInboundMessageSize(AccountCharacterCreateDelegationBindings.MAX_PROTECTION_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntent.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntent.java new file mode 100644 index 0000000000..6806a854bb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntent.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; + +/** Account's original immutable player creation request and separately bound issued scope. */ +public record AccountCharacterCreateIntent( + UUID operationId, + UUID createCharacterRequestId, + String connectScopeId, + UUID accountId, + byte[] actionBytes, + String mutationDigest, + byte[] originalSourceReadback) { + public static final String PURPOSE = "CHARACTER_CREATE"; + public static final int MAX_SOURCE_READBACK_BYTES = 32 * 1024 * 1024; + + /** Matches the existing Account bootstrap JOIN and connect-token request bound. */ + public static final int MAX_CONNECT_SCOPE_LENGTH = 2048; + + public AccountCharacterCreateIntent { + requireId(operationId); + requireId(createCharacterRequestId); + requireConnectScope(connectScopeId); + requireId(accountId); + Objects.requireNonNull(actionBytes); + if (actionBytes.length == 0 + || actionBytes.length > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES) { + throw new IllegalArgumentException("Bounded original CHARACTER_CREATE action required"); + } + actionBytes = actionBytes.clone(); + CharacterCreateOperatorAction action = CharacterCreateOperatorActionCodec.decode(actionBytes); + if (!Arrays.equals(actionBytes, CharacterCreateOperatorActionCodec.encode(action)) + || !accountId.toString().equals(action.target().accountId()) + || !GrpcPeerIdentity.isValidNamespace(action.scope().targetNamespace()) + || !action.mutation().catalog().visible() + || !action.mutation().catalog().publicProduction() + || !CharacterCreateOperatorActionCodec.mutationDigest(action).equals(mutationDigest)) { + throw new IllegalArgumentException("Exact authenticated public-production creation required"); + } + Objects.requireNonNull(originalSourceReadback); + if (originalSourceReadback.length == 0 + || originalSourceReadback.length > MAX_SOURCE_READBACK_BYTES) { + throw new IllegalArgumentException("Bounded exact original owner readback required"); + } + originalSourceReadback = originalSourceReadback.clone(); + } + + public CharacterCreateOperatorAction action() { + return CharacterCreateOperatorActionCodec.decode(actionBytes); + } + + public String targetNamespace() { + return action().scope().targetNamespace(); + } + + public UUID tenantId() { + return UUID.fromString(action().scope().tenantId()); + } + + @Override + public byte[] actionBytes() { + return actionBytes.clone(); + } + + @Override + public byte[] originalSourceReadback() { + return originalSourceReadback.clone(); + } + + /** Includes the separately bound operation/source identities, not only the mutation digest. */ + public boolean sameBinding(AccountCharacterCreateIntent other) { + return other != null + && operationId.equals(other.operationId) + && createCharacterRequestId.equals(other.createCharacterRequestId) + && connectScopeId.equals(other.connectScopeId) + && accountId.equals(other.accountId) + && mutationDigest.equals(other.mutationDigest) + && Arrays.equals(actionBytes, other.actionBytes) + && Arrays.equals(originalSourceReadback, other.originalSourceReadback); + } + + static void requireConnectScope(String scope) { + if (scope == null || scope.isBlank() || scope.length() > MAX_CONNECT_SCOPE_LENGTH) { + throw new IllegalArgumentException("Bounded nonblank issued connect scope required"); + } + for (int index = 0; index < scope.length(); index++) { + char value = scope.charAt(index); + if (value == 0 || Character.isLowSurrogate(value)) { + throw new IllegalArgumentException("Exact valid UTF-8 connect scope required"); + } + if (Character.isHighSurrogate(value) + && (++index == scope.length() || !Character.isLowSurrogate(scope.charAt(index)))) { + throw new IllegalArgumentException("Exact valid UTF-8 connect scope required"); + } + } + } + + static void requireId(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical nonnil UUID required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOwnerClients.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOwnerClients.java new file mode 100644 index 0000000000..0fe26415b8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOwnerClients.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; + +/** + * Exact-purpose dependencies for the unregistered Account producer. Implementations must perform + * same-namespace authenticated owner reads and exact original-operation readback. Content digests + * and caller-supplied evidence are never substitutes for those owner calls. + */ +public interface AccountCharacterCreateOwnerClients { + /** Resolves actual catalog/pointer, authored public source and World lifecycle; never private. */ + ResolvedSource resolvePublicProduction( + String namespace, AccountCharacterCreatePrincipal principal, String connectScopeId); + + /** + * Re-reads the retained source at its original owner identities, without refreshing the target. + */ + void requireExactOriginalSource(AccountCharacterCreateIntent intent); + + /** + * Acquires the distinct Game Session catalog/pointer and World lifecycle protections and + * delegates to Entity under the same immutable intent. Every partial acquisition must be durably + * recorded by its genuine owner before the next step; this call supplies no terminal or release + * authority. + */ + void delegateProtected( + AccountCharacterCreateIntent intent, AccountCharacterCreateRepository.Protection protection); + + record ResolvedSource(byte[] actionBytes, byte[] originalSourceReadback) { + public ResolvedSource { + Objects.requireNonNull(actionBytes); + Objects.requireNonNull(originalSourceReadback); + if (actionBytes.length == 0 + || actionBytes.length > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || originalSourceReadback.length == 0 + || originalSourceReadback.length + > AccountCharacterCreateIntent.MAX_SOURCE_READBACK_BYTES) { + throw new IllegalArgumentException("Bounded exact creation owner source required"); + } + actionBytes = actionBytes.clone(); + originalSourceReadback = originalSourceReadback.clone(); + } + + @Override + public byte[] actionBytes() { + return actionBytes.clone(); + } + + @Override + public byte[] originalSourceReadback() { + return originalSourceReadback.clone(); + } + } + + /** No genuine cross-owner creation contracts/clients are registered by this foundation. */ + static AccountCharacterCreateOwnerClients unavailable() { + return new AccountCharacterCreateOwnerClients() { + @Override + public ResolvedSource resolvePublicProduction( + String namespace, AccountCharacterCreatePrincipal principal, String scope) { + throw unavailableDependency(); + } + + @Override + public void requireExactOriginalSource(AccountCharacterCreateIntent intent) { + throw unavailableDependency(); + } + + @Override + public void delegateProtected( + AccountCharacterCreateIntent intent, + AccountCharacterCreateRepository.Protection protection) { + throw unavailableDependency(); + } + }; + } + + private static RuntimeException unavailableDependency() { + return Status.UNAVAILABLE + .withDescription("Genuine CHARACTER_CREATE owner composition is unavailable") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipal.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipal.java new file mode 100644 index 0000000000..54240223a9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipal.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; + +/** + * Private-composition identity capability backed by the existing signed bootstrap, persisted + * Account provenance and active-session verifier. It supplies identity only, never creation + * permission. + */ +public final class AccountCharacterCreatePrincipal { + private final AccountPlayerBootstrapCallerVerifier verifier; + private final String bootstrapToken; + private final UUID originalAccount; + + private AccountCharacterCreatePrincipal( + AccountPlayerBootstrapCallerVerifier verifier, String bootstrapToken, UUID originalAccount) { + this.verifier = verifier; + this.bootstrapToken = bootstrapToken; + this.originalAccount = originalAccount; + } + + public static AccountCharacterCreatePrincipal authenticate( + AccountPlayerBootstrapCallerVerifier verifier, String bootstrapToken) { + AccountCharacterCreateDelegationBindings.outsideSql(); + Objects.requireNonNull(verifier); + UUID account = Objects.requireNonNull(verifier.requireCaller(bootstrapToken)).accountUuid(); + return new AccountCharacterCreatePrincipal(verifier, bootstrapToken, account); + } + + public UUID authenticateCurrentAccount() { + return authenticateCurrentCaller().accountUuid(); + } + + AccountPlayerBootstrapCallerVerifier.VerifiedCaller authenticateCurrentCaller() { + AccountCharacterCreateDelegationBindings.outsideSql(); + var caller = Objects.requireNonNull(verifier.requireCaller(bootstrapToken)); + UUID current = caller.accountUuid(); + if (!originalAccount.equals(current)) { + throw new IllegalStateException("Bootstrap Account identity changed"); + } + return caller; + } + + @Override + public String toString() { + return "AccountCharacterCreatePrincipal[credential=]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClient.java new file mode 100644 index 0000000000..897a42e556 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClient.java @@ -0,0 +1,337 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; + +/** + * Unregistered Account transport for Game Session's independently composed public source. Its + * result authenticates the configured Game Session owner; it is not Account bootstrap, issued + * scope, membership, protection, or admission authority. + */ +public final class AccountCharacterCreatePublicSourceClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreatePublicSourceServiceGrpc.CharacterCreatePublicSourceServiceBlockingStub> { + public static final int MAX_SOURCE_WIRE_BYTES = 32 * 1024 * 1024; + public static final int MAX_TARGET_WIRE_BYTES = 64 * 1024; + private final String namespace; + + public AccountCharacterCreatePublicSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account CHARACTER_CREATE public source"), + channels, + AccountCharacterCreatePublicSourceClient.class); + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + } + + public void init() throws IOException { + initOnce("Creation public source client is closed", "Creation public source is unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CharacterCreatePublicSourceServiceGrpc.CharacterCreatePublicSourceServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + return CharacterCreatePublicSourceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withMaxInboundMessageSize(MAX_SOURCE_WIRE_BYTES); + } + + /** Canonical target identities originate in Game Session; this issues no Account scope. */ + public AuthenticatedTarget resolve(String worldSlug, String realmSlug, UUID readRequestId) { + requireNoAmbientSql("Public creation target read requires no ambient Account transaction"); + if (!RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug) + || readRequestId == null) throw invalid(); + AccountCharacterCreateDelegationBindings.id(readRequestId.toString()); + var request = + ResolveCharacterCreatePublicTargetRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(readRequestId.toString()) + .setTargetNamespace(namespace) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .build(); + if (request.getSerializedSize() > 16 * 1024) throw invalid(); + var response = + requireInitializedStub("Creation public source is unavailable") + .withMaxInboundMessageSize(MAX_TARGET_WIRE_BYTES) + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .resolveCharacterCreatePublicTarget(request); + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSchemaVersion() != 1 + || response.getSerializedSize() > MAX_TARGET_WIRE_BYTES + || !request.equals(response.getRequest()) + || !response.hasCatalog() + || !response.hasPointer() + || response.getActiveLifecycleEpoch() <= 0) throw invalid(); + var catalog = response.getCatalog(); + var pointer = response.getPointer(); + if (!catalog.getUnknownFields().asMap().isEmpty() + || !pointer.getUnknownFields().asMap().isEmpty() + || !catalog.getVisible() + || !catalog.getPublicProduction() + || !"SHARED".equals(catalog.getStateScope()) + || !"PLAYER_CREATED".equals(catalog.getCharacterCreationPolicy()) + || !worldSlug.equals(catalog.getWorldSlug()) + || !realmSlug.equals(catalog.getRealmSlug()) + || !RealmEntryPolicy.isCanonicalSlug(catalog.getTenantSlug()) + || catalog.getWorldDisplayName().isBlank() + || catalog.getRealmDisplayName().isBlank() + || catalog.getCatalogRevision() <= 0 + || !catalog.getTenantId().equals(pointer.getTenantId()) + || !catalog.getRealmId().equals(pointer.getRealmId()) + || !catalog.getWorldSlug().equals(pointer.getWorldSlug()) + || !catalog.getRealmSlug().equals(pointer.getRealmSlug()) + || catalog.getCatalogRevision() != pointer.getCatalogRevision() + || !"OPEN".equals(pointer.getAdmissionState()) + || !response.getCanonicalGameInstanceId().equals(pointer.getAdmissibleGameInstanceId()) + || pointer.getPointerVersion() <= 0 + || !catalog.getReceiptDigest().matches("sha256:[0-9a-f]{64}") + || pointer.getInitialAdmissionRequestId().isBlank() + || !pointer.getInitialAdmissionOwnerProofDigest().matches("sha256:[0-9a-f]{64}") + || !pointer.getAdmissionPointerSnapshotDigest().matches("[0-9a-f]{64}")) throw invalid(); + for (String id : + java.util.List.of( + catalog.getTenantId(), + catalog.getRealmId(), + catalog.getPlayableStateNamespaceId(), + catalog.getCreationRequestId(), + response.getCanonicalGameInstanceId(), + response.getCanonicalVersionId())) AccountCharacterCreateDelegationBindings.id(id); + AccountCharacterCreateDelegationBindings.instant(pointer.getUpdatedAt()); + for (String name : + java.util.List.of(catalog.getWorldDisplayName(), catalog.getRealmDisplayName())) { + if (!name.equals(name.strip()) + || name.codePointCount(0, name.length()) > RealmEntryPolicy.MAX_DISPLAY_NAME_CODE_POINTS + || name.codePoints().anyMatch(Character::isISOControl)) throw invalid(); + } + return new AuthenticatedTarget(response); + } + + public AuthenticatedSource read(ReadCharacterCreatePublicSourceRequest request) { + requireNoAmbientSql("Public creation source read requires no ambient Account transaction"); + requireRequest(request); + var response = + requireInitializedStub("Creation public source is unavailable") + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .readCharacterCreatePublicSource(request); + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSchemaVersion() != 1 + || response.getSerializedSize() > MAX_SOURCE_WIRE_BYTES + || !request.equals(response.getRequest()) + || !response.hasCatalog() + || !response.hasPointer() + || !response.hasAuthoredSource() + || response.getWorldLifecycleEvidence().isEmpty()) throw invalid(); + var catalog = response.getCatalog(); + var pointer = response.getPointer(); + if (!catalog.getUnknownFields().asMap().isEmpty() + || !pointer.getUnknownFields().asMap().isEmpty() + || !catalog.getVisible() + || !catalog.getPublicProduction() + || !"PLAYER_CREATED".equals(catalog.getCharacterCreationPolicy()) + || !"SHARED".equals(catalog.getStateScope()) + || !request.getCanonicalTenantId().equals(catalog.getTenantId()) + || !request.getRealmId().equals(catalog.getRealmId()) + || !request.getWorldSlug().equals(catalog.getWorldSlug()) + || !request.getRealmSlug().equals(catalog.getRealmSlug()) + || !request.getPlayableStateNamespaceId().equals(catalog.getPlayableStateNamespaceId()) + || request.getCatalogRevision() != catalog.getCatalogRevision() + || !request.getCanonicalTenantId().equals(pointer.getTenantId()) + || !request.getRealmId().equals(pointer.getRealmId()) + || !request.getWorldSlug().equals(pointer.getWorldSlug()) + || !request.getRealmSlug().equals(pointer.getRealmSlug()) + || !request.getCanonicalGameInstanceId().equals(pointer.getAdmissibleGameInstanceId()) + || !"OPEN".equals(pointer.getAdmissionState()) + || request.getCatalogRevision() != pointer.getCatalogRevision() + || request.getPointerVersion() != pointer.getPointerVersion() + || response.getActiveLifecycleEpoch() <= 0 + || response.getOriginalOwnerFence() <= 0) throw invalid(); + AccountCharacterCreateDelegationBindings.id(response.getCanonicalVersionId()); + if (response.getOriginalControlPlaneRequestId().isBlank() + || response.getOriginalControlPlaneRequestId().length() > 128) throw invalid(); + AccountCharacterCreateDelegationBindings.id(response.getOriginalOwnerAttemptId()); + AccountCharacterCreateDelegationBindings.instant(pointer.getUpdatedAt()); + var authored = + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + response.getAuthoredSource().getRequest()), + response.getAuthoredSource()); + var world = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getWorldLifecycleEvidence().toByteArray()); + var association = authored.associationRead().association(); + var lifecycleRequest = world.request(); + if (!namespace.equals(authored.request().targetNamespace()) + || !response + .getOriginalOwnerAttemptId() + .equals(authored.request().ownerAttemptId().toString()) + || response.getOriginalOwnerFence() != authored.request().ownerFence() + || !response + .getOriginalControlPlaneRequestId() + .equals(authored.request().decodedTuple().controlPlaneRequestId()) + || !authored.descriptor().equals(world.launchBinding().descriptor()) + || !association + .publishWorkflowId() + .equals(world.launchBinding().releaseAttestation().publishWorkflowId()) + || !association + .selectedCommitId() + .toString() + .equals(world.launchBinding().releaseAttestation().commitId()) + || !request.getCanonicalTenantId().equals(association.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(association.worldSlug()) + || !response.getCanonicalVersionId().equals(association.canonicalVersionId().toString()) + || !namespace.equals(lifecycleRequest.targetNamespace()) + || !request.getCanonicalTenantId().equals(lifecycleRequest.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(lifecycleRequest.worldSlug()) + || !request + .getCanonicalGameInstanceId() + .equals(lifecycleRequest.canonicalGameInstanceId().toString()) + || !request + .getPlayableStateNamespaceId() + .equals(lifecycleRequest.playableStateNamespaceId().toString()) + || !response + .getCanonicalVersionId() + .equals(lifecycleRequest.canonicalVersionId().toString()) + || !response + .getOriginalControlPlaneRequestId() + .equals(lifecycleRequest.controlPlaneRequestId()) + || !"SHARED".equals(lifecycleRequest.playableStateScope()) + || !lifecycleRequest.publicProduction() + || !"ACTIVE".equals(world.lifecycleStatus()) + || response.getActiveLifecycleEpoch() != world.lifecycleEpoch()) throw invalid(); + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + var selected = + authored.projections().stream() + .filter( + projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), json) + .realmSlug() + .equals(request.getRealmSlug())) + .toList(); + if (selected.size() != 1) throw invalid(); + var policy = + RealmEntryPolicy.parseCanonical(selected.getFirst().policy().canonicalJson(), json); + if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !policy.worldSlug().equals(catalog.getWorldSlug()) + || !policy.worldDisplayName().equals(catalog.getWorldDisplayName()) + || !policy.realmDisplayName().equals(catalog.getRealmDisplayName())) throw invalid(); + return new AuthenticatedSource(response, authored, world); + } + + private void requireRequest(ReadCharacterCreatePublicSourceRequest request) { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || request.getSerializedSize() > 16 * 1024 + || !namespace.equals(request.getTargetNamespace()) + || !"SHARED".equals(request.getPlayableStateScope()) + || request.getWorldSlug().isBlank() + || request.getRealmSlug().isBlank() + || request.getCatalogRevision() <= 0 + || request.getPointerVersion() <= 0) throw invalid(); + for (String id : + java.util.List.of( + request.getReadRequestId(), + request.getCanonicalTenantId(), + request.getRealmId(), + request.getPlayableStateNamespaceId(), + request.getCanonicalGameInstanceId())) AccountCharacterCreateDelegationBindings.id(id); + AccountCharacterCreateDelegationBindings.instant(request.getEvaluatedAt()); + AccountCharacterCreateDelegationBindings.instant(request.getConnectScopeExpiresAt()); + if (!java.time.Instant.parse(request.getEvaluatedAt()) + .isBefore(java.time.Instant.parse(request.getConnectScopeExpiresAt()))) throw invalid(); + } + + private static RuntimeException invalid() { + return AccountCharacterCreateDelegationBindings.invalid(); + } + + /** Authenticates only the configured Game Session owner, never bootstrap or scope authority. */ + public static final class AuthenticatedTarget { + private final ResolveCharacterCreatePublicTargetResponse response; + + private AuthenticatedTarget(ResolveCharacterCreatePublicTargetResponse response) { + this.response = response; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable values and cannot expose mutable state.") + public ResolveCharacterCreatePublicTargetResponse response() { + return response; + } + } + + /** Constructor custody establishes this transport read, never the other owners' authority. */ + public static final class AuthenticatedSource { + private final ReadCharacterCreatePublicSourceResponse response; + private final AuthoredInitialActorCoreReadEvidence.ReadResult authored; + private final WorldCanonicalInstanceLifecycleEvidence world; + + private AuthenticatedSource( + ReadCharacterCreatePublicSourceResponse response, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence world) { + this.response = response; + this.authored = authored; + this.world = world; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable values and cannot expose mutable state.") + public ReadCharacterCreatePublicSourceResponse response() { + return response; + } + + public AuthoredInitialActorCoreReadEvidence.ReadResult authored() { + return authored; + } + + public WorldCanonicalInstanceLifecycleEvidence world() { + return world; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateRepository.java new file mode 100644 index 0000000000..f265e9cd52 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateRepository.java @@ -0,0 +1,407 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Account owner storage. The source reads and protection insert share the actual + * writable READ COMMITTED transaction and the existing Account source-writer locks. + */ +public final class AccountCharacterCreateRepository { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final DSLContext dsl; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountDemoTenantEntitlementRepository entitlements; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected SQL collaborators are shared owner repositories and cannot be copied as values.") + public AccountCharacterCreateRepository( + DSLContext dsl, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountDemoTenantEntitlementRepository entitlements) { + this.dsl = Objects.requireNonNull(dsl); + this.memberships = Objects.requireNonNull(memberships); + this.entitlements = Objects.requireNonNull(entitlements); + } + + public Optional findOriginal( + String namespace, UUID accountId, UUID requestId) { + requireTransaction(); + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM account_character_create_intents " + + "WHERE target_namespace = ? AND account_uuid = ? AND request_id = ?", + namespace, + accountId, + requestId)) + .map(AccountCharacterCreateRepository::intent); + } + + public Optional findOperation(String namespace, UUID operationId) { + requireTransaction(); + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM account_character_create_intents " + + "WHERE target_namespace = ? AND operation_id = ?", + namespace, + operationId)) + .map(AccountCharacterCreateRepository::intent); + } + + /** Persists the full intent before any protection or delegation; never replaces its winner. */ + public AccountCharacterCreateIntent retain(AccountCharacterCreateIntent candidate) { + requireTransaction(); + dsl.execute( + "INSERT INTO account_character_create_intents " + + "(operation_id, target_namespace, account_uuid, tenant_uuid, request_id, " + + "connect_scope_id, purpose, action_bytes, mutation_digest, original_source_readback) " + + "VALUES (?, ?, ?, ?, ?, ?, 'CHARACTER_CREATE', ?, ?, ?) " + + "ON CONFLICT (target_namespace, account_uuid, request_id) DO NOTHING", + candidate.operationId(), + candidate.targetNamespace(), + candidate.accountId(), + candidate.tenantId(), + candidate.createCharacterRequestId(), + candidate.connectScopeId(), + candidate.actionBytes(), + candidate.mutationDigest(), + candidate.originalSourceReadback()); + AccountCharacterCreateIntent retained = + findOriginal( + candidate.targetNamespace(), + candidate.accountId(), + candidate.createCharacterRequestId()) + .orElseThrow(AccountCharacterCreateRepository::unavailable); + // Concurrent first producers may allocate distinct operation UUIDs; only the immutable winner + // is returned, and all caller/source bindings must still match exactly. + AccountCharacterCreateIntent boundToWinner = + new AccountCharacterCreateIntent( + retained.operationId(), + candidate.createCharacterRequestId(), + candidate.connectScopeId(), + candidate.accountId(), + candidate.actionBytes(), + candidate.mutationDigest(), + candidate.originalSourceReadback()); + if (!retained.sameBinding(boundToWinner)) throw conflict(); + return retained; + } + + /** + * Revalidates actual canonical membership/event and entitlement owners while their writers are + * excluded. The initial supported source is the existing fresh-UUID NON_PAID_DEMO entitlement; + * legacy numeric subscriptions, creator roles and private realm grants cannot substitute. + */ + public Protection acquire(AccountCharacterCreateIntent original) { + requireTransaction(); + requireRetained(original); + Optional previous = findProtection(original); + if (previous.isPresent()) return previous.orElseThrow(); + + dsl.fetch( + "SELECT account_character_create_lock_acquisition_sources(?, ?)", + original.accountId(), + original.tenantId()); + Snapshot membership = memberships.readCurrent(original.accountId(), original.tenantId()); + if (RuntimeMembershipAuthorityEvidenceValidator.validate(membership).isEmpty() + || !membership.membershipExists() + || !"ACTIVE".equals(membership.membershipLifecycleState()) + || !membership.gameplayAdmissionAllowed() + || !original.accountId().toString().equals(membership.accountId()) + || !original.tenantId().toString().equals(membership.tenantId())) { + throw unavailable(); + } + var entitlement = entitlements.readCurrent(original.tenantId()); + if (!original.tenantId().equals(entitlement.canonicalTenantId()) + || !original.targetNamespace().equals(entitlement.sourceEvidence().targetNamespace()) + || !entitlement.gameplayAvailable() + || !entitlement.allowNewGameplayBindings() + || !"ACTIVE".equals(entitlement.status())) { + throw unavailable(); + } + byte[] membershipBytes = membershipBytes(membership); + byte[] entitlementBytes = JSON.writeValueAsBytes(entitlement); + dsl.execute( + "INSERT INTO account_character_create_protections " + + "(protection_id, operation_id, membership_snapshot, entitlement_snapshot) " + + "VALUES (?, ?, ?, ?) ON CONFLICT (operation_id) DO NOTHING", + UUID.randomUUID(), + original.operationId(), + membershipBytes, + entitlementBytes); + return findProtection(original).orElseThrow(AccountCharacterCreateRepository::unavailable); + } + + /** Historical exact read: expiry never changes the original protection. */ + public Optional findProtection(AccountCharacterCreateIntent original) { + requireTransaction(); + requireRetained(original); + Record row = + dsl.fetchOne( + "SELECT * FROM account_character_create_protections WHERE operation_id = ?", + original.operationId()); + if (row == null) return Optional.empty(); + return Optional.of( + new Protection( + original, + row.get("protection_id", UUID.class), + row.get("protection_fence", Long.class), + row.get("acquired_at", OffsetDateTime.class).toInstant(), + row.get("membership_snapshot", byte[].class), + row.get("entitlement_snapshot", byte[].class))); + } + + public Optional findSettlement(Protection expected) { + requireTransaction(); + requireRetained(expected.intent()); + var actual = + findProtection(expected.intent()) + .orElseThrow(AccountCharacterCreateRepository::unavailable); + if (!actual.sameBinding(expected)) throw conflict(); + Record row = + dsl.fetchOne( + "SELECT terminal_bytes FROM account_character_create_settlements WHERE protection_id = ?", + expected.protectionId()); + if (row == null) return Optional.empty(); + try { + var terminal = EntityCharacterCreateTerminal.parseFrom(row.get(0, byte[].class)); + requireOwnTerminal(expected, terminal); + if (!Arrays.equals(row.get(0, byte[].class), terminal.toByteArray())) throw conflict(); + return Optional.of(terminal); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw unavailable(); + } + } + + /** Only the exact authenticated Entity-client capability can supply a new settlement. */ + public EntityCharacterCreateTerminal settle( + Protection expected, AccountCharacterCreateEntityClient.VerifiedTerminal verified) { + requireTransaction(); + Objects.requireNonNull(verified); + var account = + AccountCharacterCreateDelegationBindings.account( + expected.intent().targetNamespace(), expected.intent(), expected); + if (!account.equals(verified.account())) throw conflict(); + var terminal = verified.terminal(); + requireOwnTerminal(expected, terminal); + // Use the source writers' exact lock identities and ordering, without asking a held source + // to authorize its own mutation. There is no RPC under these owner locks. + dsl.fetch( + "SELECT account_character_create_lock_settlement_sources(?, ?)", + expected.intent().accountId(), + expected.intent().tenantId()); + dsl.fetchOne( + "SELECT protection_id FROM account_character_create_protections WHERE protection_id = ? FOR UPDATE", + expected.protectionId()); + var actual = + findProtection(expected.intent()) + .orElseThrow(AccountCharacterCreateRepository::unavailable); + if (!actual.sameBinding(expected)) throw conflict(); + var original = findSettlement(expected); + if (original.isPresent()) { + if (!original.orElseThrow().equals(terminal)) throw conflict(); + return original.orElseThrow(); + } + dsl.execute( + "INSERT INTO account_character_create_settlements (protection_id, protection_fence, operation_id, " + + "original_membership_snapshot, original_entitlement_snapshot, original_action, original_source_readback, " + + "entity_terminal_id, entity_terminal_fence, outcome, terminal_bytes, terminal_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + expected.protectionId(), + expected.protectionFence(), + expected.intent().operationId(), + expected.membershipSnapshot(), + expected.entitlementSnapshot(), + expected.intent().actionBytes(), + expected.intent().originalSourceReadback(), + UUID.fromString(terminal.getTerminalId()), + terminal.getTerminalFence(), + terminal.getCharacterId().isEmpty() ? "ABORTED" : "COMMITTED", + terminal.toByteArray(), + "sha256:" + java.util.HexFormat.of().formatHex(sha256(terminal.toByteArray()))); + return findSettlement(expected).orElseThrow(AccountCharacterCreateRepository::unavailable); + } + + private static void requireOwnTerminal( + Protection expected, EntityCharacterCreateTerminal terminal) { + AccountCharacterCreateDelegationBindings.exact( + terminal, AccountCharacterCreateDelegationBindings.MAX_TERMINAL_BYTES); + var account = + AccountCharacterCreateDelegationBindings.account( + expected.intent().targetNamespace(), expected.intent(), expected); + if (!terminal.hasOriginalRequest() + || !terminal.hasAccountOriginal() + || !account.getOriginal().equals(terminal.getAccountOriginal()) + || !account.toByteString().equals(terminal.getOriginalAccountProtection()) + || !AccountCharacterCreateDelegationBindings.original(account) + .equals(terminal.getOriginalRequest().getOriginal()) + || !expected + .protectionId() + .toString() + .equals(terminal.getOriginalRequest().getAccountProtection().getProtectionId()) + || expected.protectionFence() + != terminal.getOriginalRequest().getAccountProtection().getProtectionFence() + || terminal.getTerminalFence() <= 0 + || !terminal.getEntitySourceReceiptDigest().matches("sha256:[0-9a-f]{64}")) + throw conflict(); + AccountCharacterCreateDelegationBindings.id(terminal.getEntityIntakeRequestId()); + AccountCharacterCreateDelegationBindings.id(terminal.getTerminalId()); + AccountCharacterCreateDelegationBindings.instant(terminal.getCompletedAt()); + switch (terminal.getOutcome()) { + case ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED -> { + AccountCharacterCreateDelegationBindings.id(terminal.getCharacterId()); + if (!terminal.getAbortRequestId().isEmpty()) throw conflict(); + } + case ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED -> { + AccountCharacterCreateDelegationBindings.id(terminal.getAbortRequestId()); + if (!terminal.getCharacterId().isEmpty()) throw conflict(); + } + default -> throw conflict(); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return java.security.MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private void requireRetained(AccountCharacterCreateIntent expected) { + AccountCharacterCreateIntent retained = + findOperation(expected.targetNamespace(), expected.operationId()) + .orElseThrow(AccountCharacterCreateRepository::unavailable); + if (!retained.sameBinding(expected)) throw conflict(); + } + + private static AccountCharacterCreateIntent intent(Record row) { + AccountCharacterCreateIntent intent = + new AccountCharacterCreateIntent( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("connect_scope_id", String.class), + row.get("account_uuid", UUID.class), + row.get("action_bytes", byte[].class), + row.get("mutation_digest", String.class), + row.get("original_source_readback", byte[].class)); + if (!intent.targetNamespace().equals(row.get("target_namespace", String.class)) + || !intent.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !AccountCharacterCreateIntent.PURPOSE.equals(row.get("purpose", String.class))) { + throw unavailable(); + } + return intent; + } + + private static byte[] membershipBytes(Snapshot snapshot) { + Map value = new LinkedHashMap<>(); + value.put("issuerId", snapshot.issuerId()); + value.put("accountId", snapshot.accountId()); + value.put("tenantId", snapshot.tenantId()); + value.put("membershipExists", snapshot.membershipExists()); + value.put("membershipLifecycleState", snapshot.membershipLifecycleState()); + value.put("gameplayAdmissionAllowed", snapshot.gameplayAdmissionAllowed()); + value.put("membershipVersion", snapshot.membershipVersion()); + value.put("membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); + value.put("roles", snapshot.roles()); + value.put("issuanceFence", snapshot.issuanceFence()); + value.put("checkpoints", snapshot.checkpoints()); + value.put("sourceEvidence", snapshot.sourceEvidence()); + var tuple = snapshot.authorityTuple(); + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", tuple.issuerAuthGeneration()); + authority.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration()); + authority.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + authority.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + authority.put("privateRealmGrantVersions", tuple.privateRealmGrantVersions()); + tuple + .accountSecurityCutoff() + .ifPresent(cutoff -> authority.put("accountSecurityCutoff", cutoff)); + tuple.tenantBillingCutoff().ifPresent(cutoff -> authority.put("tenantBillingCutoff", cutoff)); + value.put("authorityTuple", authority); + value.put("realmGrantApplicability", "NOT_APPLICABLE_PUBLIC_PRODUCTION"); + return JSON.writeValueAsBytes(value); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact Account CHARACTER_CREATE source unavailable"); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "CHARACTER_CREATE conflicts with its original immutable intent"); + } + + public record Protection( + AccountCharacterCreateIntent intent, + UUID protectionId, + long protectionFence, + Instant acquiredAt, + byte[] membershipSnapshot, + byte[] entitlementSnapshot) { + public Protection { + Objects.requireNonNull(intent); + AccountCharacterCreateIntent.requireId(protectionId); + if (protectionFence <= 0L) + throw new IllegalArgumentException("Positive Account fence required"); + Objects.requireNonNull(acquiredAt); + membershipSnapshot = Objects.requireNonNull(membershipSnapshot).clone(); + entitlementSnapshot = Objects.requireNonNull(entitlementSnapshot).clone(); + if (membershipSnapshot.length == 0 || entitlementSnapshot.length == 0) throw unavailable(); + } + + @Override + public byte[] membershipSnapshot() { + return membershipSnapshot.clone(); + } + + @Override + public byte[] entitlementSnapshot() { + return entitlementSnapshot.clone(); + } + + public boolean sameBinding(Protection other) { + return other != null + && intent.sameBinding(other.intent) + && protectionId.equals(other.protectionId) + && protectionFence == other.protectionFence + && acquiredAt.equals(other.acquiredAt) + && Arrays.equals(membershipSnapshot, other.membershipSnapshot) + && Arrays.equals(entitlementSnapshot, other.entitlementSnapshot); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwner.java new file mode 100644 index 0000000000..c47b768e08 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwner.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import io.jsonwebtoken.Claims; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered creation-selector issuer. It accepts only the authenticated public PLAYER_CREATED + * target capability, persists exact canonical scope evidence, and grants no owner protection, + * membership, character allocation or gameplay admission. The PRESEEDED selector owner is + * unchanged. + */ +public final class AccountCharacterCreateScopeOwner { + private final String namespace; + private final JwtUtil jwt; + private final Clock clock; + private final long lifetimeMillis; + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountConnectScopeRepository scopes; + private final AccountCanonicalConnectScopeReader reader; + private final TransactionTemplate transaction; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-managed repository remains private and cannot be value-copied.") + public AccountCharacterCreateScopeOwner( + String namespace, + JwtUtil jwt, + Clock clock, + AccountTokenProperties properties, + FreshTenantIdentityAssociationRepository tenants, + AccountConnectScopeRepository scopes, + AccountCanonicalConnectScopeReader reader, + PlatformTransactionManager transactions) { + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + this.jwt = Objects.requireNonNull(jwt); + this.clock = Objects.requireNonNull(clock); + this.tenants = Objects.requireNonNull(tenants); + this.scopes = Objects.requireNonNull(scopes); + this.reader = Objects.requireNonNull(reader); + lifetimeMillis = Objects.requireNonNull(properties).getConnectScopeExpirationMs(); + if (lifetimeMillis <= 0) throw new IllegalArgumentException("Positive scope lifetime required"); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.setTimeout(5); + } + + public CanonicalJoinScopeV2 issueCanonicalCharacterCreateScope( + AccountCharacterCreatePrincipal principal, + AccountCharacterCreatePublicSourceClient.AuthenticatedTarget authenticated) { + AccountCharacterCreateDelegationBindings.outsideSql(); + var caller = Objects.requireNonNull(principal).authenticateCurrentCaller(); + var response = Objects.requireNonNull(authenticated).response(); + var catalog = response.getCatalog(); + if (!namespace.equals(response.getRequest().getTargetNamespace()) + || !catalog.getVisible() + || !catalog.getPublicProduction() + || !"SHARED".equals(catalog.getStateScope()) + || !"PLAYER_CREATED".equals(catalog.getCharacterCreationPolicy())) { + throw unavailable("Exact public creation target required", null); + } + var target = + new Target( + UUID.fromString(catalog.getTenantId()), + UUID.fromString(catalog.getRealmId()), + catalog.getTenantSlug(), + catalog.getWorldSlug(), + catalog.getRealmSlug(), + UUID.fromString(catalog.getPlayableStateNamespaceId()), + catalog.getStateScope(), + UUID.fromString(response.getCanonicalGameInstanceId()), + catalog.getCatalogRevision(), + response.getPointer().getPointerVersion()); + Instant evaluated = clock.instant().truncatedTo(ChronoUnit.MILLIS); + Instant expires = evaluated.plusMillis(lifetimeMillis); + CanonicalJoinScopeV2 scope = mintScope(caller, target, evaluated, expires); + // Credential calls remain outside SQL; Account/tenant identity is locked and rechecked by + // insertCanonical. Selection is evidence only; original source and all owner authorities are + // independently revalidated when the creation operation acquires protection. + principal.authenticateCurrentAccount(); + transaction.executeWithoutResult( + status -> { + var tenant = + tenants + .read(target.canonicalTenantId()) + .orElseThrow(() -> unavailable("Fresh tenant source required", null)); + if (!namespace.equals(tenant.targetNamespace()) + || !target.canonicalTenantId().equals(tenant.canonicalTenantId())) { + throw unavailable("Tenant source differs from creation target", null); + } + scopes.insertCanonical( + caller.accountId(), + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.operationId(), + tenant.evidenceDigest())); + }); + CanonicalJoinScopeV2 retained = reader.read(caller.accountUuid(), scope.connectScopeId()); + if (!scope.equals(retained)) throw unavailable("Creation scope readback differs", null); + principal.authenticateCurrentAccount(); + return retained; + } + + public CanonicalJoinScopeV2 verifyCanonicalCharacterCreateScope( + AccountCharacterCreatePrincipal principal, String opaqueScope, String requestedNamespace) { + AccountCharacterCreateDelegationBindings.outsideSql(); + if (!namespace.equals(requestedNamespace)) throw unavailable("Namespace differs", null); + UUID account = Objects.requireNonNull(principal).authenticateCurrentAccount(); + var scope = reader.read(account, opaqueScope); + principal.authenticateCurrentAccount(); + return scope; + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException(message, cause); + } + + private record Target( + UUID canonicalTenantId, + UUID realmId, + String tenantSlug, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + long catalogRevision, + long pointerVersion) {} + + private CanonicalJoinScopeV2 mintScope( + AccountPlayerBootstrapCallerVerifier.VerifiedCaller caller, + Target target, + Instant evaluatedAt, + Instant expiresAt) { + Map claims = new LinkedHashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", caller.accountUuid().toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2L); + claims.put("tenantId", target.canonicalTenantId().toString()); + claims.put("tenantSlug", target.tenantSlug()); + claims.put("worldSlug", target.worldSlug()); + claims.put("realmId", target.realmId().toString()); + claims.put("realmSlug", target.realmSlug()); + claims.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + claims.put("playableStateScope", target.playableStateScope()); + claims.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + claims.put("catalogRevision", target.catalogRevision()); + claims.put("pointerVersion", target.pointerVersion()); + claims.put("evaluatedAt", evaluatedAt.toString()); + claims.put("connectScopeExpiresAt", expiresAt.toString()); + claims.put("jti", UUID.randomUUID().toString()); + // Preserve the owner-selected absolute expiry even if signing starts after a scheduling pause. + final String token; + try { + token = jwt.generateToken(caller.accountUuid().toString(), expiresAt, claims); + } catch (IllegalArgumentException expired) { + throw unavailable("Scope signing clock is outside its validity", expired); + } + Claims signed = jwt.parseToken(token).getPayload(); + if (!caller.accountUuid().toString().equals(signed.getSubject()) + || signed.getExpiration() == null + || !expiresAt.equals(signed.getExpiration().toInstant()) + || signed.getIssuedAt() == null + || !signed.getIssuedAt().toInstant().isBefore(expiresAt) + || !"bootstrap-connect-scope".equals(JwtClaims.requireText(signed.get("aud"), "aud"))) { + throw unavailable("Signed scope profile differs from the retained preimage", null); + } + for (var entry : claims.entrySet()) { + if (entry.getKey().equals("aud")) continue; + Object actual = signed.get(entry.getKey()); + if (entry.getValue() instanceof Long number) { + if (JwtClaims.requireLong(actual, entry.getKey(), false) != number) { + throw unavailable("Signed scope fields differ from the retained preimage", null); + } + } else if (!entry.getValue().equals(actual)) { + throw unavailable("Signed scope fields differ from the retained preimage", null); + } + } + return new CanonicalJoinScopeV2( + token, + caller.accountUuid(), + target.canonicalTenantId(), + target.realmId(), + target.tenantSlug(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeService.java new file mode 100644 index 0000000000..7af715a20b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeService.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; + +/** Unregistered Account scope composition; issuance grants neither membership nor admission. */ +public final class AccountCharacterCreateScopeService { + private final String namespace; + private final AccountCharacterCreateScopeOwner accounts; + private final AccountCharacterCreatePublicSourceClient sources; + + public AccountCharacterCreateScopeService( + String namespace, + AccountCharacterCreateScopeOwner accounts, + AccountCharacterCreatePublicSourceClient sources) { + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + this.accounts = Objects.requireNonNull(accounts); + this.sources = Objects.requireNonNull(sources); + } + + public CanonicalJoinScopeV2 issue( + AccountCharacterCreatePrincipal principal, + String worldSlug, + String realmSlug, + UUID readRequestId) { + AccountCharacterCreateDelegationBindings.outsideSql(); + Objects.requireNonNull(principal).authenticateCurrentAccount(); + var target = sources.resolve(worldSlug, realmSlug, readRequestId); + if (!namespace.equals(target.response().getRequest().getTargetNamespace())) { + throw AccountCharacterCreateDelegationBindings.invalid(); + } + return accounts.issueCanonicalCharacterCreateScope(principal, target); + } + + public CanonicalJoinScopeV2 verify( + AccountCharacterCreatePrincipal principal, String opaqueScope) { + return accounts.verifyCanonicalCharacterCreateScope(principal, opaqueScope, namespace); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateService.java new file mode 100644 index 0000000000..b18f9bf393 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateService.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.time.Clock; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateRepository.Protection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Account-owned producer preparation and exact original-source reader. Preparation consumes an + * Account-verified player-bootstrap capability and revalidates it before accessing owner state. + * Deliberately has no controller, bean or routable ingress registration until genuine coupled owner + * composition is proved. + */ +public final class AccountCharacterCreateService { + private static final Set CREATION_SOURCE_READ_OWNERS = + Set.of("entity-management-service", "game-session-service", "world-management-service"); + private final AccountCharacterCreateRepository repository; + private final AccountCharacterCreateOwnerClients owners; + private final TransactionTemplate transaction; + private final String namespace; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected repository is the shared Account owner for these transactions and is not a copyable value.") + public AccountCharacterCreateService( + AccountCharacterCreateRepository repository, + AccountCharacterCreateOwnerClients owners, + PlatformTransactionManager transactions, + String namespace, + Clock clock) { + this.repository = Objects.requireNonNull(repository); + this.owners = Objects.requireNonNull(owners); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed canonical Account workload namespace required"); + } + this.namespace = namespace; + this.clock = Objects.requireNonNull(clock); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setReadOnly(false); + } + + /** + * Retains the exact resolved source first, then protects Account and delegates. A return only + * means delegation was submitted; only Entity's genuine immutable terminal can prove commit or + * abort. Missing peers fail unavailable, leaving any committed protection pending genuine + * authenticated immutable Entity terminal evidence. + */ + public void submit( + AccountCharacterCreatePrincipal principal, + UUID createCharacterRequestId, + String connectScopeId) { + requireOutsideTransaction(); + if (principal == null) { + throw Status.UNAUTHENTICATED + .withDescription("Authenticated player-bootstrap principal required") + .asRuntimeException(); + } + UUID accountId = Objects.requireNonNull(principal.authenticateCurrentAccount()); + AccountCharacterCreateIntent.requireId(createCharacterRequestId); + AccountCharacterCreateIntent.requireConnectScope(connectScopeId); + + AccountCharacterCreateIntent original = + transaction.execute( + status -> + repository + .findOriginal(namespace, accountId, createCharacterRequestId) + .orElse(null)); + if (original == null) { + var source = + Objects.requireNonNull( + owners.resolvePublicProduction(namespace, principal, connectScopeId), + "Genuine resolved owner source required"); + var candidate = + new AccountCharacterCreateIntent( + UUID.randomUUID(), + createCharacterRequestId, + connectScopeId, + accountId, + source.actionBytes(), + CharacterCreateOperatorActionCodec.mutationDigest(source.actionBytes()), + source.originalSourceReadback()); + if (!namespace.equals(candidate.targetNamespace())) throw denied(); + original = + Objects.requireNonNull(transaction.execute(status -> repository.retain(candidate))); + } + if (!accountId.equals(original.accountId()) + || !createCharacterRequestId.equals(original.createCharacterRequestId()) + || !connectScopeId.equals(original.connectScopeId()) + || !namespace.equals(original.targetNamespace())) throw denied(); + + // A fresh transaction proves the full retained winner is committed before any owner hold. + AccountCharacterCreateIntent exact = original; + AccountCharacterCreateIntent readback = + Objects.requireNonNull( + transaction.execute( + status -> repository.findOperation(namespace, exact.operationId()).orElseThrow())); + if (!exact.sameBinding(readback)) throw denied(); + owners.requireExactOriginalSource(readback); + requireUnexpired(readback); + if (!accountId.equals(principal.authenticateCurrentAccount())) throw denied(); + Protection acquired = + Objects.requireNonNull(transaction.execute(status -> repository.acquire(readback))); + Protection committed = + Objects.requireNonNull( + transaction.execute(status -> repository.findProtection(readback).orElseThrow())); + if (!acquired.sameBinding(committed)) throw denied(); + requireUnexpired(readback); + if (!accountId.equals(principal.authenticateCurrentAccount())) throw denied(); + owners.delegateProtected(readback, committed); + } + + /** Exact original intent read, qualified by a creation owner's actual same-namespace peer. */ + public AccountCharacterCreateIntent readOriginalForOwner( + UUID operationId, String mutationDigest) { + requireCreationOwnerPeer(); + requireOutsideTransaction(); + AccountCharacterCreateIntent.requireId(operationId); + AccountCharacterCreateIntent retained = + Objects.requireNonNull( + transaction.execute( + status -> repository.findOperation(namespace, operationId).orElseThrow())); + if (!retained.mutationDigest().equals(mutationDigest)) throw denied(); + return retained; + } + + /** Historical protection read for reconciliation; it makes no expiry or terminal inference. */ + public Protection readProtectionForOwner( + UUID operationId, String mutationDigest, UUID protectionId, long protectionFence) { + AccountCharacterCreateIntent retained = readOriginalForOwner(operationId, mutationDigest); + Protection protection = + Objects.requireNonNull( + transaction.execute(status -> repository.findProtection(retained).orElseThrow())); + if (!protection.protectionId().equals(protectionId) + || protection.protectionFence() != protectionFence) throw denied(); + return protection; + } + + private void requireUnexpired(AccountCharacterCreateIntent intent) { + if (!clock.instant().isBefore(intent.action().expectedVersion().connectScopeExpiresAt())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Original CHARACTER_CREATE authority expired; protection remains pending") + .asRuntimeException(); + } + } + + private void requireCreationOwnerPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !namespace.equals(peer.namespace()) + || !CREATION_SOURCE_READ_OWNERS.contains(peer.service()) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) throw denied(); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("CHARACTER_CREATE must own its Account transactions"); + } + } + + private static RuntimeException denied() { + return Status.PERMISSION_DENIED + .withDescription("Exact authenticated CHARACTER_CREATE binding required") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSettlementService.java new file mode 100644 index 0000000000..7475bc434c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSettlementService.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered original-only reconciliation. Expiry, absence and transport failure never settle. + */ +public final class AccountCharacterCreateSettlementService { + private final AccountCharacterCreateRepository repository; + private final AccountCharacterCreateEntityClient entity; + private final TransactionTemplate transaction; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected repository is the shared Account owner for settlement transactions and is not a copyable value.") + public AccountCharacterCreateSettlementService( + AccountCharacterCreateRepository repository, + AccountCharacterCreateEntityClient entity, + PlatformTransactionManager manager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.entity = Objects.requireNonNull(entity); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(manager)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setTimeout(10); + } + + public EntityCharacterCreateTerminal reconcile(UUID operation, String mutationDigest) { + AccountCharacterCreateDelegationBindings.outsideSql(); + AccountCharacterCreateIntent.requireId(operation); + if (mutationDigest == null || !mutationDigest.matches("[0-9a-f]{64}")) { + throw AccountCharacterCreateDelegationBindings.invalid(); + } + var original = + Objects.requireNonNull( + transaction.execute( + status -> { + var intent = + repository + .findOperation(namespace, operation) + .orElseThrow(AccountCharacterCreateDelegationBindings::invalid); + if (!mutationDigest.equals(intent.mutationDigest())) + throw AccountCharacterCreateDelegationBindings.invalid(); + return repository + .findProtection(intent) + .orElseThrow(AccountCharacterCreateDelegationBindings::invalid); + })); + var retained = transaction.execute(status -> repository.findSettlement(original)); + if (retained != null && retained.isPresent()) return retained.orElseThrow(); + var account = + AccountCharacterCreateDelegationBindings.account(namespace, original.intent(), original); + // The actual authenticated Entity lookup completes before any owner lock is acquired. + var verified = entity.readVerifiedOriginalTerminal(account); + return Objects.requireNonNull( + transaction.execute(status -> repository.settle(original, verified))); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceGrpcService.java new file mode 100644 index 0000000000..5a05c55041 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceGrpcService.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.CharacterCreateSourceServiceGrpc; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Deliberately unregistered exact-purpose adapter; the owner service authenticates every read. */ +public final class AccountCharacterCreateSourceGrpcService + extends CharacterCreateSourceServiceGrpc.CharacterCreateSourceServiceImplBase { + private final AccountCharacterCreateService owner; + private final String namespace; + + public AccountCharacterCreateSourceGrpcService( + AccountCharacterCreateService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed canonical Account namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readOriginalCharacterCreate( + ReadOriginalCharacterCreateRequest request, + StreamObserver observer) { + try { + validate(request); + observer.onNext( + response( + owner.readOriginalForOwner( + id(request.getOperationId()), request.getMutationDigest()))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + + @Override + public void readOriginalCharacterCreateProtection( + ReadOriginalCharacterCreateProtectionRequest request, + StreamObserver observer) { + try { + if (!request.hasOriginal() + || !request.getUnknownFields().asMap().isEmpty() + || request.getAccountProtectionFence() <= 0L) throw invalid(); + validate(request.getOriginal()); + var protection = + owner.readProtectionForOwner( + id(request.getOriginal().getOperationId()), + request.getOriginal().getMutationDigest(), + id(request.getAccountProtectionId()), + request.getAccountProtectionFence()); + observer.onNext( + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(response(protection.intent())) + .setAccountProtectionId(protection.protectionId().toString()) + .setAccountProtectionFence(protection.protectionFence()) + .setAcquiredAt(protection.acquiredAt().toString()) + .setOriginalMembershipSnapshot(ByteString.copyFrom(protection.membershipSnapshot())) + .setOriginalEntitlementSnapshot(ByteString.copyFrom(protection.entitlementSnapshot())) + .build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + + private void validate(ReadOriginalCharacterCreateRequest request) { + if (!namespace.equals(request.getTargetNamespace()) + || !request.getUnknownFields().asMap().isEmpty() + || !request.getMutationDigest().matches("[0-9a-f]{64}")) throw invalid(); + id(request.getOperationId()); + } + + private static UUID id(String value) { + try { + UUID id = UUID.fromString(value); + AccountCharacterCreateIntent.requireId(id); + if (!id.toString().equals(value)) throw invalid(); + return id; + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + private static ReadOriginalCharacterCreateResponse response(AccountCharacterCreateIntent intent) { + return ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(intent.targetNamespace()) + .setOperationId(intent.operationId().toString()) + .setCreateCharacterRequestId(intent.createCharacterRequestId().toString()) + .setConnectScopeId(intent.connectScopeId()) + .setAuthenticatedAccountId(intent.accountId().toString()) + .setPurpose(AccountCharacterCreateIntent.PURPOSE) + .setOriginalAction(ByteString.copyFrom(intent.actionBytes())) + .setMutationDigest(intent.mutationDigest()) + .setOriginalSourceReadback(ByteString.copyFrom(intent.originalSourceReadback())) + .build(); + } + + private static RuntimeException invalid() { + return Status.INVALID_ARGUMENT + .withDescription("Exact original CHARACTER_CREATE read binding required") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolver.java new file mode 100644 index 0000000000..0b2edbc8f2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolver.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.Status; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import tools.jackson.databind.json.JsonMapper; + +/** Unregistered source composition; owner protection and Entity delegation remain separate. */ +public final class AccountCharacterCreateSourceResolver + implements AccountCharacterCreateOwnerClients { + private final String namespace; + private final AccountCharacterCreateScopeService scopes; + private final AccountCharacterCreatePublicSourceClient sources; + + public AccountCharacterCreateSourceResolver( + String namespace, + AccountCharacterCreateScopeService scopes, + AccountCharacterCreatePublicSourceClient sources) { + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + this.scopes = Objects.requireNonNull(scopes); + this.sources = Objects.requireNonNull(sources); + } + + @Override + public ResolvedSource resolvePublicProduction( + String requestedNamespace, AccountCharacterCreatePrincipal principal, String opaqueScope) { + AccountCharacterCreateDelegationBindings.outsideSql(); + if (!namespace.equals(requestedNamespace) || principal == null) throw invalid(); + UUID account = Objects.requireNonNull(principal.authenticateCurrentAccount()); + var scope = Objects.requireNonNull(scopes.verify(principal, opaqueScope)); + if (!account.equals(scope.accountId()) + || !opaqueScope.equals(scope.connectScopeId()) + || !"SHARED".equals(scope.playableStateScope())) throw invalid(); + var request = + ReadCharacterCreatePublicSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(UUID.randomUUID().toString()) + .setTargetNamespace(namespace) + .setCanonicalTenantId(scope.tenantId().toString()) + .setRealmId(scope.realmId().toString()) + .setWorldSlug(scope.worldSlug()) + .setRealmSlug(scope.realmSlug()) + .setPlayableStateNamespaceId(scope.playableStateNamespaceId().toString()) + .setPlayableStateScope(scope.playableStateScope()) + .setCanonicalGameInstanceId(scope.gameInstanceId().toString()) + .setCatalogRevision(scope.catalogRevision()) + .setPointerVersion(scope.pointerVersion()) + .setEvaluatedAt(scope.evaluatedAt()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) + .build(); + var source = Objects.requireNonNull(sources.read(request)); + var response = Objects.requireNonNull(source.response()); + if (!request.equals(response.getRequest()) + || !scope.tenantSlug().equals(response.getCatalog().getTenantSlug())) throw invalid(); + byte[] action = action(response, account); + return new ResolvedSource(action, response.toByteArray()); + } + + @Override + public void requireExactOriginalSource(AccountCharacterCreateIntent intent) { + AccountCharacterCreateDelegationBindings.outsideSql(); + if (!namespace.equals(intent.targetNamespace())) throw invalid(); + byte[] retained = intent.originalSourceReadback(); + ReadCharacterCreatePublicSourceResponse original; + try { + original = ReadCharacterCreatePublicSourceResponse.parseFrom(retained); + } catch (InvalidProtocolBufferException malformed) { + throw invalid(); + } + if (!Arrays.equals(retained, original.toByteArray()) + || !Arrays.equals(intent.actionBytes(), action(original, intent.accountId()))) + throw invalid(); + var current = Objects.requireNonNull(sources.read(original.getRequest())).response(); + if (!Arrays.equals(retained, current.toByteArray())) throw invalid(); + // Decode the actual reread as well; no new scope, target, clock or expiry is introduced. + if (!Arrays.equals(intent.actionBytes(), action(current, intent.accountId()))) throw invalid(); + } + + @Override + public void delegateProtected( + AccountCharacterCreateIntent intent, AccountCharacterCreateRepository.Protection protection) { + throw Status.UNAVAILABLE + .withDescription("CHARACTER_CREATE source resolver supplies no owner delegation") + .asRuntimeException(); + } + + /** Rebuilds the exact action only from the complete closed owner source and original selector. */ + private byte[] action(ReadCharacterCreatePublicSourceResponse response, UUID account) { + var request = response.getRequest(); + var catalog = response.getCatalog(); + var pointer = response.getPointer(); + if (!response.getUnknownFields().asMap().isEmpty() + || !request.getUnknownFields().asMap().isEmpty() + || !catalog.getUnknownFields().asMap().isEmpty() + || !pointer.getUnknownFields().asMap().isEmpty() + || response.getSchemaVersion() != 1 + || request.getSchemaVersion() != 1 + || response.getSerializedSize() + > AccountCharacterCreatePublicSourceClient.MAX_SOURCE_WIRE_BYTES + || !namespace.equals(request.getTargetNamespace()) + || !"SHARED".equals(request.getPlayableStateScope()) + || !response.hasAuthoredSource() + || response.getWorldLifecycleEvidence().isEmpty() + || !request.getCanonicalTenantId().equals(catalog.getTenantId()) + || !request.getRealmId().equals(catalog.getRealmId()) + || !request.getWorldSlug().equals(catalog.getWorldSlug()) + || !request.getRealmSlug().equals(catalog.getRealmSlug()) + || !request.getPlayableStateNamespaceId().equals(catalog.getPlayableStateNamespaceId()) + || request.getCatalogRevision() != catalog.getCatalogRevision() + || !request.getCanonicalTenantId().equals(pointer.getTenantId()) + || !request.getRealmId().equals(pointer.getRealmId()) + || !request.getWorldSlug().equals(pointer.getWorldSlug()) + || !request.getRealmSlug().equals(pointer.getRealmSlug()) + || !request.getCanonicalGameInstanceId().equals(pointer.getAdmissibleGameInstanceId()) + || request.getCatalogRevision() != pointer.getCatalogRevision() + || request.getPointerVersion() != pointer.getPointerVersion() + || response.getActiveLifecycleEpoch() <= 0 + || response.getOriginalOwnerFence() <= 0) throw invalid(); + AccountCharacterCreateDelegationBindings.id(request.getReadRequestId()); + AccountCharacterCreateDelegationBindings.id(catalog.getCreationRequestId()); + AccountCharacterCreateDelegationBindings.instant(request.getEvaluatedAt()); + AccountCharacterCreateDelegationBindings.instant(request.getConnectScopeExpiresAt()); + AccountCharacterCreateDelegationBindings.instant(pointer.getUpdatedAt()); + if (!Instant.parse(request.getEvaluatedAt()) + .isBefore(Instant.parse(request.getConnectScopeExpiresAt()))) throw invalid(); + if (!catalog.getReceiptDigest().matches("sha256:[0-9a-f]{64}") + || pointer.getInitialAdmissionRequestId().isBlank() + || !pointer.getInitialAdmissionOwnerProofDigest().matches("sha256:[0-9a-f]{64}") + || !pointer.getAdmissionPointerSnapshotDigest().matches("[0-9a-f]{64}")) throw invalid(); + var authored = + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + response.getAuthoredSource().getRequest()), + response.getAuthoredSource()); + var world = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getWorldLifecycleEvidence().toByteArray()); + var association = authored.associationRead().association(); + var lifecycle = world.request(); + if (!namespace.equals(authored.request().targetNamespace()) + || !response + .getOriginalOwnerAttemptId() + .equals(authored.request().ownerAttemptId().toString()) + || response.getOriginalOwnerFence() != authored.request().ownerFence() + || !response + .getOriginalControlPlaneRequestId() + .equals(authored.request().decodedTuple().controlPlaneRequestId()) + || !authored.descriptor().equals(world.launchBinding().descriptor()) + || !association + .publishWorkflowId() + .equals(world.launchBinding().releaseAttestation().publishWorkflowId()) + || !association + .selectedCommitId() + .toString() + .equals(world.launchBinding().releaseAttestation().commitId()) + || !request.getCanonicalTenantId().equals(association.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(association.worldSlug()) + || !response.getCanonicalVersionId().equals(association.canonicalVersionId().toString()) + || !namespace.equals(lifecycle.targetNamespace()) + || !request.getCanonicalTenantId().equals(lifecycle.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(lifecycle.worldSlug()) + || !request + .getCanonicalGameInstanceId() + .equals(lifecycle.canonicalGameInstanceId().toString()) + || !request + .getPlayableStateNamespaceId() + .equals(lifecycle.playableStateNamespaceId().toString()) + || !response.getCanonicalVersionId().equals(lifecycle.canonicalVersionId().toString()) + || !response.getOriginalControlPlaneRequestId().equals(lifecycle.controlPlaneRequestId()) + || !"SHARED".equals(lifecycle.playableStateScope()) + || !lifecycle.publicProduction() + || !"ACTIVE".equals(world.lifecycleStatus()) + || response.getActiveLifecycleEpoch() != world.lifecycleEpoch()) throw invalid(); + var json = JsonMapper.builder().build(); + var selected = + authored.projections().stream() + .filter( + projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), json) + .realmSlug() + .equals(request.getRealmSlug())) + .toList(); + if (selected.size() != 1) throw invalid(); + var projection = selected.getFirst(); + var policy = projection.policy(); + var raw = + new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + namespace, + request.getCanonicalTenantId(), + request.getPlayableStateNamespaceId(), + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + account.toString(), + request.getRealmId(), + request.getWorldSlug(), + request.getRealmSlug(), + request.getCanonicalGameInstanceId(), + response.getCanonicalVersionId()), + new CharacterCreateOperatorAction.ExpectedVersion( + Long.toString(request.getCatalogRevision()), + Long.toString(request.getPointerVersion()), + Long.toString(response.getActiveLifecycleEpoch()), + Instant.parse(request.getEvaluatedAt()), + Instant.parse(request.getConnectScopeExpiresAt())), + new CharacterCreateOperatorAction.Mutation( + "CHARACTER_CREATE", + "PLAYER_CREATED", + new CharacterCreateOperatorAction.Catalog( + catalog.getTenantId(), + catalog.getTenantSlug(), + catalog.getWorldSlug(), + catalog.getWorldDisplayName(), + catalog.getRealmId(), + catalog.getRealmSlug(), + catalog.getRealmDisplayName(), + catalog.getVisible(), + catalog.getPublicProduction(), + catalog.getStateScope(), + catalog.getPlayableStateNamespaceId(), + catalog.getCharacterCreationPolicy(), + Long.toString(catalog.getCatalogRevision())), + new CharacterCreateOperatorAction.Pointer( + pointer.getTenantId(), + pointer.getRealmId(), + pointer.getWorldSlug(), + pointer.getRealmSlug(), + pointer.getAdmissionState(), + pointer.getAdmissibleGameInstanceId(), + Long.toString(pointer.getPointerVersion()), + Long.toString(pointer.getCatalogRevision()), + Instant.parse(pointer.getUpdatedAt())), + new CharacterCreateOperatorAction.AuthoredSource( + AuthoredInitialActorCoreProjection.SCHEMA, + projection.bindingId().toString(), + projection.bindingDigest(), + projection.canonicalTenantId().toString(), + projection.canonicalVersionId().toString(), + projection.worldSourceOperationId().toString(), + projection.worldSourceEvidenceDigest(), + projection.worldSlug(), + projection.publicationWorkflowId(), + projection.selectedCommitId().toString(), + projection.selectedCommitDigest(), + new CharacterCreateOperatorAction.Policy( + policy.commitId().toString(), + policy.revisionId().toString(), + policy.logicalRevisionId(), + policy.canonicalJson(), + policy.contentDigest()), + new CharacterCreateOperatorAction.Core(projection.core().canonicalJson()), + new CharacterCreateOperatorAction.Descriptor( + projection.descriptor().canonicalJson(), projection.descriptor().digest()), + rule(projection.disposition()), + rule(projection.safeFeedback())), + "{}"), + CharacterCreateOperatorAction.AuditReason.ABSENT); + return CharacterCreateOperatorActionCodec.encode(raw); + } + + private static CharacterCreateOperatorAction.Rule rule( + AuthoredInitialActorCoreProjection.RuleDefinition rule) { + return new CharacterCreateOperatorAction.Rule( + rule.key(), + rule.definitionJson(), + rule.definitionDigest(), + rule.sourceCommitId().toString(), + rule.sourceCommitDigest(), + rule.revisionId().toString(), + rule.revisionOrder()); + } + + private static RuntimeException invalid() { + return AccountCharacterCreateDelegationBindings.invalid(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateWorldClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateWorldClient.java new file mode 100644 index 0000000000..9e8983bae8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateWorldClient.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.AcquireCharacterCreateLifecycleProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.CharacterCreateLifecycleServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalCharacterCreateLifecycleProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; + +/** + * Unregistered certificate-only Account client; every call uses its exact owner server identity. + */ +public final class AccountCharacterCreateWorldClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceBlockingStub> { + private final String namespace; + + public AccountCharacterCreateWorldClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account CHARACTER_CREATE lifecycle"), + channels, + AccountCharacterCreateWorldClient.class); + this.namespace = AccountCharacterCreateDelegationBindings.namespace(namespace); + } + + public void init() throws IOException { + initOnce("Creation lifecycle client is closed", "Creation lifecycle client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + return CharacterCreateLifecycleServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public WorldCharacterCreateLifecycleProtection acquireAndReadOriginal( + ReadOriginalCharacterCreateProtectionResponse account) { + requireNoAmbientSql("World creation calls require no ambient Account transaction"); + AccountCharacterCreateDelegationBindings.requireAccount(namespace, account); + var selector = AccountCharacterCreateDelegationBindings.selector(account); + var acquired = + calls() + .acquireCharacterCreateLifecycleProtection( + AcquireCharacterCreateLifecycleProtectionRequest.newBuilder() + .setAccountProtection(selector) + .build()); + AccountCharacterCreateDelegationBindings.world(account, acquired); + var readback = + calls() + .readOriginalCharacterCreateLifecycleProtection( + ReadOriginalCharacterCreateLifecycleProtectionRequest.newBuilder() + .setAccountProtection(selector) + .setWorldProtectionId(acquired.getWorldProtectionId()) + .setWorldProtectionFence(acquired.getWorldProtectionFence()) + .build()); + AccountCharacterCreateDelegationBindings.world(account, readback); + if (!acquired.equals(readback)) throw AccountCharacterCreateDelegationBindings.invalid(); + return readback; + } + + private CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceBlockingStub calls() { + return requireInitializedStub("Creation lifecycle client is not initialized") + .withMaxInboundMessageSize(AccountCharacterCreateDelegationBindings.MAX_PROTECTION_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java index 271941bd4b..ebebd179dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java @@ -30,7 +30,8 @@ public class GameSessionClient private static final String ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE = "Gameplay routing authority unavailable; retry later"; private static final String ADMISSION_POINTER_UNAVAILABLE_MESSAGE = - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"; + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying" + + " gameplay entry"; public GameSessionClient( ServiceEndpointsProperties endpoints, @@ -102,17 +103,11 @@ public GameplayAdmissionPointer getAdmissionPointer( .build()); if (response.hasError()) { String code = response.getError().getCode(); - if ("INTERNAL".equals(code) - || "UNAVAILABLE".equals(code) - || "DEADLINE_EXCEEDED".equals(code)) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE); - } if ("INVALID_ARGUMENT".equals(code) || "NOT_FOUND".equals(code)) { throw new AuthenticationException( "ADMISSION_POINTER_UNAVAILABLE", ADMISSION_POINTER_UNAVAILABLE_MESSAGE); } - throw new IllegalStateException("Admission pointer lookup failed: " + code); + throw discoveryFailure("Admission pointer lookup failed", code); } return response.getAdmissionPointer(); } catch (StatusRuntimeException ex) { @@ -125,9 +120,16 @@ private GameSessionServiceGrpc.GameSessionServiceBlockingStub callStub() { } private static RuntimeException discoveryFailure(String operation, String code) { - if ("INTERNAL".equals(code) || "UNAVAILABLE".equals(code) || "DEADLINE_EXCEEDED".equals(code)) { + if ("AUTH_UNAVAILABLE".equals(code) + || "INTERNAL".equals(code) + || "UNAVAILABLE".equals(code) + || "DEADLINE_EXCEEDED".equals(code)) { return new AuthenticationException("AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE); } + if ("ADMISSION_POINTER_UNAVAILABLE".equals(code)) { + return new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", ADMISSION_POINTER_UNAVAILABLE_MESSAGE); + } return new IllegalStateException(operation + ": " + code); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java index baee06d334..644d6fdcb3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java @@ -156,7 +156,7 @@ BindableService accountPlayerAdmissionEntitlementReceiver( transactions, Clock.systemUTC(), namespace); - return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace)::bindProtectedService; + return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace)::bindService; } @Bean diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfiguration.java new file mode 100644 index 0000000000..8e77e0a9dc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfiguration.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +/** + * Explicit isolated receiving only. Requires an independently composed genuine Account source + * owner; creates no source, credential, entitlement, admission or deployment authority. The server + * must supply TLS client certificates and the receiver's bounded wire policy. + */ +@Configuration(proxyBeanMethods = false) +@Profile("isolated-player-admission-receiving") +@ConditionalOnProperty( + prefix = "firemud.account.player-admission-receiving", + name = "enabled", + havingValue = "true") +public class AccountPlayerAdmissionReceivingConfiguration { + @Bean + AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementReceiver( + AccountPlayerAdmissionEntitlementOwner owner, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java index 256a95eb9c..a98e355bfc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java @@ -1,10 +1,9 @@ package net.firedevops.firemud.accountservice.controller; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; -import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.ApiResponse; import net.firedevops.firemud.common.security.SessionContext; import org.springframework.http.ResponseEntity; @@ -18,30 +17,13 @@ @RestController @RequestMapping("/internal/runtime") public class InternalRuntimeController { - private final AccountService accountService; - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "AccountService is injected and not exposed") - public InternalRuntimeController(AccountService accountService) { - this.accountService = accountService; - } - @PostMapping("/realm-access-grants") public ResponseEntity> grantRealmAccess( @Valid @RequestBody RealmAccessGrantRequest request) { SessionContext.requireGlobalPrivilegedRole(); - RealmAccessGrantRequest normalizedRequest = - new RealmAccessGrantRequest( - AccountRequestReaders.requireAccountId(request.accountId()), - AccountRequestReaders.requireTenantId(request.tenantId()), - request.worldSlug(), - request.realmSlug(), - request.grantedBy(), - request.grantReason(), - request.requestId()); - return ResponseEntity.ok( - ApiResponse.success(accountService.grantRealmAccess(normalizedRequest))); + AccountRequestReaders.requireAccountId(request.accountId()); + AccountRequestReaders.requireTenantId(request.tenantId()); + throw grantMutationUnavailable(); } @DeleteMapping("/realm-access-grants") @@ -51,11 +33,13 @@ public ResponseEntity> revokeRealmAccess( @RequestParam("worldSlug") String worldSlug, @RequestParam("realmSlug") String realmSlug) { SessionContext.requireGlobalPrivilegedRole(); - accountService.revokeRealmAccess( - AccountRequestReaders.requireAccountId(accountId), - AccountRequestReaders.requireTenantId(tenantId), - worldSlug, - realmSlug); - return ResponseEntity.ok(ApiResponse.success(null)); + AccountRequestReaders.requireAccountId(accountId); + AccountRequestReaders.requireTenantId(tenantId); + throw grantMutationUnavailable(); + } + + private static AuthenticationException grantMutationUnavailable() { + return new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBinding.java new file mode 100644 index 0000000000..3ba520cb63 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBinding.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Exact caller-bound LEAVE intent. This value is not caller authentication or authority. */ +public record AccountLeaveMembershipBinding( + String requestId, UUID accountId, UUID tenantId, String callerBinding) { + public AccountLeaveMembershipBinding { + requireUuid(accountId); + requireUuid(tenantId); + requireText(requestId, 256); + requireText(callerBinding, 512); + } + + public String digest() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + for (String value : + new String[] { + "account-leave-membership/v1", + "LEAVE", + requestId, + accountId.toString(), + tenantId.toString(), + callerBinding + }) { + byte[] encoded = utf8(value); + bytes.writeBytes(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + bytes.write(':'); + bytes.writeBytes(encoded); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical LEAVE account and tenant UUIDs required"); + } + } + + private static void requireText(String value, int maxCodePoints) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > maxCodePoints + || value.indexOf(0) >= 0) { + throw new IllegalArgumentException("Bounded exact LEAVE request and caller binding required"); + } + utf8(value); + } + + private static byte[] utf8(String value) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("LEAVE binding requires well-formed Unicode", exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java index ef46d7fda0..c6de02b371 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java @@ -7,7 +7,6 @@ public record ConnectTokenResponse( long gameInstanceId, String realmSlug, String connectScopeId, - String jti, String requestId, String issuedAt, String expiresAt, @@ -20,7 +19,6 @@ public static ConnectTokenResponse from(ConnectTokenResult result) { result.gameInstanceId(), result.realmSlug(), result.connectScopeId(), - result.jti(), result.requestId(), result.issuedAt(), result.expiresAt(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java index 252f469df5..779c015cca 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -433,6 +434,37 @@ public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exa return new CanonicalIssuerSourceSnapshot(current, latest); } + /** Reads the exact retained issuer event with the verified current source in one transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalIssuerEventReadback readExactCanonicalIssuerEvent( + String exactIssuerId, long sequence, String expectedEventId, String expectedEventDigest) { + if (!ACCOUNT_ISSUER.equals(exactIssuerId) || sequence <= 0L) { + throw new SourceEvidenceUnavailableException(); + } + CanonicalIssuerSourceSnapshot current = readCurrentCanonicalIssuerSource(exactIssuerId); + SourceCheckpoint checkpoint = current.source().checkpoint(); + if (sequence > checkpoint.sequence()) { + throw new SourceEvidenceUnavailableException(); + } + Event stored = + outbox + .findEvent(checkpoint.outboxStreamKey(), sequence) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (stored.outboxSequence() != sequence + || !stored.outboxStreamKey().equals(checkpoint.outboxStreamKey()) + || !stored.eventId().equals(expectedEventId) + || !stored.eventDigest().equals(expectedEventDigest)) { + throw new SourceEvidenceUnavailableException(); + } + IssuerEvent selected = verifyIssuerEvent(stored, current.source().scope()); + String retainedSourcePosition = Long.toString(sequence + 1L); + if (!retainedSourcePosition.equals(selected.issuerAuthGeneration()) + || !retainedSourcePosition.equals(selected.sourceVersion())) { + throw new SourceEvidenceUnavailableException(); + } + return new CanonicalIssuerEventReadback(current, selected); + } + /** Records an explicit issuer-wide mutation with exact event readback and no Account cutoff. */ @Transactional(propagation = Propagation.MANDATORY) public CurrentSourceEvidence appendIssuerAuthorityChange( @@ -477,7 +509,11 @@ public CurrentSourceEvidence appendIssuerAuthorityChange( outbox .findEvent(streamKey, expectedSequence(expected)) .orElseThrow(() -> new SourceEvidenceUnavailableException()); - IssuerEvent verified = verifyIssuerEvent(readback, scope, advanced); + IssuerEvent verified = verifyIssuerEvent(readback, scope); + if (advanced.generation() != Long.parseLong(verified.issuerAuthGeneration()) + || advanced.sourceVersion() != Long.parseLong(verified.sourceVersion())) { + throw new SourceEvidenceUnavailableException(); + } updateSourceHead(before, verified, advanced, null); return readCurrentSource(scope, advanced); } @@ -586,10 +622,40 @@ private CurrentSourceEvidence readCurrentSource( IssuanceFence fence = authority.issuanceFence(); if (scope.kind() == ScopeKind.ACCOUNT) { if (fence == null - || positive(source, "current_issuance_fence") != fence.value() - || positive(source, "current_issuance_fence_source_version") != fence.sourceVersion()) { + || positive(source, "current_issuance_fence") > fence.value() + || positive(source, "current_issuance_fence_source_version") > fence.sourceVersion()) { throw new SourceEvidenceUnavailableException(); } + // Security history keeps its own immutable event fence. Membership invalidation can + // advance the composite fence only with independently validated causal provenance. + Record provenanceTable = + dsl.fetchOne("SELECT to_regclass('account_issuance_fence_provenance')"); + if (provenanceTable == null || provenanceTable.get(0) == null) { + // Historical migration fixtures retain the exact pre-cutover V40 equality contract. + if (positive(source, "current_issuance_fence") != fence.value() + || positive(source, "current_issuance_fence_source_version") != fence.sourceVersion()) { + throw new SourceEvidenceUnavailableException(); + } + } else { + // A closed security append checks its immutable before-image after its exact CAS. + // That private path verifies the pending event immediately below; it must not present + // the predecessor as current authority or relax the ordinary current-snapshot helper. + String query = + allowOnePendingAppend + ? "SELECT EXISTS (SELECT 1 FROM account_issuance_fence_provenance p " + + "JOIN account_authority_issuance_fences f USING (account_uuid) " + + "WHERE p.account_uuid = ? AND p.issuance_fence = ? AND p.source_version = ? " + + "AND f.issuance_fence = p.issuance_fence + 1 AND f.source_version = p.source_version + 1 " + + "AND (p.event_sequence = 0 OR EXISTS (SELECT 1 FROM account_authority_outbox_events e " + + "WHERE (e.outbox_stream_key,e.outbox_sequence,e.event_id,e.event_digest) " + + "= (p.source_stream_key,p.event_sequence,p.event_id,p.event_digest))))" + : "SELECT account_has_current_fence_provenance(?, ?, ?)"; + Record provenance = + dsl.fetchOne(query, scope.accountId(), fence.value(), fence.sourceVersion()); + if (provenance == null || !Boolean.TRUE.equals(provenance.get(0, Boolean.class))) { + throw new SourceEvidenceUnavailableException(); + } + } } else if (fence != null) { throw new SourceEvidenceUnavailableException(); } @@ -898,6 +964,56 @@ private void updateSourceHead( AccountSecurityCutoff cutoff, ScopeState advanced, IssuanceFence advancedFence) { + // The source head owns its last security-event fence, not necessarily the live composite + // before-fence. Lock and compare that exact independently sequenced source position. + Record sourcePosition = + dsl.fetchOne( + "SELECT current_issuance_fence, current_issuance_fence_source_version FROM " + + SOURCE_TABLE + + " WHERE outbox_stream_key = ? AND current_generation = ? AND current_source_version = ? " + + "AND last_outbox_sequence = ? AND last_event_id IS NOT DISTINCT FROM ? " + + "AND last_event_digest IS NOT DISTINCT FROM ? FOR UPDATE", + before.checkpoint().outboxStreamKey(), + before.generation(), + before.sourceVersion(), + before.checkpoint().sequence(), + before.checkpoint().sourceEventId().orElse(null), + before.checkpoint().sourceEventDigest().orElse(null)); + if (sourcePosition == null) throw new SourceEvidenceUnavailableException(); + Long sourceFence = sourcePosition.get("current_issuance_fence", Long.class); + Long sourceFenceVersion = + sourcePosition.get("current_issuance_fence_source_version", Long.class); + if (before.issuanceFence() == null) { + if (sourceFence != null || sourceFenceVersion != null) + throw new SourceEvidenceUnavailableException(); + } else { + if (sourceFence == null + || sourceFenceVersion == null + || sourceFence <= 0 + || sourceFenceVersion <= 0 + || sourceFence > before.issuanceFence().value() + || sourceFenceVersion > before.issuanceFence().sourceVersion()) { + throw new SourceEvidenceUnavailableException(); + } + Record table = dsl.fetchOne("SELECT to_regclass('account_issuance_fence_provenance')"); + if (table != null && table.get(0) != null) { + Record matches = + dsl.fetchOne( + "SELECT account_fence_security_position_matches(?, ?, ?, ?, ?, ?, ?)", + before.scope().accountId(), + sourceFence, + sourceFenceVersion, + before.checkpoint().outboxStreamKey(), + before.checkpoint().sequence(), + before.checkpoint().sourceEventId().orElse(null), + before.checkpoint().sourceEventDigest().orElse(null)); + if (matches == null || !Boolean.TRUE.equals(matches.get(0, Boolean.class))) + throw new SourceEvidenceUnavailableException(); + } else if (sourceFence != before.issuanceFence().value() + || sourceFenceVersion != before.issuanceFence().sourceVersion()) { + throw new SourceEvidenceUnavailableException(); + } + } Record changed = dsl.fetchOne( "UPDATE " @@ -925,8 +1041,8 @@ private void updateSourceHead( before.generation(), before.sourceVersion(), before.checkpoint().sequence(), - before.issuanceFence() == null ? null : before.issuanceFence().value(), - before.issuanceFence() == null ? null : before.issuanceFence().sourceVersion()); + sourceFence, + sourceFenceVersion); if (changed == null || positive(changed, "current_generation") != advanced.generation()) { throw new SourceEvidenceUnavailableException(); } @@ -982,11 +1098,15 @@ private static AccountEvent verifyAccountEvent( return account; } - private static IssuerEvent verifyIssuerEvent( - Event event, AuthorityScope scope, ScopeState state) { - SourceEvent verified = - AccountAuthoritySourceEventV1Codec.verify( - new String(event.payload(), StandardCharsets.UTF_8)); + private static IssuerEvent verifyIssuerEvent(Event event, AuthorityScope scope) { + byte[] payload = event.payload(); + final SourceEvent verified; + try { + verified = + AccountAuthoritySourceEventV1Codec.verify(new String(payload, StandardCharsets.UTF_8)); + } catch (IllegalArgumentException malformed) { + throw new SourceEvidenceUnavailableException(); + } if (!(verified instanceof IssuerEvent issuer) || !issuer.issuerId().equals(scope.issuerId()) || !event.eventId().equals(issuer.eventId()) @@ -994,8 +1114,7 @@ private static IssuerEvent verifyIssuerEvent( || !event.outboxStreamKey().equals(issuer.outboxStreamKey()) || event.outboxSequence() != Long.parseLong(issuer.outboxSequence()) || !event.eventDigest().equals(issuer.eventDigest()) - || state.generation() != Long.parseLong(issuer.issuerAuthGeneration()) - || state.sourceVersion() != Long.parseLong(issuer.sourceVersion())) { + || !Arrays.equals(payload, issuer.canonicalJsonUtf8())) { throw new SourceEvidenceUnavailableException(); } return issuer; @@ -1350,6 +1469,9 @@ public record CanonicalIssuerSourceSnapshot( } } + public record CanonicalIssuerEventReadback( + CanonicalIssuerSourceSnapshot currentSnapshot, IssuerEvent selectedEvent) {} + public record IssuerAccountSourceSnapshot( CurrentSourceEvidence issuer, CurrentSourceEvidence account, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCaptureRepository.java new file mode 100644 index 0000000000..c9aaa554b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCaptureRepository.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier.Lookup; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultConnectionProvider; + +/** Manually composed Account storage for the original Connect issuance fence. */ +public final class AccountConnectIssuanceFenceCaptureRepository { + private static final String CAPTURE_FIELDS = + "issuance_fence_capture_schema, issuance_fence_capture_account_uuid, " + + "issuance_fence_capture_value, issuance_fence_capture_source_version, " + + "issuance_fence_capture_digest"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The owner supplies its internal transaction-bound DSLContext.") + public AccountConnectIssuanceFenceCaptureRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Captures the supplied owner-observed fence only if it still matches the current Account + * composite position and the exact operation is pending. The caller owns authority evaluation. + */ + public AccountConnectIssuanceFenceEvidence capture( + UUID operationId, Lookup identity, IssuanceFence expectedFence) { + AccountConnectIssuanceFenceEvidence candidate = + AccountConnectIssuanceFenceEvidence.capture(operationId, identity, expectedFence); + return inOwnerTransaction( + transaction -> { + lockCurrentFence(transaction, expectedFence); + Record operation = exactOperation(transaction, operationId, identity, true); + if (!"PENDING".equals(operation.get("status", String.class))) { + throw new IllegalStateException("Connect issuance fence requires a pending operation"); + } + Optional retained = + readCapture(operationId, identity, operation); + if (retained.isPresent()) { + if (!candidate.equals(retained.orElseThrow())) { + throw new IllegalStateException( + "Connect issuance fence was captured with different evidence"); + } + return retained.orElseThrow(); + } + Record changed = + transaction.fetchOne( + "UPDATE connect_token_issuance_operation " + + "SET issuance_fence_capture_schema=?, issuance_fence_capture_account_uuid=?, " + + "issuance_fence_capture_value=?, issuance_fence_capture_source_version=?, " + + "issuance_fence_capture_digest=? WHERE operation_id=? AND status='PENDING' " + + "AND issuance_fence_capture_schema IS NULL RETURNING " + + CAPTURE_FIELDS, + AccountConnectIssuanceFenceEvidence.SCHEMA_NAME, + expectedFence.accountId(), + expectedFence.value(), + expectedFence.sourceVersion(), + HexFormat.of().parseHex(candidate.digest()), + operationId); + if (changed == null + || !readCapture(operationId, identity, changed).equals(Optional.of(candidate))) { + throw new IllegalStateException("Connect issuance fence capture lacks exact readback"); + } + return candidate; + }); + } + + /** Reads retained historical capture evidence without asserting current Account authority. */ + public Optional read(UUID operationId, Lookup identity) { + Objects.requireNonNull(operationId); + Objects.requireNonNull(identity); + return inOwnerTransaction( + transaction -> + readCapture( + operationId, identity, exactOperation(transaction, operationId, identity, false))); + } + + private static void lockCurrentFence(DSLContext transaction, IssuanceFence expected) { + UUID account = expected.accountId(); + // Account authority writers acquire the Account row before the fence and operation rows. + Record owner = + transaction.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid=? FOR SHARE", account); + if (owner == null) { + throw new IllegalStateException("Connect issuance fence requires its exact Account"); + } + Record current = + transaction.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid=? FOR SHARE", + account); + if (current == null) { + throw new IllegalStateException("Current Account issuance fence is unavailable"); + } + IssuanceFence locked = + new IssuanceFence(account, current.get(0, Long.class), current.get(1, Long.class)); + // Use a fresh statement after any lock wait so provenance is evaluated at the locked position. + if (!expected.equals(locked) + || !Boolean.TRUE.equals( + transaction + .fetchSingle( + "SELECT account_has_current_fence_provenance(?, ?, ?)", + account, + locked.value(), + locked.sourceVersion()) + .get(0, Boolean.class))) { + throw new IllegalStateException("Current Account issuance fence differs or lacks provenance"); + } + } + + private static Record exactOperation( + DSLContext transaction, UUID operationId, Lookup identity, boolean lock) { + Record operation = + transaction.fetchOne( + "SELECT status, " + + CAPTURE_FIELDS + + " FROM connect_token_issuance_operation WHERE operation_id=? AND account_uuid=? " + + "AND tenant_uuid=? AND connect_scope_id=? AND request_id=? " + + "AND request_digest_version=? AND request_digest=?" + + (lock ? " FOR UPDATE" : ""), + operationId, + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId(), + identity.digestVersion(), + identity.requestDigest()); + if (operation == null) { + throw new IllegalStateException( + "Original Connect operation is missing or its identity differs"); + } + return operation; + } + + private static Optional readCapture( + UUID operationId, Lookup identity, Record row) { + String schema = row.get("issuance_fence_capture_schema", String.class); + UUID accountId = row.get("issuance_fence_capture_account_uuid", UUID.class); + Long value = row.get("issuance_fence_capture_value", Long.class); + Long sourceVersion = row.get("issuance_fence_capture_source_version", Long.class); + byte[] digest = row.get("issuance_fence_capture_digest", byte[].class); + if (schema == null + && accountId == null + && value == null + && sourceVersion == null + && digest == null) { + return Optional.empty(); + } + if (!AccountConnectIssuanceFenceEvidence.SCHEMA_NAME.equals(schema) + || !identity.accountId().equals(accountId) + || value == null + || sourceVersion == null + || digest == null) { + throw new IllegalStateException("Stored Connect issuance fence capture is malformed"); + } + return Optional.of( + new AccountConnectIssuanceFenceEvidence( + operationId, + identity, + new IssuanceFence(accountId, value, sourceVersion), + HexFormat.of().formatHex(digest))); + } + + private T inOwnerTransaction(Function action) { + return dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Connect issuance fence requires an existing Account transaction"); + } + return action.apply( + DSL.using(dsl.configuration().derive(new DefaultConnectionProvider(connection)))); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java new file mode 100644 index 0000000000..b45b3231c8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier.Lookup; + +/** Immutable Account-local issuance fence captured for the original Connect operation. */ +public record AccountConnectIssuanceFenceEvidence( + UUID operationId, Lookup identity, IssuanceFence fence, String digest) { + + static final String SCHEMA_NAME = "account-connect-issuance-fence/v1"; + private static final HexFormat HEX = HexFormat.of(); + + public AccountConnectIssuanceFenceEvidence { + if (!calculateDigest(operationId, identity, fence).equals(digest)) { + throw new IllegalArgumentException("Account issuance-fence capture digest does not match"); + } + } + + static AccountConnectIssuanceFenceEvidence capture( + UUID operationId, Lookup identity, IssuanceFence fence) { + return new AccountConnectIssuanceFenceEvidence( + operationId, identity, fence, calculateDigest(operationId, identity, fence)); + } + + private static String calculateDigest(UUID operationId, Lookup identity, IssuanceFence fence) { + Objects.requireNonNull(identity); + Objects.requireNonNull(fence); + if (operationId == null + || operationId.equals(new UUID(0, 0)) + || !identity.accountId().equals(fence.accountId())) { + throw new IllegalArgumentException("Exact Connect operation and fence owner are required"); + } + + // Preserve the donor domain and byte-length-framed component order for the v1 capture. + // Lookup validates UTF-8, bounds, and the sole supported request digest version before hashing. + String scopeHash = + "sha256:" + sha256(identity.connectScopeId().getBytes(StandardCharsets.UTF_8)); + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + append(preimage, SCHEMA_NAME); + append(preimage, operationId.toString()); + append(preimage, identity.accountId().toString()); + append(preimage, identity.tenantId().toString()); + append(preimage, scopeHash); + append(preimage, identity.requestId()); + append(preimage, identity.requestDigest().substring("sha256:".length())); + append(preimage, Long.toString(fence.value())); + append(preimage, Long.toString(fence.sourceVersion())); + return sha256(preimage.toByteArray()); + } + + private static void append(ByteArrayOutputStream output, String component) { + byte[] bytes = component.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String sha256(byte[] bytes) { + try { + return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepository.java new file mode 100644 index 0000000000..b869bb9c5d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepository.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, existing-only informational observation of the fresh unscoped source cut. + * + *

This does not authenticate a lookup UUID, inspect a token, produce an authority Snapshot, + * satisfy current restriction evidence, or replace captureAccount/verifyAccount. No caller or + * registration uses this component. Missing or contradictory sources never cause enrollment. + */ +public final class AccountControlUiCurrentSourceObservationRepository { + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountAuthoritySourceEvidenceRepository sources; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Retain the transaction-bound SQL context and owner repositories; these injected collaborators cannot be defensively copied.") + public AccountControlUiCurrentSourceObservationRepository( + DSLContext dsl, + AccountRepository accounts, + AccountAuthoritySourceEvidenceRepository sources) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.sources = Objects.requireNonNull(sources); + } + + /** All source reads and locks belong to this caller's one writable READ_COMMITTED transaction. */ + public Observation observeExisting(UUID lookupAccountId) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw unavailable(); + } + }); + Objects.requireNonNull(lookupAccountId); + var account = + accounts + .findByAccountUuidForUpdate(lookupAccountId) + .orElseThrow(AccountControlUiCurrentSourceObservationRepository::unavailable); + if (!lookupAccountId.equals(account.getAccountUuid()) + || account.getId() == null + || account.getId() <= 0L + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) throw unavailable(); + // Preserve the current Account/composite owner's lock order, not the obsolete donor APIs. + var current = + sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, lookupAccountId); + if (!AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER) + .equals(current.issuer().scope()) + || !AuthorityScope.account(lookupAccountId).equals(current.account().scope()) + || !lookupAccountId.equals(current.issuanceFence().accountId()) + || !current.issuanceFence().equals(current.account().issuanceFence()) + || !account.getId().equals(current.account().accountSourceNumericId()) + || !account + .getAccountUuidProvenance() + .name() + .equals(current.account().accountUuidProvenance()) + || current.canonicalIssuerProjection() == null + || current.canonicalAccountProjection() == null) throw unavailable(); + var roles = + dsl.fetchOne( + "SELECT account_uuid,account_uuid_source_numeric_id,account_uuid_provenance," + + "global_roles,global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid=? FOR SHARE", + lookupAccountId); + if (roles == null + || !lookupAccountId.equals(roles.get("account_uuid", UUID.class)) + || !account.getId().equals(roles.get("account_uuid_source_numeric_id", Long.class)) + || !account + .getAccountUuidProvenance() + .name() + .equals(roles.get("account_uuid_provenance", String.class))) { + throw unavailable(); + } + String[] values = roles.get("global_roles", String[].class); + Long version = roles.get("global_role_source_version", Long.class); + if (values == null || values.length != 0 || version == null || version <= 0L) + throw unavailable(); + return new Observation(lookupAccountId, current, version); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Existing unscoped Account source observation unavailable"); + } + + /** Owner-minted informational values only, deliberately incompatible with authorization types. */ + public static final class Observation { + private final UUID accountId; + private final IssuerAccountSourceSnapshot sources; + private final long globalRoleSourceVersion; + + private Observation(UUID accountId, IssuerAccountSourceSnapshot sources, long roleVersion) { + this.accountId = accountId; + this.sources = sources; + this.globalRoleSourceVersion = roleVersion; + } + + public UUID accountId() { + return accountId; + } + + public IssuerAccountSourceSnapshot sources() { + return sources; + } + + public long globalRoleSourceVersion() { + return globalRoleSourceVersion; + } + + @Override + public String toString() { + return "AccountCurrentSourceObservation[non-authorizing]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java index 1d276df24c..69ff72c8be 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java @@ -95,8 +95,17 @@ private void checkCompletedSourceBoundary() { // These guards compare each queued row image to the current source head. Validate the // complete baseline/first result before advancing it, retaining every intermediate check. // Only source constraints run here: both category results must still commit atomically. - dsl.execute("SET CONSTRAINTS " + SOURCE_CONSTRAINTS + " IMMEDIATE"); - dsl.execute("SET CONSTRAINTS " + SOURCE_CONSTRAINTS + " DEFERRED"); + // Historical pre-cutover schemas have no composite provenance table. Preserve their exact + // original source guards; once the table exists its constraint is mandatory, never optional. + Record provenance = + dsl.fetchSingle( + "SELECT to_regclass(quote_ident(current_schema()) || '.account_issuance_fence_provenance')"); + String constraints = SOURCE_CONSTRAINTS; + if (provenance.get(0) != null) { + constraints += ", account_fence_provenance_consistent"; + } + dsl.execute("SET CONSTRAINTS " + constraints + " IMMEDIATE"); + dsl.execute("SET CONSTRAINTS " + constraints + " DEFERRED"); } private Result readResult(Record enrollment) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java index 4bde3ac4ba..7f8a533d4e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -229,6 +229,7 @@ Current readCurrentPublicProductionNew( } else { lockExactAccountFirst(accountId); } + if (AccountGlobalPendingIntentReader.hasPending(dsl, accountId)) throw unavailable(); // Match composite snapshot order: lock the issuer and caller before tenant source generations. CommittedCandidateVerificationData candidate = readCommittedCandidate(expectedOriginalTokenJti, expectedCommittedCandidate); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalPendingIntentReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalPendingIntentReader.java new file mode 100644 index 0000000000..86f433f450 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalPendingIntentReader.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import org.jooq.DSLContext; + +/** Exact Account-wide negative evidence only; absence does not establish admission authority. */ +final class AccountGlobalPendingIntentReader { + private AccountGlobalPendingIntentReader() {} + + /** + * Reads beneath the caller's already-held Account row lock in its writable owner transaction. + * V143's Account row-version fences serialize new intent against that lock, including stale + * repeatable-read/serializable snapshots. Do not lock the intent rows in the reverse order. + * Tenant-only scopes are deliberately not Account-wide denial evidence. + */ + static boolean hasPending(DSLContext dsl, UUID accountId) { + Objects.requireNonNull(accountId, "Exact Account UUID is required"); + Boolean pending = + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM account_security_state_operations " + + "WHERE account_uuid = ? AND status = 'WAITING') " + + "OR EXISTS (SELECT 1 FROM account_draft_authorization_source_changes c " + + "JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id " + + "WHERE c.status = 'WAITING' AND s.source_key IN (?, ?))", + accountId, + "ACCOUNT:" + accountId, + "GLOBAL_ROLES:" + accountId) + .get(0, Boolean.class); + // An unreadable result must never be interpreted as clear authority. + return !Boolean.FALSE.equals(pending); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java new file mode 100644 index 0000000000..93f06b65c8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventReadback; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered, authenticated owner for current and retained Account issuer source reads. */ +public final class AccountIssuerSourceSnapshotReadOwner { + private final AccountAuthoritySourceEvidenceRepository sourceRepository; + private final TransactionTemplate transaction; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected source repository collaborator; the owner never exposes it") + public AccountIssuerSourceSnapshotReadOwner( + AccountAuthoritySourceEvidenceRepository sourceRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceRepository = Objects.requireNonNull(sourceRepository); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace); + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + /** + * Authenticates first, then validates the closed request before opening the owner transaction. + */ + public ReadResult read(ReadCurrentIssuerAuthoritySourceRequest request) { + GrpcPeerIdentity peer = requireGameSessionPeer(); + rejectAmbientTransaction(); + if (request == null) { + throw new IllegalArgumentException("Malformed Account issuer source request"); + } + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest parsed = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(request, workloadNamespace, peer.uri()); + + var current = readInOwnerTransaction(() -> readCurrent(parsed, peer)); + return new ReadResult(parsed, peer.uri(), current); + } + + /** + * Reads a retained issuer event and the independently current source in one owner transaction. + */ + public ExactEventReadResult readExactEvent(ReadExactIssuerAuthorityEventRequest request) { + GrpcPeerIdentity peer = requireGameSessionPeer(); + rejectAmbientTransaction(); + if (request == null) { + throw new IllegalArgumentException("Malformed Account issuer source request"); + } + ExactEventRequest parsed = + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest( + request, workloadNamespace, peer.uri()); + + ExactEventReadback readback = readInOwnerTransaction(() -> readSelected(parsed, peer)); + return new ExactEventReadResult(parsed, peer.uri(), readback); + } + + private T readInOwnerTransaction(Supplier read) { + try { + return Objects.requireNonNull( + transaction.execute( + ignored -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw failedPrecondition("Owned writable Account source transaction required"); + } + return read.get(); + }), + "Account issuer source transaction returned no evidence"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException | TransactionException unavailable) { + throw unavailable(); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + } + + private AccountIssuerSourceSnapshotEvidence readCurrent( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, GrpcPeerIdentity peer) { + final AccountIssuerSourceSnapshotEvidence current; + try { + var source = sourceRepository.readCurrentCanonicalIssuerSource(request.issuerId()); + current = snapshotEvidence(source, request, peer); + } catch (IllegalArgumentException | IllegalStateException invalidSource) { + throw failedPrecondition("Account issuer source snapshot is unavailable or inconsistent"); + } catch (DataAccessException unavailable) { + throw unavailable(); + } + + request + .expectedSource() + .ifPresent( + expected -> { + if (!expected.equals(current)) { + throw failedPrecondition( + "Account issuer source differs from the exact expected snapshot"); + } + }); + return current; + } + + private ExactEventReadback readSelected(ExactEventRequest request, GrpcPeerIdentity peer) { + try { + var readback = + sourceRepository.readExactCanonicalIssuerEvent( + request.scope().issuerId(), + request.outboxSequence(), + request.expectedEventId(), + request.expectedEventDigest()); + return new ExactEventReadback( + snapshotEvidence(readback.currentSnapshot(), request.scope(), peer), + readback.selectedEvent()); + } catch (IllegalArgumentException | IllegalStateException invalidSource) { + throw failedPrecondition("Exact Account issuer event is unavailable or inconsistent"); + } catch (DataAccessException unavailable) { + throw unavailable(); + } + } + + private static AccountIssuerSourceSnapshotEvidence snapshotEvidence( + CanonicalIssuerSourceSnapshot source, + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, + GrpcPeerIdentity peer) { + IssuerGenerationProjection projection = IssuerGenerationProjection.fromSource(source); + return new AccountIssuerSourceSnapshotEvidence( + request.reconciliationOperationId(), + request.targetNamespace(), + peer.uri(), + projection.issuerId(), + projection.issuerAuthGeneration(), + projection.sourceVersion(), + projection.outboxStreamKey(), + projection.lastAppliedSourceOutboxSequence(), + projection.sourceEvent()); + } + + private GrpcPeerIdentity requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !peer.isInNamespace(workloadNamespace) + || !peer.isService("game-session-service") + || SessionContext.hasAuthenticatedCallerContext() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Same-namespace Game Session workload required") + .asRuntimeException(); + } + return peer; + } + + private static void rejectAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw failedPrecondition("Account issuer source read requires its own transaction"); + } + } + + private static StatusRuntimeException failedPrecondition(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + private static StatusRuntimeException unavailable() { + return Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException(); + } + + /** Context required by the unregistered gRPC adapter to encode the closed response. */ + public record ReadResult( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, + String authenticatedCallerWorkload, + AccountIssuerSourceSnapshotEvidence evidence) { + public ReadResult { + Objects.requireNonNull(request); + Objects.requireNonNull(authenticatedCallerWorkload); + Objects.requireNonNull(evidence); + } + } + + /** Context required by the unregistered gRPC adapter to encode the historical readback. */ + public record ExactEventReadResult( + ExactEventRequest request, String authenticatedCallerWorkload, ExactEventReadback readback) { + public ExactEventReadResult { + Objects.requireNonNull(request); + Objects.requireNonNull(authenticatedCallerWorkload); + Objects.requireNonNull(readback); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 60d9ce907c..2db16801ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -98,6 +98,13 @@ public void lockAccount(long accountId) { } } + /** Exact negative evidence, read only after the caller has locked the owning Account row. */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean hasGlobalPendingIntent(UUID accountId) { + requireWritableOwnerTransaction(); + return AccountGlobalPendingIntentReader.hasPending(dsl, accountId); + } + public Optional find(String requestId) { return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId).and(retainedV1Representation())) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLeaveOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLeaveOperationRepository.java new file mode 100644 index 0000000000..ac4e6a0d6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLeaveOperationRepository.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Internal durable LEAVE operation owner. Receipts are retry evidence, never current authority. */ +public final class AccountLeaveOperationRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Shared Account transaction collaborator") + public AccountLeaveOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public Receipt begin(long privateAccountId, AccountLeaveMembershipBinding binding) { + requireTransaction(); + Objects.requireNonNull(binding); + dsl.execute( + "INSERT INTO account_leave_operations " + + "(request_id, account_id, account_uuid, tenant_uuid, caller_binding, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, 'PENDING') ON CONFLICT (request_id) DO NOTHING", + binding.requestId(), + privateAccountId, + binding.accountId(), + binding.tenantId(), + binding.callerBinding(), + binding.digest()); + Record row = + dsl.fetchOne( + "SELECT * FROM account_leave_operations WHERE request_id = ? FOR UPDATE", + binding.requestId()); + if (row == null + || !Objects.equals(row.get("account_id", Long.class), privateAccountId) + || !binding.accountId().equals(row.get("account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.callerBinding().equals(row.get("caller_binding", String.class)) + || !binding.digest().equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("LEAVE idempotency conflict: original binding differs"); + } + return decode(row); + } + + public Receipt finish(AccountLeaveMembershipBinding binding, Terminal terminal) { + requireTransaction(); + Objects.requireNonNull(terminal); + int changed = + dsl.execute( + "UPDATE account_leave_operations SET status = 'COMMITTED', outcome = ?, membership_id = ?, " + + "before_membership_version = ?, before_membership_generation = ?, before_fence = ?, " + + "membership_version = ?, membership_authority_generation = ?, issuance_fence = ?, " + + "membership_event_stream_key = ?, event_sequence = ?, event_id = ?, event_digest = ?, " + + "audit_event_id = ?, audit_payload_digest = ? " + + "WHERE request_id = ? AND account_uuid = ? AND tenant_uuid = ? " + + "AND caller_binding = ? AND request_digest = ? AND status = 'PENDING'", + terminal.outcome(), + terminal.membershipId(), + terminal.beforeVersion(), + terminal.beforeGeneration(), + terminal.beforeFence(), + terminal.version(), + terminal.generation(), + terminal.fence(), + terminal.streamKey(), + terminal.eventSequence(), + terminal.eventId(), + terminal.eventDigest(), + terminal.auditEventId(), + terminal.auditDigest(), + binding.requestId(), + binding.accountId(), + binding.tenantId(), + binding.callerBinding(), + binding.digest()); + if (changed != 1) throw new IllegalStateException("LEAVE terminal compare-and-commit failed"); + Record row = + dsl.fetchOne( + "SELECT * FROM account_leave_operations WHERE request_id = ?", binding.requestId()); + Receipt result = decode(Objects.requireNonNull(row)); + if (!terminal.equals(result.terminal())) + throw new IllegalStateException("LEAVE terminal readback differs"); + return result; + } + + /** Retains the membership event as the sole cause of its exact composite fence advance. */ + public void recordFenceCause( + AccountLeaveMembershipBinding binding, + AccountAuthorityGenerationRepository.ScopeState before, + AccountAuthorityGenerationRepository.ScopeState after, + AccountAuthorityOutboxRepository.Event event) { + requireTransaction(); + var scope = + AccountAuthorityGenerationRepository.AuthorityScope.membership( + binding.accountId(), binding.tenantId()); + if (!scope.equals(before.scope()) + || !scope.equals(after.scope()) + || after.generation() != Math.incrementExact(before.generation()) + || after.sourceVersion() != Math.incrementExact(before.sourceVersion()) + || after.issuanceFence().value() != Math.incrementExact(before.issuanceFence().value()) + || !event.requestId().equals("leave:" + binding.requestId())) { + throw new IllegalArgumentException("Exact LEAVE fence cause required"); + } + dsl.execute( + "INSERT INTO account_issuance_fence_provenance " + + "(account_uuid, issuance_fence, source_version, prior_fence, cause_kind, tenant_uuid, " + + "source_stream_key, event_sequence, event_id, event_digest, prior_generation, generation, " + + "prior_authority_source_version, authority_source_version) " + + "VALUES (?, ?, ?, ?, 'MEMBERSHIP', ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.accountId(), + after.issuanceFence().value(), + after.issuanceFence().sourceVersion(), + before.issuanceFence().value(), + binding.tenantId(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + before.generation(), + after.generation(), + before.sourceVersion(), + after.sourceVersion()); + } + + private static Receipt decode(Record row) { + AccountLeaveMembershipBinding binding = + new AccountLeaveMembershipBinding( + row.get("request_id", String.class), row.get("account_uuid", UUID.class), + row.get("tenant_uuid", UUID.class), row.get("caller_binding", String.class)); + if (!binding.digest().equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("Stored LEAVE digest differs from exact binding"); + } + String status = row.get("status", String.class); + Terminal terminal = + "COMMITTED".equals(status) + ? new Terminal( + row.get("outcome", String.class), row.get("membership_id", Long.class), + row.get("before_membership_version", Long.class), + row.get("before_membership_generation", Long.class), + row.get("before_fence", Long.class), row.get("membership_version", Long.class), + row.get("membership_authority_generation", Long.class), + row.get("issuance_fence", Long.class), + row.get("membership_event_stream_key", String.class), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), row.get("event_digest", String.class), + row.get("audit_event_id", UUID.class), + row.get("audit_payload_digest", String.class)) + : null; + if (!"PENDING".equals(status) && !"COMMITTED".equals(status)) + throw new IllegalStateException("Invalid LEAVE status"); + return new Receipt(binding, status, terminal); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("LEAVE requires a writable Account transaction"); + } + } + + public record Receipt(AccountLeaveMembershipBinding binding, String status, Terminal terminal) {} + + public record Terminal( + String outcome, + Long membershipId, + Long beforeVersion, + Long beforeGeneration, + Long beforeFence, + Long version, + Long generation, + Long fence, + String streamKey, + Long eventSequence, + String eventId, + String eventDigest, + UUID auditEventId, + String auditDigest) { + public Terminal { + if (!("LEFT".equals(outcome) || "ALREADY_LEFT".equals(outcome)) + || beforeFence == null + || beforeFence <= 0 + || fence == null + || fence <= 0) { + throw new IllegalArgumentException("Complete LEAVE outcome required"); + } + if ("LEFT".equals(outcome)) { + if (membershipId == null + || membershipId <= 0 + || beforeVersion == null + || beforeGeneration == null + || version == null + || generation == null + || version != Math.addExact(beforeVersion, 1) + || generation != Math.addExact(beforeGeneration, 1) + || fence != Math.addExact(beforeFence, 1) + || streamKey == null + || eventSequence == null + || eventSequence <= 0 + || eventId == null + || eventDigest == null + || auditEventId == null + || auditDigest == null) { + throw new IllegalArgumentException("Exact LEAVE transition evidence required"); + } + } else if (!Objects.equals(beforeVersion, version) + || !Objects.equals(beforeGeneration, generation) + || !beforeFence.equals(fence) + || streamKey != null + || eventSequence != null + || eventId != null + || eventDigest != null + || auditEventId != null + || auditDigest != null) { + throw new IllegalArgumentException("Already-left outcome cannot carry a new transition"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index ed5b6c3fb4..c751f25dea 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -307,6 +307,98 @@ public PairAuthority commitRestore(PairAuthority expected, PairTransition transi return actual; } + /** Advances an existing positive pair after its exact left membership event was appended. */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority commitLeave(PairAuthority expected, PairTransition transition) { + requireOwnerWriteTransaction(); + Objects.requireNonNull(expected); + Objects.requireNonNull(transition); + requireFreshProvenance(expected.provenance()); + long nextSequence = increment(expected.eventSequence(), "membership event sequence"); + long nextVersion = increment(expected.membershipVersion(), "membership version"); + long nextGeneration = + increment(expected.membershipAuthorityGeneration(), "membership authority generation"); + if (!expected.membershipExists() + || expected.eventSequence() <= 0L + || !transition.membershipExists() + || transition.eventSequence() != nextSequence + || !transition.callerBoundAuthorityInvalidated() + || !expected.equals( + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow())) { + throw new IllegalStateException("Leave requires the exact current positive pair"); + } + Record ownerEvidence = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_authority_outbox_events next_event " + + "JOIN account_authority_outbox_streams stream USING (outbox_stream_key) " + + "JOIN account_authority_outbox_events prior_event USING (outbox_stream_key) " + + "JOIN accounts account ON account.account_uuid = ? " + + "JOIN account_tenant_membership member ON member.account_id = account.id AND member.tenant_uuid = ? " + + "WHERE next_event.outbox_stream_key = ? AND next_event.outbox_sequence = ? " + + "AND next_event.event_id = ? AND next_event.event_digest = ? AND stream.last_sequence = ? " + + "AND prior_event.outbox_sequence = ? AND prior_event.event_id = ? AND prior_event.event_digest = ? " + + "AND convert_from(prior_event.payload, 'UTF8')::JSONB ->> 'membershipLifecycleState' = 'ACTIVE' " + + "AND member.lifecycle_state = 'INACTIVE' AND member.gameplay_admission_allowed IS FALSE " + + "AND member.membership_version = ? AND member.membership_authority_generation = ?)", + expected.accountUuid(), + expected.tenantUuid(), + "account:auth-authority:v1:membership/" + + expected.accountUuid() + + "/" + + expected.tenantUuid(), + nextSequence, + transition.eventId(), + transition.eventDigest(), + nextSequence, + expected.eventSequence(), + expected.eventId(), + expected.eventDigest(), + nextVersion, + nextGeneration); + if (ownerEvidence == null || !Boolean.TRUE.equals(ownerEvidence.get(0, Boolean.class))) { + throw new IllegalStateException( + "Leave pair requires actual current membership and event evidence"); + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET membership_version = ?, membership_authority_generation = ?, last_event_sequence = ?, " + + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND membership_exists IS TRUE " + + "AND membership_version = ? AND membership_authority_generation = ? " + + "AND last_event_sequence = ? AND last_event_id = ? AND last_event_digest = ?", + nextVersion, + nextGeneration, + nextSequence, + transition.eventId(), + transition.eventDigest(), + expected.accountUuid(), + expected.tenantUuid(), + expected.membershipVersion(), + expected.membershipAuthorityGeneration(), + expected.eventSequence(), + expected.eventId(), + expected.eventDigest()); + if (changed != 1) throw new IllegalStateException("Leave pair compare-and-advance failed"); + PairAuthority actual = + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow(); + PairAuthority required = + new PairAuthority( + expected.accountUuid(), + expected.tenantUuid(), + expected.provenance(), + true, + nextVersion, + nextGeneration, + nextSequence, + transition.eventId(), + transition.eventDigest(), + true); + if (!required.equals(actual)) throw new IllegalStateException("Leave pair readback differs"); + return actual; + } + /** Advances only the stream checkpoint for the exact retained membership facts. */ PairAuthority commitPaidAuthorityCheckpoint( PairAuthority expected, AccountAuthorityOutboxRepository.Event event) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 33d6f4d147..489fa52f55 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -363,6 +363,53 @@ public AccountTenantMembership restoreFreshMembershipForJoin( return restored; } + /** Stages an exact ACTIVE leave; event, pair, fence and terminal receipt must commit with it. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountTenantMembership stageFreshMembershipForLeave( + UUID accountUuid, UUID tenantUuid, AccountTenantMembership expected) { + requireOwnerWriteTransaction(); + AccountTenantMembership current = + findFreshMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Leave membership is absent")); + if (expected == null + || !Objects.equals(current.getId(), expected.getId()) + || !"ACTIVE".equals(current.getLifecycleState()) + || current.getMembershipVersion() != expected.getMembershipVersion() + || current.getMembershipAuthorityGeneration() + != expected.getMembershipAuthorityGeneration()) { + throw new IllegalStateException("Leave membership changed from its locked snapshot"); + } + long nextVersion = increment(current.getMembershipVersion(), "membership version"); + long nextGeneration = + increment(current.getMembershipAuthorityGeneration(), "membership authority generation"); + int changed = + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE, membership_version = ?, membership_authority_generation = ? " + + "WHERE id = ? AND account_id = ? AND tenant_id IS NULL AND tenant_uuid = ? " + + "AND lifecycle_state = 'ACTIVE' AND membership_version = ? AND membership_authority_generation = ?", + nextVersion, + nextGeneration, + current.getId(), + current.getAccount().getId(), + tenantUuid, + current.getMembershipVersion(), + current.getMembershipAuthorityGeneration()); + if (changed != 1) + throw new IllegalStateException("Leave membership compare-and-advance failed"); + AccountTenantMembership left = + findCanonicalMembershipForUpdate(accountUuid, tenantUuid).orElseThrow(); + if (!"INACTIVE".equals(left.getLifecycleState()) + || left.isGameplayAdmissionAllowed() + || left.getMembershipVersion() != nextVersion + || left.getMembershipAuthorityGeneration() != nextGeneration + || !Objects.equals(left.getId(), current.getId()) + || !Objects.equals(left.getAuthorityProvenance(), current.getAuthorityProvenance())) { + throw new IllegalStateException("Leave membership readback differs"); + } + return left; + } + /** Account-fenced absence enrollment for the fresh creator owner; creates no membership. */ @Transactional(propagation = Propagation.MANDATORY) public PairAuthority prepareFreshCreatorAbsence(UUID accountUuid, UUID tenantUuid) { 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..9850fcd43e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepository.java @@ -0,0 +1,666 @@ +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 = 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().toString(), + 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/repository/ConnectTokenReceiptClassifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ConnectTokenReceiptClassifier.java new file mode 100644 index 0000000000..bb76adcef0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ConnectTokenReceiptClassifier.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Objects; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Unregistered storage-only recovery classifier. It cannot claim, mint, decrypt, replay, renew or + * delete anything. Supplied identity/digest provenance remains the Account owner's responsibility. + */ +public final class ConnectTokenReceiptClassifier { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The owner supplies its internal transaction-bound DSLContext; this is not registered.") + public ConnectTokenReceiptClassifier(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum State { + MISSING_UNCERTAIN, + IDEMPOTENCY_CONFLICT, + PENDING, + ABORTED, + RECONCILIATION_REQUIRED, + SUCCESS_REVALIDATION_REQUIRED, + FAILURE_ENVELOPE_RETAINED, + RESPONSE_RECOVERY_EXPIRED, + INCONSISTENT_EVIDENCE + } + + /** Exact caller-bound lookup input, not proof of authentication or a digest producer. */ + public record Lookup( + UUID accountId, + UUID tenantId, + String connectScopeId, + String requestId, + int digestVersion, + String requestDigest) { + public Lookup { + requireUuid(accountId); + requireUuid(tenantId); + requireText(connectScopeId, 2048); + requireText(requestId, 128); + if (digestVersion != 1 + || requestDigest == null + || !requestDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact supported retained digest is required"); + } + } + } + + /** + * Reads and locks only an existing receipt within the caller's transaction. A missing receipt is + * uncertain, never permission to mint. Success remains unusable until the owner independently + * revalidates current authority/postconditions and authenticates the encrypted envelope. + */ + public State classify(Lookup lookup) { + Objects.requireNonNull(lookup); + return dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Receipt classification requires an existing Account transaction"); + } + return classifyLocked( + org.jooq.impl.DSL.using( + dsl.configuration() + .derive(new org.jooq.impl.DefaultConnectionProvider(connection))), + lookup); + }); + } + + private State classifyLocked(DSLContext transaction, Lookup lookup) { + Record row = + transaction.fetchOne( + "SELECT op.request_digest_version,op.request_digest,op.status,op.reconciliation_blocked," + + "op.reconciliation_evidence,op.operation_id " + + "FROM connect_token_issuance_operation op " + + "WHERE op.account_uuid=? AND op.tenant_uuid=? AND op.connect_scope_id=? AND op.request_id=? " + + "FOR UPDATE OF op", + lookup.accountId(), + lookup.tenantId(), + lookup.connectScopeId(), + lookup.requestId()); + if (row == null) return State.MISSING_UNCERTAIN; + Integer version = row.get("request_digest_version", Integer.class); + String digest = row.get("request_digest", String.class); + if (!Objects.equals(version, lookup.digestVersion()) + || digest == null + || !MessageDigest.isEqual( + digest.getBytes(StandardCharsets.UTF_8), + lookup.requestDigest().getBytes(StandardCharsets.UTF_8))) { + return State.IDEMPOTENCY_CONFLICT; + } + String status = row.get("status", String.class); + if ("PENDING".equals(status)) return State.PENDING; + if ("ABORTED".equals(status)) return State.ABORTED; + if (!"COMMITTED".equals(status) && !"FAILED".equals(status)) return State.INCONSISTENT_EVIDENCE; + if (!Boolean.FALSE.equals(row.get("reconciliation_blocked", Boolean.class)) + || row.get("reconciliation_evidence", byte[].class) == null) { + return State.RECONCILIATION_REQUIRED; + } + // Separate read after taking the owner lock: READ COMMITTED can update the locked row + // while a joined envelope would still come from the pre-wait statement snapshot. + Record envelope = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM connect_token_response_envelope e WHERE e.operation_id=op.operation_id) AS present," + + "op.response_recovery_expires_at > clock_timestamp() AS within_horizon " + + "FROM connect_token_issuance_operation op WHERE operation_id=?", + row.get("operation_id", UUID.class)); + if (envelope == null) return State.INCONSISTENT_EVIDENCE; + boolean present = Boolean.TRUE.equals(envelope.get("present", Boolean.class)); + boolean withinHorizon = Boolean.TRUE.equals(envelope.get("within_horizon", Boolean.class)); + if (!present) + return withinHorizon ? State.INCONSISTENT_EVIDENCE : State.RESPONSE_RECOVERY_EXPIRED; + return "COMMITTED".equals(status) + ? State.SUCCESS_REVALIDATION_REQUIRED + : State.FAILURE_ENVELOPE_RETAINED; + } + + private static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Canonical identity is required"); + } + + private static void requireText(String value, int maxBytes) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) + throw new IllegalArgumentException("Exact request identity is required"); + try { + int length = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)).remaining(); + if (length > maxBytes) + throw new IllegalArgumentException("Request identity exceeds storage bound"); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Request identity must be valid UTF-8", exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ConnectTokenRequestFingerprint.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ConnectTokenRequestFingerprint.java new file mode 100644 index 0000000000..b134ed9b18 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ConnectTokenRequestFingerprint.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.IOException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Dormant Account-owned request encoding, not authentication or scope validation. Callers must + * authenticate the current account and establish exact scope provenance separately. No credential + * instance or mutable authority snapshot participates in immutable retry identity. + */ +public final class ConnectTokenRequestFingerprint { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private ConnectTokenRequestFingerprint() {} + + /** Produces a storage lookup only; neither missing nor retained state authorizes issuance. */ + public static ConnectTokenReceiptClassifier.Lookup lookup( + UUID accountId, UUID tenantId, String connectScopeId, String requestId) { + requireUuid(accountId); + requireUuid(tenantId); + requireText(connectScopeId, 2048); + requireText(requestId, 128); + Map fields = + Map.of( + "domain", + "connect-token-request/v1", + "accountId", + accountId.toString(), + "tenantId", + tenantId.toString(), + "connectScopeId", + connectScopeId, + "requestId", + requestId); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + String digest = + "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + return new ConnectTokenReceiptClassifier.Lookup( + accountId, tenantId, connectScopeId, requestId, 1, digest); + } catch (IOException failure) { + throw new IllegalStateException("Connect request encoding failed", failure); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("A non-nil canonical UUID is required"); + } + + private static void requireText(String value, int maxBytes) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) + throw new IllegalArgumentException("Exact request identity is required"); + try { + if (StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)).remaining() > maxBytes) + throw new IllegalArgumentException("Request identity exceeds storage bound"); + } catch (CharacterCodingException failure) { + throw new IllegalArgumentException("Request identity must be valid UTF-8", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ProfileRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ProfileRepository.java index 1e52774414..1c687582fe 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ProfileRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ProfileRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_TENANT_MEMBERSHIP; import static net.firedevops.firemud.accountservice.jooq.Tables.PROFILES; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -43,6 +44,14 @@ public List findByTenantIdAndAccountIds(Long tenantId, List accou } return baseSelect() .where(PROFILES.TENANT_ID.eq(tenantId).and(PROFILES.ACCOUNT_ID.in(accountIds))) + .andExists( + org.jooq + .impl + .DSL + .selectOne() + .from(ACCOUNT_TENANT_MEMBERSHIP) + .where(ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID.eq(PROFILES.ACCOUNT_ID)) + .and(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID.eq(PROFILES.TENANT_ID))) .orderBy(PROFILES.ACCOUNT_ID.asc()) .fetch(this::toEntity); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index f04c74800c..5ef0b8b620 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -379,6 +379,9 @@ private CanonicalJoinTerminalProof commitCanonicalFirstJoin( final Checkpoint checkpoint; if ("PENDING".equals(operation.status())) { + if (joinOperationRepository.hasGlobalPendingIntent(scope.accountId())) { + throw new IllegalStateException("Canonical first-JOIN Account source intent is unresolved"); + } VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); if (!Boolean.TRUE.equals(operation.allowPublicJoin()) || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalLeaveMembershipCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalLeaveMembershipCoordinator.java new file mode 100644 index 0000000000..5f4eaea7d4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalLeaveMembershipCoordinator.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLeaveOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLeaveOperationRepository.Receipt; +import net.firedevops.firemud.accountservice.repository.AccountLeaveOperationRepository.Terminal; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Account-local LEAVE owner. The caller supplies an authenticated binding and one + * writable owner transaction; failures must escape it. No public route or current authority is + * provided by this primitive, and historical receipt replay never reruns a transition. + */ +public final class AccountCanonicalLeaveMembershipCoordinator { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final AccountRepository accounts; + private final AccountJoinOperationRepository accountLocks; + private final AccountLeaveOperationRepository operations; + private final AccountTenantMembershipRepository memberships; + private final AccountAuthoritySourceEvidenceRepository sources; + private final AccountMembershipAuthorityEventProducer producer; + private final AccountAuditOutboxRepository audit; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Shared Account owner transaction collaborators") + public AccountCanonicalLeaveMembershipCoordinator( + AccountRepository accounts, + AccountJoinOperationRepository accountLocks, + AccountLeaveOperationRepository operations, + AccountTenantMembershipRepository memberships, + AccountAuthoritySourceEvidenceRepository sources, + AccountMembershipAuthorityEventProducer producer, + AccountAuditOutboxRepository audit) { + this.accounts = Objects.requireNonNull(accounts); + this.accountLocks = Objects.requireNonNull(accountLocks); + this.operations = Objects.requireNonNull(operations); + this.memberships = Objects.requireNonNull(memberships); + this.sources = Objects.requireNonNull(sources); + this.producer = Objects.requireNonNull(producer); + this.audit = Objects.requireNonNull(audit); + } + + public Receipt leave(AccountLeaveMembershipBinding binding) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("LEAVE requires a writable Account owner transaction"); + } + Objects.requireNonNull(binding); + var account = accounts.findByAccountUuid(binding.accountId()).orElseThrow(); + if (account.getId() == null + || account.getId() <= 0 + || !binding.accountId().equals(account.getAccountUuid()) + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Exact persisted LEAVE Account identity required"); + } + accountLocks.lockAccount(account.getId()); + Receipt original = operations.begin(account.getId(), binding); + if ("COMMITTED".equals(original.status())) return original; + var member = + memberships + .findFreshMembershipForUpdate(binding.accountId(), binding.tenantId()) + .orElse(null); + if (member == null || "INACTIVE".equals(member.getLifecycleState())) { + long fence = + sources + .readCurrentIssuerAccountSources("firemud-account-service", binding.accountId()) + .issuanceFence() + .value(); + if (member != null && member.isGameplayAdmissionAllowed()) + throw new IllegalStateException("Inactive membership still admits gameplay"); + Long version = member == null ? null : member.getMembershipVersion(); + Long generation = member == null ? null : member.getMembershipAuthorityGeneration(); + return operations.finish( + binding, + new Terminal( + "ALREADY_LEFT", + member == null ? null : member.getId(), + version, + generation, + fence, + version, + generation, + fence, + null, + null, + null, + null, + null, + null)); + } + if (!"ACTIVE".equals(member.getLifecycleState())) + throw new IllegalStateException("Membership lifecycle does not permit LEAVE"); + var transition = producer.publishCanonicalLeftMembershipChange(binding); + var event = transition.event(); + operations.recordFenceCause( + binding, transition.beforeAuthority(), transition.afterAuthority(), event); + Map payload = new LinkedHashMap<>(); + payload.put("operationKind", "LEAVE"); + payload.put("requestId", binding.requestId()); + payload.put("requestDigest", binding.digest()); + payload.put("accountId", binding.accountId().toString()); + payload.put("tenantId", binding.tenantId().toString()); + payload.put("membershipEventId", event.eventId()); + payload.put("membershipEventDigest", event.eventDigest()); + payload.put("membershipVersion", Long.toString(transition.version())); + payload.put("membershipAuthorityGeneration", Long.toString(transition.generation())); + final String bytes; + try { + bytes = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload)), + StandardCharsets.UTF_8); + } catch (Exception failure) { + throw new IllegalStateException("Cannot encode exact LEAVE audit", failure); + } + UUID auditId = + UUID.nameUUIDFromBytes( + ("account-leave-audit/v1:" + binding.requestId()).getBytes(StandardCharsets.UTF_8)); + var appended = + audit.appendCanonicalTenant( + auditId, binding.tenantId().toString(), "ACCOUNT_LEFT_TENANT_MEMBERSHIP", bytes); + var retained = audit.findExactCanonicalTenantEnvelopeForUpdate(appended).orElseThrow(); + return operations.finish( + binding, + new Terminal( + "LEFT", + transition.membershipId(), + transition.beforeVersion(), + transition.beforeGeneration(), + transition.beforeAuthority().issuanceFence().value(), + transition.version(), + transition.generation(), + transition.afterAuthority().issuanceFence().value(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + retained.auditEventId(), + retained.payloadDigest())); + } +} 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 62fc2bb614..559bf8bca4 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 @@ -14,6 +14,7 @@ import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; +import net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; @@ -303,6 +304,169 @@ public Checkpoint publishCanonicalRestoredMembershipChange( return checkpoint; } + /** + * Stages one genuine canonical leave under the Account lock. The caller must retain its exact + * fence cause, audit and LEAVE terminal receipt in this same transaction; this is not a route. + */ + @Transactional(propagation = Propagation.MANDATORY) + public LeaveTransition publishCanonicalLeftMembershipChange( + AccountLeaveMembershipBinding binding) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(binding); + var account = lockCanonicalAccountOwner(binding.accountId()); + var before = + membershipRepository + .findFreshMembershipForUpdate(binding.accountId(), binding.tenantId()) + .orElseThrow(); + var previous = + pairAuthorityRepository + .readForUpdate(binding.accountId(), binding.tenantId()) + .orElseThrow(); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + before.getTenantSourceOperationId(), + before.getTenantProvenanceDigest()); + requireExactPairScope(previous, binding.accountId(), binding.tenantId(), provenance); + if (!"ACTIVE".equals(before.getLifecycleState()) + || !previous.membershipExists() + || previous.eventSequence() <= 0 + || previous.membershipVersion() != before.getMembershipVersion() + || previous.membershipAuthorityGeneration() != before.getMembershipAuthorityGeneration()) { + throw new IllegalStateException("LEAVE requires exact retained ACTIVE membership and pair"); + } + roleSnapshotRepository + .findForCanonicalUpdate( + binding.accountId(), + binding.tenantId(), + provenance, + before.getId(), + before.getMembershipVersion()) + .orElseThrow(); + CompositeSnapshot original = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + binding.accountId(), + List.of(binding.tenantId()), + List.of(binding.tenantId())); + IssuerAccountSourceSnapshot sources = + sourceEvidenceRepository.readCurrentIssuerAccountSources( + ACCOUNT_JWT_ISSUER, binding.accountId()); + var tenant = + readCurrentTenantSourceEvent( + binding.tenantId(), provenance, only(original.tenants(), "tenant")); + requireCurrentAuthority( + original, + sources, + account.getId(), + binding.accountId(), + binding.tenantId(), + before, + provenance, + tenant); + String stream = membershipStreamKey(binding.accountId(), binding.tenantId()); + Event priorEvent = + authorityOutboxRepository.findEvent(stream, previous.eventSequence()).orElseThrow(); + var prior = + MembershipAuthorityEventV1Codec.verify( + new String(priorEvent.payload(), StandardCharsets.UTF_8)); + requireCheckpointMatchesEvent( + authorityOutboxRepository.readCheckpoint(stream).orElseThrow(), priorEvent); + if (!Arrays.equals(prior.canonicalJsonUtf8(), priorEvent.payload()) + || !previous.eventId().equals(priorEvent.eventId()) + || !previous.eventDigest().equals(priorEvent.eventDigest()) + || !priorEvent.eventId().equals(prior.eventId()) + || !priorEvent.eventDigest().equals(prior.eventDigest()) + || !binding.accountId().toString().equals(prior.accountId()) + || !binding.tenantId().toString().equals(prior.tenantId()) + || !"ACTIVE".equals(prior.membershipLifecycleState()) + || !Map.of(binding.tenantId().toString(), Long.toString(previous.membershipVersion())) + .equals(prior.membershipVersion()) + || !Long.toString(previous.membershipAuthorityGeneration()) + .equals(prior.membershipAuthorityGeneration())) { + throw new IllegalStateException( + "LEAVE predecessor differs from the exact current membership event"); + } + ScopeState beforeAuthority = only(original.memberships(), "membership"); + ScopeState afterAuthority = + authorityGenerationRepository.advance(beforeAuthority, original.issuanceFence()); + var left = + membershipRepository.stageFreshMembershipForLeave( + binding.accountId(), binding.tenantId(), before); + roleSnapshotRepository.replaceCanonical( + left, + binding.accountId(), + binding.tenantId(), + provenance, + left.getMembershipVersion(), + List.of()); + CompositeSnapshot advanced = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + binding.accountId(), + List.of(binding.tenantId()), + List.of(binding.tenantId())); + if (afterAuthority.generation() != left.getMembershipAuthorityGeneration() + || !afterAuthority.issuanceFence().equals(advanced.issuanceFence())) { + throw new IllegalStateException("LEAVE authority and membership advances differ"); + } + long sequence = Math.incrementExact(previous.eventSequence()); + String eventRequest = "leave:" + binding.requestId(); + String eventId = + UUID.nameUUIDFromBytes( + ("account-leave-membership/v1:" + binding.requestId()) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + Event event = + authorityOutboxRepository.append( + stream, + eventRequest, + allocated -> { + if (allocated != sequence) + throw new IllegalStateException("LEAVE event sequence changed"); + var sealed = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + binding.accountId(), + binding.tenantId(), + left, + List.of(), + advanced, + sources, + tenant, + eventId, + eventRequest, + sequence, + true)); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + Event readback = authorityOutboxRepository.findEvent(stream, sequence).orElseThrow(); + if (!event.equals(readback)) throw new IllegalStateException("LEAVE event readback differs"); + pairAuthorityRepository.commitLeave( + previous, new PairTransition(true, sequence, event.eventId(), event.eventDigest(), true)); + return new LeaveTransition( + left.getId(), + before.getMembershipVersion(), + before.getMembershipAuthorityGeneration(), + left.getMembershipVersion(), + left.getMembershipAuthorityGeneration(), + beforeAuthority, + afterAuthority, + event); + } + + public record LeaveTransition( + long membershipId, + long beforeVersion, + long beforeGeneration, + long version, + long generation, + ScopeState beforeAuthority, + ScopeState afterAuthority, + Event event) {} + /** Rechecks actual Account policy sources under the caller's final membership transaction. */ @Transactional(propagation = Propagation.MANDATORY) public void requireCurrentCanonicalJoinPolicy( @@ -619,8 +783,32 @@ private static Map membershipEventPreimage( String eventId, String requestId, long sequence) { - UUID accountUuid = scope.accountId(); - UUID tenantUuid = scope.tenantId(); + return membershipEventPreimage( + scope.accountId(), + scope.tenantId(), + membership, + roles, + authority, + sourceSnapshot, + tenantSourceEvent, + eventId, + requestId, + sequence, + false); + } + + private static Map membershipEventPreimage( + UUID accountUuid, + UUID tenantUuid, + AccountTenantMembership membership, + List roles, + CompositeSnapshot authority, + IssuerAccountSourceSnapshot sourceSnapshot, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, + String eventId, + String requestId, + long sequence, + boolean invalidated) { String streamKey = membershipStreamKey(accountUuid, tenantUuid); ScopeState tenant = only(authority.tenants(), "tenant"); ScopeState member = only(authority.memberships(), "membership"); @@ -681,7 +869,7 @@ private static Map membershipEventPreimage( event.put("issuanceFence", decimal(authority.issuanceFence().value())); event.put("roles", roles); event.put("gameplayAdmissionAllowed", membership.isGameplayAdmissionAllowed()); - event.put("callerBoundAuthorityInvalidated", false); + event.put("callerBoundAuthorityInvalidated", invalidated); return event; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java new file mode 100644 index 0000000000..b3ba99e406 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ExactIssuerAuthorityEventReadback; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; + +/** Unregistered adapter for the protected Account issuer-source owner read. */ +public final class AccountIssuerAuthoritySourceGrpcService + extends AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceImplBase { + private final AccountIssuerSourceSnapshotReadOwner owner; + + public AccountIssuerAuthoritySourceGrpcService(AccountIssuerSourceSnapshotReadOwner owner) { + this.owner = Objects.requireNonNull(owner); + } + + @Override + public void readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest request, + StreamObserver observer) { + respond( + () -> owner.read(request), + result -> + AccountIssuerSourceSnapshotGrpcCodec.toResponse( + result.evidence(), result.request(), result.authenticatedCallerWorkload()), + observer); + } + + @Override + public void readExactIssuerAuthorityEvent( + ReadExactIssuerAuthorityEventRequest request, + StreamObserver observer) { + respond( + () -> owner.readExactEvent(request), + result -> + AccountIssuerSourceSnapshotGrpcCodec.toExactEventResponse( + result.readback().currentSnapshot(), + result.readback().selectedEvent(), + result.request(), + result.authenticatedCallerWorkload()), + observer); + } + + private static void respond( + Supplier readOwner, Function encode, StreamObserver observer) { + final T result; + try { + result = readOwner.get(); + } catch (StatusRuntimeException failure) { + observer.onError(sanitize(failure)); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account issuer source request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException()); + return; + } + + final R response; + try { + response = encode.apply(result); + } catch (RuntimeException invalidSource) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Account issuer source snapshot is unavailable or inconsistent") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static StatusRuntimeException sanitize(StatusRuntimeException failure) { + return switch (Status.fromThrowable(failure).getCode()) { + case UNAUTHENTICATED -> + Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + case PERMISSION_DENIED -> + Status.PERMISSION_DENIED + .withDescription("Same-namespace Game Session workload required") + .asRuntimeException(); + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Malformed Account issuer source request") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Account issuer source snapshot is unavailable or conflicts") + .asRuntimeException(); + default -> + Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException(); + }; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index 5b7c1d1193..25e09b889c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.impl; import com.google.protobuf.Any; +import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.ServerServiceDefinition; @@ -28,12 +29,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Unregistered Account owner receiver. No component annotation, capacity commit, World hold or - * gameplay admission. + * Default-off Account owner receiver, available only through explicit private composition or the + * isolated receiving configuration. No capacity commit, World hold or gameplay admission. */ -public final class AccountPlayerAdmissionEntitlementGrpcService - extends AccountPlayerAdmissionEntitlementReadServiceGrpc - .AccountPlayerAdmissionEntitlementReadServiceImplBase { +public final class AccountPlayerAdmissionEntitlementGrpcService implements BindableService { private final AccountPlayerAdmissionEntitlementOwner owner; private final String namespace; private final AccountPlayerAdmissionEntitlementWorkloadGuard guard; @@ -59,16 +58,27 @@ public Server createUnregisteredServer( TlsServerCredentials.ClientAuth.REQUIRE, GrpcRequestBytePolicy.ordinary(), RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); - factory.addService(bindProtectedService()); + factory.addService(bindService()); return factory.createServer(); } - /** Binds the receiver and its method guard to the same private caller context. */ - public ServerServiceDefinition bindProtectedService() { - return ServerInterceptors.interceptForward(this, guard); + /** Every registration path retains the exact TLS workload guard, including Spring discovery. */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceImplBase() { + @Override + public void readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest request, + StreamObserver observer) { + AccountPlayerAdmissionEntitlementGrpcService.this.readPlayerAdmissionEntitlement( + request, observer); + } + }; + return ServerInterceptors.interceptForward(handler, guard); } - @Override public void readPlayerAdmissionEntitlement( ReadPlayerAdmissionEntitlementRequest wire, StreamObserver observer) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 4d58f7214f..3124b1c852 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -65,7 +65,6 @@ import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; -import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; @@ -1386,49 +1385,17 @@ public RealmAccessGrantResult getRealmAccessGrantForRuntime( } @Override - @Transactional @Timed(value = "account.realm_access_grant_upsert") public RealmAccessGrantResult grantRealmAccess(RealmAccessGrantRequest request) { - Account account = requireAccount(request.accountId()); - Instant now = Instant.now(); - AccountRealmAccessGrant grant = - accountRealmAccessGrantRepository - .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - request.accountId(), request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseGet( - () -> { - AccountRealmAccessGrant created = new AccountRealmAccessGrant(); - created.setAccount(account); - created.setTenantId(request.tenantId()); - created.setWorldSlug(request.worldSlug()); - created.setRealmSlug(request.realmSlug()); - created.setGrantVersion(0L); - created.setGranted(true); - created.setCreatedAt(now); - return created; - }); - grant.setGrantVersion(grant.getGrantVersion() + 1L); - grant.setGranted(true); - grant.setGrantedBy(request.grantedBy()); - grant.setGrantReason(request.grantReason()); - grant.setUpdatedAt(now); - accountRealmAccessGrantRepository.save(grant); - return new RealmAccessGrantResult( - request.accountId(), - request.tenantId(), - request.worldSlug(), - request.realmSlug(), - true, - grant.getGrantVersion(), - now.toString()); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } @Override - @Transactional @Timed(value = "account.realm_access_grant_revoke") public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, String realmSlug) { - accountRealmAccessGrantRepository.revokeByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } @Override @@ -2001,7 +1968,9 @@ private long requireAccountStorageId(Account account, UUID accountUuid) { } private String mintToken(String subject, long expirationMs, Map claims) { - return jwtUtil.generateToken(subject, expirationMs, claims); + Map accountClaims = new HashMap<>(claims); + accountClaims.put("iss", "firemud-account-service"); + return jwtUtil.generateToken(subject, expirationMs, accountClaims); } private Map authenticationTokenClaims(String audience, Account account) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java index af2412f947..f482e6b0b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -165,7 +165,7 @@ public String toString() { public static final String SCRIPT_ID = "account.game-session-delegation-pending-register.v1"; public static final String ISSUER_PROJECTION_SCRIPT_ID = - "account.game-session-delegation-authority-project-issuer.v1"; + "account.game-session-delegation-authority-project-issuer.v2"; public static final String ACCOUNT_PROJECTION_SCRIPT_ID = AccountGenerationProjectionRedisContract.SCRIPT_ID; public static final String TENANT_PROJECTION_SCRIPT_ID = @@ -175,7 +175,7 @@ public String toString() { public static final String ACTIVE_TRANSITION_SCRIPT_ID = "account.game-session-delegation-activate-committed.v1"; private static final String AUTHORITY_PROJECTION_SCRIPT_RESOURCE = - "redis/lua/account-game-session-delegation-authority-project.lua"; + "redis/lua/account-game-session-delegation-authority-project-v2.lua"; private static final String ACTIVE_TRANSITION_SCRIPT_RESOURCE = "redis/lua/account-game-session-delegation-activate-committed.lua"; public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; @@ -751,20 +751,8 @@ private ProjectionPublicationOutcome publishProjections( try { RedisCommands commands = requirePinnedCommands(connection); requireAccountAclIdentity(commands); - String loadedSha = commands.scriptLoad(scriptSource); - if (loadedSha == null - || !SHA1.matcher(loadedSha).matches() - || !sha1(scriptSource).equals(loadedSha)) { - throw unavailable(); - } - byte[][] issuerProjectionArguments = {issuerProjectionBytes}; Long issuerResult = - commands.evalsha( - loadedSha, - ScriptOutputType.INTEGER, - new byte[][] {issuerKey}, - issuerProjectionArguments); - requireProjectionResult(issuerResult); + applyIssuerProjection(commands, issuerKey, issuerProjectionBytes, scriptSource); String accountSha = commands.scriptLoad(accountScriptSource); if (accountSha == null || !sha1(accountScriptSource).equals(accountSha)) throw unavailable(); byte[] priorAccountBytes = commands.get(accountKey); @@ -1454,6 +1442,74 @@ private static Long exactInteger(Object value) { } } + /** Package-local issuer-only path; supplied value is typed, never an arbitrary key/script. */ + ProjectionPublicationOutcome publishIssuerAuthorityProjection( + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection projection) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) { + throw unavailable(); + } + byte[] bytes = projection.toJson().getBytes(StandardCharsets.UTF_8); + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + bytes, "issuer", GameSessionAccountDelegationProfile.ISSUER); + byte[] key = ascii(projection.key()); + var descriptor = requireIssuerProjectionDescriptor(); + byte[] script = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(script))) throw unavailable(); + try (var connection = connectionProvider.openPinnedConnection()) { + if (connection == null) throw unavailable(); + var commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + Long outcome = applyIssuerProjection(commands, key, bytes, script); + requireDurabilityAcknowledgement(commands); + if (!Arrays.equals(bytes, commands.get(key)) + || !Long.valueOf(-1L).equals(commands.pttl(key))) { + throw unavailable(); + } + return outcome == 0L + ? ProjectionPublicationOutcome.EXACT_RETRY + : ProjectionPublicationOutcome.PUBLISHED; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static Long applyIssuerProjection( + RedisCommands commands, + byte[] issuerKey, + byte[] issuerProjectionBytes, + byte[] scriptSource) { + // Validate the complete canonical retained issuer event before considering replacement. + // The v2 script compares these exact bytes atomically; a changed read cannot authorize CAS. + byte[] priorIssuerBytes = commands.get(issuerKey); + if (priorIssuerBytes != null) { + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + priorIssuerBytes, "issuer", GameSessionAccountDelegationProfile.ISSUER); + } + boolean exactIssuer = Arrays.equals(priorIssuerBytes, issuerProjectionBytes); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) { + throw unavailable(); + } + byte[][] issuerProjectionArguments = { + ascii(priorIssuerBytes == null ? "ABSENT" : exactIssuer ? "VERIFY" : "PRESENT"), + priorIssuerBytes == null ? new byte[0] : priorIssuerBytes, + exactIssuer ? new byte[0] : issuerProjectionBytes + }; + Long issuerResult = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {issuerKey}, + issuerProjectionArguments); + requireProjectionResult(issuerResult); + return issuerResult; + } + private RedisScriptDescriptor requireIssuerProjectionDescriptor() { RedisScriptDescriptor descriptor = scriptCatalog.require(ISSUER_PROJECTION_SCRIPT_ID); if (!ISSUER_PROJECTION_SCRIPT_ID.equals(descriptor.scriptId()) @@ -1461,14 +1517,15 @@ private RedisScriptDescriptor requireIssuerProjectionDescriptor() { || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION || descriptor.category() != ScriptCategory.SESSION_CAS || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) - || !canonicalSharedDescriptorMetadata(descriptor) + || !canonicalSharedDescriptorMetadata(descriptor, "v2") || !AUTHORITY_PROJECTION_SCRIPT_RESOURCE.equals(descriptor.resourcePath()) || descriptor.keys().size() != 1 || !"authorityProjection".equals(descriptor.keys().getFirst().name()) || !AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX.equals( descriptor.keys().getFirst().ownedPrefix()) || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED - || !argumentNames(descriptor).equals(List.of("canonicalProjectionUtf8"))) { + || !argumentNames(descriptor) + .equals(List.of("expectedMode", "expectedBytes", "candidateBytes"))) { throw unavailable(); } return descriptor; @@ -1569,13 +1626,18 @@ private static List argumentNames(RedisScriptDescriptor descriptor) { } private static boolean canonicalSharedDescriptorMetadata(RedisScriptDescriptor descriptor) { + return canonicalSharedDescriptorMetadata(descriptor, "v1"); + } + + private static boolean canonicalSharedDescriptorMetadata( + RedisScriptDescriptor descriptor, String callerVersion) { return descriptor.resetSensitivity() == RedisScriptDescriptor.ResetSensitivity.CLUSTER && descriptor.lossClass() == RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP && descriptor.compatibilityLevel() == RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET && descriptor .supportedCoexistence() - .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"))) + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence(callerVersion, "v1"))) && descriptor.legacyPayloadShape() == null; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java index aaa05c75ee..6e407b6c7d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java @@ -18,7 +18,7 @@ public final class AccountGameplayDelegationRedisScriptContribution private static final String[] DESCRIPTOR_RESOURCES = { "/redis/scripts/account-game-session-delegation-pending-register.json", "/redis/scripts/account-game-session-delegation-activate-committed.json", - "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json", "/redis/scripts/account-selected-tenant-generation-projection.json", "/redis/scripts/account-selected-membership-generation-projection.json", "/redis/scripts/account-initial-gameplay-login-dispose.json" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisher.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisher.java new file mode 100644 index 0000000000..7effb7330b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisher.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered issuer-only informational reprojection. No Account lookup/enrollment/key, token, + * authority grant, repair of malformed Redis evidence, or runtime activation is supplied. + */ +public final class AccountIssuerGenerationProjectionPublisher { + private final AccountAuthoritySourceEvidenceRepository sources; + private final TransactionTemplate transaction; + private final AccountGameplayDelegationRedisClient redis; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Retain the existing issuer source owner; copying an injected repository would break its transaction-bound SQL collaboration.") + public AccountIssuerGenerationProjectionPublisher( + AccountAuthoritySourceEvidenceRepository sources, + PlatformTransactionManager transactions, + AccountGameplayDelegationRedisClient redis) { + this.sources = Objects.requireNonNull(sources); + this.redis = Objects.requireNonNull(redis); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** One issuer-key CAS followed by exact Redis and fresh SQL readback, never implicit retry. */ + public Publication refreshCurrent(String issuerId) { + IssuerGenerationProjection.keyForIssuer(issuerId); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Issuer-only projection cannot inherit owner SQL context"); + } + var before = read(issuerId); + var candidate = IssuerGenerationProjection.fromSource(before); + var outcome = redis.publishIssuerAuthorityProjection(candidate); + var after = read(issuerId); + if (!before.source().equals(after.source()) + || !candidate.equals(IssuerGenerationProjection.fromSource(after))) { + throw new IllegalStateException( + "Issuer source changed during projection; explicit retry required"); + } + return new Publication(candidate.key(), candidate.toJson(), outcome); + } + + private CanonicalIssuerSourceSnapshot read(String issuerId) { + return Objects.requireNonNull( + transaction.execute(ignored -> sources.readCurrentCanonicalIssuerSource(issuerId)), + "Current existing issuer source required"); + } + + /** Exact observed cache values, never an authorization or freshness receipt for later use. */ + public record Publication( + String key, + String json, + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome outcome) { + public Publication { + Objects.requireNonNull(key); + Objects.requireNonNull(json); + Objects.requireNonNull(outcome); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/AccountTransferCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/AccountTransferCaptureRepository.java new file mode 100644 index 0000000000..07a4bc3f58 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/AccountTransferCaptureRepository.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.tenantrole; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered fresh-tenant owner observation only. No actor authentication, transfer permission, + * mutation intent, source change, or admission is produced. Historical decoding cannot replace this + * owner transaction. Retained tenant provenance is deliberately unsupported in this first slice. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Account owner repositories and DSLContext are explicit internal transaction collaborators, not public data.") +public final class AccountTransferCaptureRepository { + private final DSLContext dsl; + private final AccountCanonicalRuntimeMembershipSnapshotRepository current; + private final AccountAuthorityGenerationRepository generations; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRoleSnapshotRepository roles; + + public AccountTransferCaptureRepository( + DSLContext dsl, + AccountCanonicalRuntimeMembershipSnapshotRepository current, + AccountAuthorityGenerationRepository generations, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles) { + this.dsl = Objects.requireNonNull(dsl); + this.current = Objects.requireNonNull(current); + this.generations = Objects.requireNonNull(generations); + this.pairs = Objects.requireNonNull(pairs); + this.roles = Objects.requireNonNull(roles); + } + + public TransferCaptureCodec.Pair capture(UUID actor, UUID target, UUID tenant) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw new IllegalStateException("Transfer capture requires one writable owner transaction"); + if (tenant == null || tenant.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Tenant UUID required"); + List ordered = TransferCaptureBounds.orderedAccounts(actor, target); + // All Account owners first, in the SAME UUID-string order as Draft source changes. Never + // read one member/source/fence and then acquire the other Account owner. + for (UUID account : ordered) { + Record row = + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", account); + if (row == null || !account.equals(row.get("account_uuid", UUID.class))) throw unavailable(); + } + Map captured = new HashMap<>(); + for (UUID account : ordered) captured.put(account, readMember(account, tenant)); + TransferCaptureCodec.Pair result = + new TransferCaptureCodec.Pair(captured.get(actor), captured.get(target)); + TransferCaptureCodec.encode( + result); // Validate the complete bounded representation before return. + return result; + } + + private TransferCaptureCodec.Member readMember(UUID account, UUID tenant) { + var pair = + pairs + .readForUpdate(account, tenant) + .orElseThrow(AccountTransferCaptureRepository::unavailable); + if (!pair.membershipExists() + || pair.provenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN) throw unavailable(); + Record member = + dsl.fetchOne( + "SELECT m.id, m.membership_version, m.lifecycle_state FROM account_tenant_membership m JOIN accounts a ON a.id=m.account_id WHERE a.account_uuid=? AND m.tenant_uuid=? FOR UPDATE OF m", + account, + tenant); + if (member == null || !"ACTIVE".equals(member.get("lifecycle_state", String.class))) + throw unavailable(); + long membershipId = member.get("id", Long.class); + Record bounds = + dsl.fetchOne( + "SELECT count(*) AS n, coalesce(max(octet_length(role_identifier)),0) AS width FROM account_tenant_membership_role_snapshot_roles WHERE membership_id=?", + membershipId); + if (bounds == null + || bounds.get("n", Long.class) > TransferCaptureBounds.MAX_ROLES_PER_MEMBER + || bounds.get("width", Integer.class) > TransferCaptureBounds.MAX_ROLE_UTF8_BYTES) + throw unavailable(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account + + "/" + + tenant; + Record size = + dsl.fetchOne( + "SELECT octet_length(payload) AS n FROM account_authority_outbox_events WHERE outbox_stream_key=? AND outbox_sequence=?", + stream, + pair.eventSequence()); + if (size == null + || size.get("n", Integer.class) <= 0 + || size.get("n", Integer.class) > TransferCaptureBounds.MAX_COMPONENT_BYTES) + throw unavailable(); + // Reuse actual owner evidence/provenance/current source/checkpoint verification. It is not + // caller permission and is intentionally fresh-tenant-only. The two Account locks already hold. + var snapshot = current.readCurrent(account, tenant); + if (!snapshot.membershipExists() || !"ACTIVE".equals(snapshot.membershipLifecycleState())) + throw unavailable(); + var role = + roles + .findForCanonicalUpdate( + account, + tenant, + pair.provenance(), + membershipId, + member.get("membership_version", Long.class)) + .orElseThrow(AccountTransferCaptureRepository::unavailable); + var authority = + generations.readCompositeSnapshot( + snapshot.issuerId(), account, List.of(tenant), List.of(tenant)); + var evidence = + snapshot.sourceEvidence().stream().filter(e -> e.outboxStreamKey().equals(stream)).toList(); + if (evidence.size() != 1) throw unavailable(); + var event = MembershipAuthorityEventV1Codec.verify(evidence.getFirst().canonicalEventJson()); + return TransferCaptureCodec.fromObserved( + role, pair, authority, snapshot.membershipLifecycleState(), event); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact current two-member transfer capture is unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBounds.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBounds.java new file mode 100644 index 0000000000..fe60146fdd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBounds.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.tenantrole; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** + * Resource bounds and owner-lock ordering for an unregistered, non-authenticating transfer capture. + * These checks do not establish membership, event provenance, actor permission or mutation + * authority. + */ +public final class TransferCaptureBounds { + public static final int MEMBER_COUNT = 2; + public static final int MAX_ROLES_PER_MEMBER = 64; + public static final int MAX_ROLE_UTF8_BYTES = 128; + public static final int MAX_COMPONENT_BYTES = 16 * 1024; + public static final int MAX_CAPTURE_BYTES = 256 * 1024; + + private TransferCaptureBounds() {} + + /** Same lexical UUID ordering used by Draft source-change Account owner locks. */ + public static List orderedAccounts(UUID actor, UUID target) { + requireAccount(actor); + requireAccount(target); + if (actor.equals(target)) { + throw new IllegalArgumentException("Transfer capture requires two distinct Account owners"); + } + return List.of(actor, target).stream().sorted(Comparator.comparing(UUID::toString)).toList(); + } + + /** Checks the envelope before a decoder can allocate component buffers. */ + public static byte[] copyEnvelope(byte[] encoded) { + Objects.requireNonNull(encoded, "Capture bytes are required"); + if (encoded.length == 0 || encoded.length > MAX_CAPTURE_BYTES) { + throw new IllegalArgumentException("Capture byte bound exceeded"); + } + return Arrays.copyOf(encoded, encoded.length); + } + + /** Check a wire length against both its component cap and actual remaining envelope. */ + public static int componentLength(int declaredLength, int remainingBytes) { + if (declaredLength <= 0 + || declaredLength > MAX_COMPONENT_BYTES + || remainingBytes < 0 + || declaredLength > remainingBytes) { + throw new IllegalArgumentException("Capture component length is invalid"); + } + return declaredLength; + } + + private static void requireAccount(UUID account) { + if (account == null || account.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodec.java new file mode 100644 index 0000000000..e105adec28 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodec.java @@ -0,0 +1,287 @@ +package net.firedevops.firemud.accountservice.tenantrole; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +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.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; + +/** + * Bounded immutable observations, NOT authenticated transfer permission or current-owner proof. The + * owner adapter must obtain and cross-check the supplied records in one ordered transaction. + * Decoding historical bytes never makes them current and does not admit a source mutation. + */ +public final class TransferCaptureCodec { + private static final int MAGIC = 0x54524331; + + private TransferCaptureCodec() {} + + public record Pair(Member actor, Member target) { + public Pair { + Objects.requireNonNull(actor); + Objects.requireNonNull(target); + TransferCaptureBounds.orderedAccounts(actor.account(), target.account()); + if (!actor.tenant().equals(target.tenant()) + || !actor.provenance().equals(target.provenance()) + || !actor.issuerId().equals(target.issuerId()) + || actor.currentIssuerGeneration() != target.currentIssuerGeneration() + || actor.currentTenantGeneration() != target.currentTenantGeneration()) { + throw invalid(); + } + } + } + + /** Fixed fields: no extensible or caller-selected source-kind map. */ + public record Member( + long numericAccountId, + long membershipId, + VerifiedTenantProvenance provenance, + String issuerId, + long issuerSourceVersion, + long accountSourceVersion, + long tenantSourceVersion, + long membershipSourceVersion, + long issuanceFenceSourceVersion, + long currentIssuerGeneration, + long currentAccountGeneration, + long currentTenantGeneration, + long currentMembershipGeneration, + long currentIssuanceFence, + MembershipEvent event) { + public Member { + Objects.requireNonNull(provenance); + Objects.requireNonNull(event); + if (numericAccountId <= 0 + || membershipId <= 0 + || issuerSourceVersion <= 0 + || accountSourceVersion <= 0 + || tenantSourceVersion <= 0 + || membershipSourceVersion <= 0 + || issuanceFenceSourceVersion <= 0 + || currentIssuerGeneration <= 0 + || currentAccountGeneration <= 0 + || currentTenantGeneration <= 0 + || currentMembershipGeneration <= 0 + || currentIssuanceFence <= 0 + || issuerId == null + || issuerId.isBlank()) throw invalid(); + if (issuerId.length() > TransferCaptureBounds.MAX_COMPONENT_BYTES + || event.canonicalJson().length() > TransferCaptureBounds.MAX_COMPONENT_BYTES) + throw invalid(); + bounded(issuerId.getBytes(StandardCharsets.UTF_8)); + bounded(event.canonicalJsonUtf8()); + if (!"ACTIVE".equals(event.membershipLifecycleState()) + || currentMembershipGeneration != number(event.membershipAuthorityGeneration()) + || event.roles().size() > TransferCaptureBounds.MAX_ROLES_PER_MEMBER) throw invalid(); + for (String role : event.roles()) { + if (role.getBytes(StandardCharsets.UTF_8).length + > TransferCaptureBounds.MAX_ROLE_UTF8_BYTES) throw invalid(); + } + } + + public UUID account() { + return UUID.fromString(event.accountId()); + } + + public UUID tenant() { + return UUID.fromString(event.tenantId()); + } + } + + /** + * Checks agreement, not provenance: none of these caller-supplied values authenticates itself. + */ + public static Member fromObserved( + RoleSnapshot roles, + PairAuthority pair, + CompositeSnapshot authority, + String membershipLifecycle, + MembershipEvent event) { + Objects.requireNonNull(roles); + Objects.requireNonNull(pair); + Objects.requireNonNull(authority); + Objects.requireNonNull(event); + UUID account = UUID.fromString(event.accountId()); + UUID tenant = UUID.fromString(event.tenantId()); + if (!"ACTIVE".equals(membershipLifecycle) + || !pair.membershipExists() + || !account.equals(pair.accountUuid()) + || !tenant.equals(pair.tenantUuid()) + || !account.equals(roles.accountUuid()) + || !tenant.equals(roles.tenantUuid()) + || !pair.provenance().equals(roles.tenantProvenance()) + || roles.snapshotVersion() != pair.membershipVersion() + || !roles.roles().equals(event.roles()) + || pair.membershipVersion() != number(event.membershipVersion().get(tenant.toString())) + || pair.membershipAuthorityGeneration() != number(event.membershipAuthorityGeneration()) + || pair.eventSequence() != number(event.outboxSequence()) + || !pair.eventId().equals(event.eventId()) + || !pair.eventDigest().equals(event.eventDigest()) + || pair.lastTransitionInvalidated() != event.callerBoundAuthorityInvalidated()) + throw invalid(); + if (authority.tenants().size() != 1 || authority.memberships().size() != 1) throw invalid(); + ScopeState tenantState = authority.tenants().getFirst(); + ScopeState memberState = authority.memberships().getFirst(); + if (authority.issuer().scope().kind() + != net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .ScopeKind.ISSUER + || authority.account().scope().kind() + != net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .ScopeKind.ACCOUNT + || tenantState.scope().kind() + != net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .ScopeKind.TENANT + || memberState.scope().kind() + != net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .ScopeKind.MEMBERSHIP + || !account.equals(authority.account().scope().accountId()) + || !account.equals(authority.issuanceFence().accountId()) + || !tenant.equals(tenantState.scope().tenantId()) + || !account.equals(memberState.scope().accountId()) + || !tenant.equals(memberState.scope().tenantId()) + || memberState.generation() != pair.membershipAuthorityGeneration() + || !authority.issuanceFence().equals(authority.account().issuanceFence()) + || !authority.issuanceFence().equals(memberState.issuanceFence())) throw invalid(); + return new Member( + roles.accountId(), + roles.membershipId(), + pair.provenance(), + authority.issuer().scope().issuerId(), + authority.issuer().sourceVersion(), + authority.account().sourceVersion(), + tenantState.sourceVersion(), + memberState.sourceVersion(), + authority.issuanceFence().sourceVersion(), + authority.issuer().generation(), + authority.account().generation(), + tenantState.generation(), + memberState.generation(), + authority.issuanceFence().value(), + event); + } + + public static byte[] encode(Pair pair) { + Objects.requireNonNull(pair); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + out.writeInt(MAGIC); + write(out, pair.actor()); + write(out, pair.target()); + return TransferCaptureBounds.copyEnvelope(bytes.toByteArray()); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static Pair decode(byte[] encoded) { + byte[] stable = TransferCaptureBounds.copyEnvelope(encoded); + try { + DataInputStream in = new DataInputStream(new ByteArrayInputStream(stable)); + if (in.readInt() != MAGIC) throw invalid(); + Pair pair = new Pair(read(in), read(in)); + if (in.available() != 0 || !Arrays.equals(stable, encode(pair))) throw invalid(); + return pair; + } catch (IOException | IllegalArgumentException malformed) { + throw new IllegalArgumentException("Invalid bounded transfer capture", malformed); + } + } + + private static void write(DataOutputStream out, Member m) throws IOException { + out.writeLong(m.numericAccountId()); + out.writeLong(m.membershipId()); + text(out, m.provenance().kind().name()); + out.writeLong(m.provenance().legacyTenantId() == null ? 0 : m.provenance().legacyTenantId()); + text(out, m.provenance().sourceOperationId().toString()); + text(out, m.provenance().digest()); + text(out, m.issuerId()); + out.writeLong(m.issuerSourceVersion()); + out.writeLong(m.accountSourceVersion()); + out.writeLong(m.tenantSourceVersion()); + out.writeLong(m.membershipSourceVersion()); + out.writeLong(m.issuanceFenceSourceVersion()); + out.writeLong(m.currentIssuerGeneration()); + out.writeLong(m.currentAccountGeneration()); + out.writeLong(m.currentTenantGeneration()); + out.writeLong(m.currentMembershipGeneration()); + out.writeLong(m.currentIssuanceFence()); + bytes(out, m.event().canonicalJsonUtf8()); + } + + private static Member read(DataInputStream in) throws IOException { + long account = in.readLong(), membership = in.readLong(); + TenantProvenanceKind kind = TenantProvenanceKind.valueOf(text(in)); + long legacy = in.readLong(); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + legacy == 0 ? null : legacy, kind, UUID.fromString(text(in)), text(in)); + String issuer = text(in); + long is = in.readLong(), + as = in.readLong(), + ts = in.readLong(), + ms = in.readLong(), + fs = in.readLong(); + long ig = in.readLong(), + ag = in.readLong(), + tg = in.readLong(), + mg = in.readLong(), + fv = in.readLong(); + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(text(in)); + return new Member( + account, membership, provenance, issuer, is, as, ts, ms, fs, ig, ag, tg, mg, fv, event); + } + + private static void text(DataOutputStream out, String s) throws IOException { + bytes(out, s.getBytes(StandardCharsets.UTF_8)); + } + + private static void bytes(DataOutputStream out, byte[] b) throws IOException { + bounded(b); + out.writeInt(b.length); + out.write(b); + } + + private static String text(DataInputStream in) throws IOException { + int length = TransferCaptureBounds.componentLength(in.readInt(), in.available()); + byte[] bytes = new byte[length]; + in.readFully(bytes); + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } + + private static void bounded(byte[] b) { + TransferCaptureBounds.componentLength(b.length, TransferCaptureBounds.MAX_COMPONENT_BYTES); + } + + private static long number(String s) { + try { + long n = Long.parseLong(s); + if (n <= 0) throw invalid(); + return n; + } catch (NumberFormatException e) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Capture evidence mismatch"); + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 1d9d619c58..60bf388130 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -105,8 +105,8 @@ firemud: connect-token-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS:30000} mail: from: ${SMTP_FROM:no-reply@firemud.com} - verification-url: ${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/auth/verify-email?token=%s} - reset-url: ${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password?token=%s} + verification-url: ${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/verify-email#token=%s} + reset-url: ${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password#token=%s} management: health: diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 88bd60ebc9..1056a8c305 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -64,8 +64,8 @@ firemud: enabled: ${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} mail: from: no-reply@firemud.local - verification-url: http://localhost:8080/auth/verify-email?token=%s - reset-url: http://localhost:8080/reset-password?token=%s + verification-url: http://localhost:5173/verify-email#token=%s + reset-url: http://localhost:5173/reset-password#token=%s payment: stripe-api-key: test-key platform-fee-percent: 5 diff --git a/services/account-service/src/main/resources/db/migration/V1048.1__account_tenant_role_operations.sql b/services/account-service/src/main/resources/db/migration/V1048.1__account_tenant_role_operations.sql new file mode 100644 index 0000000000..c75a4e6b9b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1048.1__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/main/resources/db/migration/V1049__account_character_create_source_protections.sql b/services/account-service/src/main/resources/db/migration/V1049__account_character_create_source_protections.sql new file mode 100644 index 0000000000..40e0cf32b4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1049__account_character_create_source_protections.sql @@ -0,0 +1,306 @@ +-- Private CHARACTER_CREATE owner storage. No RPC, controller, scheduled reconciler or default +-- composition is enabled here. Existing source-writer serialization remains authoritative. +CREATE TABLE account_character_create_intents ( + operation_id UUID PRIMARY KEY CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace TEXT NOT NULL CHECK (length(target_namespace) BETWEEN 1 AND 63), + account_uuid UUID NOT NULL CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'), + tenant_uuid UUID NOT NULL CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + connect_scope_id TEXT NOT NULL CHECK (length(connect_scope_id) BETWEEN 1 AND 2048), + purpose TEXT NOT NULL CHECK (purpose = 'CHARACTER_CREATE'), + action_bytes BYTEA NOT NULL CHECK (octet_length(action_bytes) BETWEEN 1 AND 33554432), + mutation_digest TEXT NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + original_source_readback BYTEA NOT NULL CHECK (octet_length(original_source_readback) BETWEEN 1 AND 33554432), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE account_character_create_protections ( + protection_id UUID PRIMARY KEY CHECK (protection_id <> '00000000-0000-0000-0000-000000000000'), + operation_id UUID NOT NULL UNIQUE REFERENCES account_character_create_intents(operation_id), + protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE CHECK (protection_fence > 0), + acquired_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + membership_snapshot BYTEA NOT NULL CHECK (octet_length(membership_snapshot) BETWEEN 1 AND 1048576), + entitlement_snapshot BYTEA NOT NULL CHECK (octet_length(entitlement_snapshot) BETWEEN 1 AND 1048576) +); +CREATE TABLE account_character_create_settlements ( + protection_id UUID PRIMARY KEY REFERENCES account_character_create_protections(protection_id), + protection_fence BIGINT NOT NULL, + operation_id UUID NOT NULL UNIQUE REFERENCES account_character_create_intents(operation_id), + original_membership_snapshot BYTEA NOT NULL, + original_entitlement_snapshot BYTEA NOT NULL, + original_action BYTEA NOT NULL, + original_source_readback BYTEA NOT NULL, + entity_terminal_id UUID NOT NULL CHECK (entity_terminal_id <> '00000000-0000-0000-0000-000000000000'), + entity_terminal_fence BIGINT NOT NULL CHECK (entity_terminal_fence > 0), + outcome TEXT NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 201326592), + terminal_digest TEXT NOT NULL CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- [jooq ignore start] +-- H2 DDL emulation maps PostgreSQL TEXT to CLOB; retain this native uniqueness constraint. +ALTER TABLE account_character_create_intents + ADD CONSTRAINT account_character_create_intents_request_key + UNIQUE (target_namespace, account_uuid, request_id); + +CREATE FUNCTION account_character_create_source_keys(account_value UUID, tenant_value UUID) +RETURNS TEXT[] LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT ARRAY['ISSUER:firemud-account-service', 'ACCOUNT:' || account_value::TEXT, + 'GLOBAL_ROLES:' || account_value::TEXT, 'TENANT:' || tenant_value::TEXT, + 'MEMBERSHIP:' || account_value::TEXT || '/' || tenant_value::TEXT]; +$$; + +CREATE FUNCTION account_character_create_lock_acquisition_sources(account_value UUID, tenant_value UUID) +RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE key_value TEXT; +BEGIN + FOR key_value IN SELECT value FROM unnest(account_character_create_source_keys(account_value, tenant_value)) value + ORDER BY account_publication_authorization_source_sort_key(value) + LOOP + INSERT INTO account_draft_authorization_source_locks(source_key) + VALUES (key_value) ON CONFLICT DO NOTHING; + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = key_value FOR UPDATE NOWAIT; + END LOOP; +END; +$$; + +-- Purpose-local strict protobuf reader, not a general decoding/authorization API. All known +-- CHARACTER_CREATE messages use only scalar nonnegative int64 and length-delimited fields. +-- Reject duplicate/out-of-order/unknown fields, wrong wire types, nonminimal and overflowing +-- varints, truncation, and empty explicitly encoded defaults. Maximum schema is thirteen fields. +CREATE FUNCTION account_character_create_wire_fields(payload BYTEA, wire_types INTEGER[]) +RETURNS BYTEA[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE fields BYTEA[] := array_fill(NULL::BYTEA, ARRAY[cardinality(wire_types)]); + offset_value INTEGER := 0; tag_value INTEGER; field_value INTEGER; previous_field INTEGER := 0; + wire_value INTEGER; byte_value INTEGER; number_value NUMERIC; multiplier NUMERIC; + count_value INTEGER; size_value INTEGER; output_value BYTEA; +BEGIN + IF cardinality(wire_types) NOT BETWEEN 1 AND 13 OR octet_length(payload) > 201326592 THEN + RAISE EXCEPTION 'Invalid CHARACTER_CREATE wire bound' USING ERRCODE = '23514'; + END IF; + WHILE offset_value < octet_length(payload) LOOP + tag_value := get_byte(payload, offset_value); offset_value := offset_value + 1; + field_value := tag_value / 8; wire_value := tag_value % 8; + IF tag_value >= 128 OR field_value <= previous_field + OR field_value > cardinality(wire_types) + OR wire_types[field_value] IS DISTINCT FROM wire_value THEN + RAISE EXCEPTION 'Invalid CHARACTER_CREATE wire field' USING ERRCODE = '23514'; + END IF; + previous_field := field_value; number_value := 0; multiplier := 1; count_value := 0; + LOOP + IF offset_value >= octet_length(payload) OR count_value >= 9 THEN + RAISE EXCEPTION 'Invalid CHARACTER_CREATE wire varint' USING ERRCODE = '23514'; + END IF; + byte_value := get_byte(payload, offset_value); offset_value := offset_value + 1; + number_value := number_value + (byte_value % 128) * multiplier; + count_value := count_value + 1; + EXIT WHEN byte_value < 128; + multiplier := multiplier * 128; + END LOOP; + IF (count_value > 1 AND byte_value = 0) OR number_value <= 0 + OR number_value > 9223372036854775807 THEN + RAISE EXCEPTION 'Noncanonical CHARACTER_CREATE wire value' USING ERRCODE = '23514'; + END IF; + IF wire_value = 0 THEN + output_value := convert_to(number_value::BIGINT::TEXT, 'UTF8'); + ELSIF wire_value = 2 THEN + IF number_value > octet_length(payload) - offset_value THEN + RAISE EXCEPTION 'Truncated CHARACTER_CREATE wire value' USING ERRCODE = '23514'; + END IF; + size_value := number_value::INTEGER; + output_value := substring(payload FROM offset_value + 1 FOR size_value); + offset_value := offset_value + size_value; + ELSE + RAISE EXCEPTION 'Unsupported CHARACTER_CREATE wire type' USING ERRCODE = '23514'; + END IF; + fields[field_value] := output_value; + END LOOP; + RETURN fields; +END; +$$; + +CREATE FUNCTION account_character_create_terminal_binding( + terminal BYTEA, original account_character_create_intents, + protection account_character_create_protections, + terminal_id UUID, terminal_fence BIGINT, outcome TEXT) +RETURNS BOOLEAN LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE t BYTEA[]; request_fields BYTEA[]; selector_fields BYTEA[]; reference_fields BYTEA[]; + original_fields BYTEA[]; protection_fields BYTEA[]; remote_fields BYTEA[]; + expected_original BYTEA[]; remote_index INTEGER; required_index INTEGER; +BEGIN + t := account_character_create_wire_fields(terminal, ARRAY[2,2,2,2,2,2,0,2,2,0,2,2,2]); + FOREACH required_index IN ARRAY ARRAY[1,2,3,4,5,6,7,9,10,11,13] LOOP + IF t[required_index] IS NULL THEN RETURN FALSE; END IF; + END LOOP; + IF convert_from(t[9], 'UTF8') IS DISTINCT FROM terminal_id::TEXT + OR convert_from(t[10], 'UTF8') IS DISTINCT FROM terminal_fence::TEXT + OR convert_from(t[13], 'UTF8') !~ '^sha256:[0-9a-f]{64}$' + OR convert_from(t[6], 'UTF8') IS DISTINCT FROM (convert_from(t[6], 'UTF8')::UUID)::TEXT + OR convert_from(t[6], 'UTF8') = '00000000-0000-0000-0000-000000000000' + OR convert_from(t[11], 'UTF8') !~ 'Z$' + OR convert_from(t[11], 'UTF8')::TIMESTAMPTZ <= 'epoch'::TIMESTAMPTZ THEN RETURN FALSE; END IF; + IF outcome = 'COMMITTED' THEN + IF t[7] IS DISTINCT FROM convert_to('1', 'UTF8') OR t[8] IS NULL OR t[12] IS NOT NULL + OR convert_from(t[8], 'UTF8') IS DISTINCT FROM (convert_from(t[8], 'UTF8')::UUID)::TEXT + OR convert_from(t[8], 'UTF8') = '00000000-0000-0000-0000-000000000000' THEN RETURN FALSE; END IF; + ELSIF outcome = 'ABORTED' THEN + IF t[7] IS DISTINCT FROM convert_to('2', 'UTF8') OR t[12] IS NULL OR t[8] IS NOT NULL + OR convert_from(t[12], 'UTF8') IS DISTINCT FROM (convert_from(t[12], 'UTF8')::UUID)::TEXT + OR convert_from(t[12], 'UTF8') = '00000000-0000-0000-0000-000000000000' THEN RETURN FALSE; END IF; + ELSE RETURN FALSE; END IF; + expected_original := ARRAY[convert_to(original.target_namespace, 'UTF8'), + convert_to(original.operation_id::TEXT, 'UTF8'), convert_to(original.request_id::TEXT, 'UTF8'), + convert_to(original.connect_scope_id, 'UTF8'), convert_to(original.account_uuid::TEXT, 'UTF8'), + convert_to(original.purpose, 'UTF8'), original.action_bytes, + convert_to(original.mutation_digest, 'UTF8'), original.original_source_readback]; + original_fields := account_character_create_wire_fields(t[2], ARRAY[2,2,2,2,2,2,2,2,2]); + IF original_fields IS DISTINCT FROM expected_original THEN RETURN FALSE; END IF; + protection_fields := account_character_create_wire_fields(t[3], ARRAY[2,2,0,2,2,2]); + IF protection_fields[1] IS DISTINCT FROM t[2] + OR protection_fields[2] IS DISTINCT FROM convert_to(protection.protection_id::TEXT, 'UTF8') + OR protection_fields[3] IS DISTINCT FROM convert_to(protection.protection_fence::TEXT, 'UTF8') + OR protection_fields[4] IS NULL + OR convert_from(protection_fields[4], 'UTF8')::TIMESTAMPTZ IS DISTINCT FROM protection.acquired_at + OR protection_fields[5] IS DISTINCT FROM protection.membership_snapshot + OR protection_fields[6] IS DISTINCT FROM protection.entitlement_snapshot THEN RETURN FALSE; END IF; + request_fields := account_character_create_wire_fields(t[1], ARRAY[2,2,2,2]); + IF array_position(request_fields, NULL::BYTEA) IS NOT NULL THEN RETURN FALSE; END IF; + selector_fields := account_character_create_wire_fields(request_fields[1], ARRAY[2,2,2]); + IF selector_fields IS DISTINCT FROM ARRAY[expected_original[1], expected_original[2], expected_original[8]] THEN RETURN FALSE; END IF; + reference_fields := account_character_create_wire_fields(request_fields[2], ARRAY[2,0]); + IF reference_fields IS DISTINCT FROM ARRAY[protection_fields[2], protection_fields[3]] THEN RETURN FALSE; END IF; + FOR remote_index IN 4..5 LOOP + remote_fields := account_character_create_wire_fields(t[remote_index], ARRAY[2,2,0,2,2]); + IF array_position(remote_fields, NULL::BYTEA) IS NOT NULL + OR remote_fields[1] IS DISTINCT FROM t[3] + OR convert_from(remote_fields[2], 'UTF8') IS DISTINCT FROM (convert_from(remote_fields[2], 'UTF8')::UUID)::TEXT + OR convert_from(remote_fields[2], 'UTF8') = '00000000-0000-0000-0000-000000000000' + OR convert_from(remote_fields[4], 'UTF8') !~ 'Z$' + OR convert_from(remote_fields[4], 'UTF8')::TIMESTAMPTZ <= 'epoch'::TIMESTAMPTZ THEN RETURN FALSE; END IF; + reference_fields := account_character_create_wire_fields(request_fields[remote_index - 1], ARRAY[2,0]); + IF reference_fields IS DISTINCT FROM ARRAY[remote_fields[2], remote_fields[3]] THEN RETURN FALSE; END IF; + END LOOP; + RETURN TRUE; +END; +$$; + +CREATE FUNCTION account_character_create_lock_settlement_sources(account_value UUID, tenant_value UUID) +RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE key_value TEXT; locked_key TEXT; +BEGIN + -- Settlement locks exactly the existing serialization identities. Calling the acquisition + -- helper would incorrectly ask an operation to authorize mutation of its own held sources. + FOR key_value IN SELECT value FROM unnest(account_character_create_source_keys(account_value, tenant_value)) value + ORDER BY account_publication_authorization_source_sort_key(value) + LOOP + SELECT source_key INTO locked_key FROM account_draft_authorization_source_locks + WHERE source_key = key_value FOR UPDATE NOWAIT; + IF NOT FOUND THEN + RAISE EXCEPTION 'Character creation source serialization row is missing' USING ERRCODE = '55P03'; + END IF; + END LOOP; +END; +$$; + +CREATE FUNCTION account_character_create_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_character_create_protections protection + JOIN account_character_create_intents intent USING (operation_id) + WHERE account_character_create_source_keys(intent.account_uuid, intent.tenant_uuid) && source_keys + AND NOT EXISTS (SELECT 1 FROM account_character_create_settlements settlement + WHERE settlement.protection_id = protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Character creation remains protected pending an original definitive Entity terminal' + USING ERRCODE = '55P03'; + END IF; +END; +$$; + +CREATE FUNCTION account_character_create_protection_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_character_create_intents%ROWTYPE; membership JSONB; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Character creation protection requires READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT original FROM account_character_create_intents WHERE operation_id = NEW.operation_id; + PERFORM account_character_create_lock_acquisition_sources(original.account_uuid, original.tenant_uuid); + membership := convert_from(NEW.membership_snapshot, 'UTF8')::JSONB; + IF membership->>'accountId' IS DISTINCT FROM original.account_uuid::TEXT + OR membership->>'tenantId' IS DISTINCT FROM original.tenant_uuid::TEXT + OR membership->>'issuerId' IS DISTINCT FROM 'firemud-account-service' + OR membership->>'realmGrantApplicability' IS DISTINCT FROM 'NOT_APPLICABLE_PUBLIC_PRODUCTION' + OR membership->>'membershipExists' IS DISTINCT FROM 'true' + OR membership->>'membershipLifecycleState' IS DISTINCT FROM 'ACTIVE' + OR membership->>'gameplayAdmissionAllowed' IS DISTINCT FROM 'true' THEN + RAISE EXCEPTION 'Character creation membership snapshot differs from the original' USING ERRCODE = '23514'; + END IF; + NEW.acquired_at := clock_timestamp(); + RETURN NEW; +END; +$$; +CREATE TRIGGER account_character_create_protection_binding BEFORE INSERT ON account_character_create_protections + FOR EACH ROW EXECUTE FUNCTION account_character_create_protection_guard(); + +CREATE FUNCTION account_character_create_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_character_create_intents%ROWTYPE; protection account_character_create_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_character_create_intents WHERE operation_id = NEW.operation_id; + PERFORM account_character_create_lock_settlement_sources(original.account_uuid, original.tenant_uuid); + SELECT * INTO STRICT protection FROM account_character_create_protections + WHERE protection_id = NEW.protection_id FOR UPDATE; + IF protection.operation_id IS DISTINCT FROM NEW.operation_id + OR protection.protection_fence IS DISTINCT FROM NEW.protection_fence + OR protection.membership_snapshot IS DISTINCT FROM NEW.original_membership_snapshot + OR protection.entitlement_snapshot IS DISTINCT FROM NEW.original_entitlement_snapshot + OR original.action_bytes IS DISTINCT FROM NEW.original_action + OR original.original_source_readback IS DISTINCT FROM NEW.original_source_readback THEN + RAISE EXCEPTION 'Character creation settlement differs from original protection' USING ERRCODE = '23514'; + END IF; + IF NOT account_character_create_terminal_binding(NEW.terminal_bytes, original, protection, + NEW.entity_terminal_id, NEW.entity_terminal_fence, NEW.outcome) THEN + RAISE EXCEPTION 'Character creation terminal bytes are not the exact definitive original' USING ERRCODE = '23514'; + END IF; + NEW.recorded_at := clock_timestamp(); + RETURN NEW; +END; +$$; +CREATE TRIGGER account_character_create_settlement_binding BEFORE INSERT ON account_character_create_settlements + FOR EACH ROW EXECUTE FUNCTION account_character_create_settlement_guard(); + +DO $migration$ +DECLARE table_name TEXT; original TEXT; anchor TEXT; +BEGIN + FOREACH table_name IN ARRAY ARRAY['account_character_create_intents', + 'account_character_create_protections', 'account_character_create_settlements'] LOOP + EXECUTE format('CREATE TRIGGER immutable_owner_rows BEFORE UPDATE OR DELETE ON %I ' + || 'FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard()', table_name); + EXECUTE format('CREATE TRIGGER immutable_owner_truncate BEFORE TRUNCATE ON %I ' + || 'FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard()', table_name); + END LOOP; + anchor := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing Account source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, + E' PERFORM account_character_create_assert_no_pending(source_keys);\n' || anchor); + anchor := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing Account source-change anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ PERFORM account_character_create_assert_no_pending( + ARRAY(SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id)); +$guard$ || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1050__membership_backed_composite_issuance_fence.sql b/services/account-service/src/main/resources/db/migration/V1050__membership_backed_composite_issuance_fence.sql new file mode 100644 index 0000000000..5771c8ad4d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1050__membership_backed_composite_issuance_fence.sql @@ -0,0 +1,561 @@ +-- Keep the Account security source independently sequenced. Composite fence movement has +-- immutable, exact causal provenance; no membership transition is a security mutation. +CREATE TABLE account_leave_operations ( + request_id VARCHAR(256) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL, + caller_binding VARCHAR(512) NOT NULL, + request_digest TEXT NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + status TEXT NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + outcome TEXT CHECK (outcome IN ('LEFT', 'ALREADY_LEFT')), + membership_id BIGINT REFERENCES account_tenant_membership(id) ON DELETE RESTRICT, + before_membership_version BIGINT, + before_membership_generation BIGINT, + before_fence BIGINT, + membership_version BIGINT, + membership_authority_generation BIGINT, + issuance_fence BIGINT, + membership_event_stream_key TEXT, + event_sequence BIGINT, + event_id TEXT, + event_digest TEXT, + audit_event_id UUID REFERENCES account_audit_outbox(audit_event_id) ON DELETE RESTRICT, + audit_payload_digest TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE account_issuance_fence_provenance ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_version BIGINT NOT NULL CHECK (source_version = issuance_fence), + prior_fence BIGINT NOT NULL CHECK (prior_fence >= 0), + cause_kind TEXT NOT NULL CHECK (cause_kind IN ('BASELINE', 'CUTOVER', 'ACCOUNT', 'MEMBERSHIP')), + tenant_uuid UUID, + source_stream_key VARCHAR(2048) NOT NULL, + event_sequence BIGINT NOT NULL CHECK (event_sequence >= 0), + event_id TEXT, + event_digest TEXT, + prior_generation BIGINT NOT NULL CHECK (prior_generation >= 0), + generation BIGINT NOT NULL CHECK (generation > 0), + prior_authority_source_version BIGINT NOT NULL CHECK (prior_authority_source_version >= 0), + authority_source_version BIGINT NOT NULL CHECK (authority_source_version > 0), + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + PRIMARY KEY (account_uuid, issuance_fence), + UNIQUE (source_stream_key, event_sequence), + CHECK ((cause_kind = 'MEMBERSHIP' AND tenant_uuid IS NOT NULL) + OR (cause_kind <> 'MEMBERSHIP' AND tenant_uuid IS NULL)), + CHECK ((event_sequence = 0 AND event_id IS NULL AND event_digest IS NULL) + OR (event_sequence > 0 AND event_id IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +-- A cutover is not reconstructed history. Anchor only the exact currently verifiable V40 +-- security source/fence position; preserve all original rows, event bytes, baselines and xmins. +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM account_authority_source_records s + LEFT JOIN account_authority_issuance_fences f USING (account_uuid) + LEFT JOIN account_authority_generations g ON g.scope_kind = 'ACCOUNT' AND g.account_uuid = s.account_uuid + LEFT JOIN account_authority_outbox_streams stream ON stream.outbox_stream_key = s.outbox_stream_key + WHERE s.scope_kind = 'ACCOUNT' AND ( + f.issuance_fence IS DISTINCT FROM s.current_issuance_fence + OR f.source_version IS DISTINCT FROM s.current_issuance_fence_source_version + OR g.generation IS DISTINCT FROM s.current_generation + OR g.source_version IS DISTINCT FROM s.current_source_version + OR stream.last_sequence IS DISTINCT FROM s.last_outbox_sequence + OR (s.last_outbox_sequence > 0 AND NOT EXISTS ( + SELECT 1 FROM account_authority_outbox_events e + WHERE (e.outbox_stream_key,e.outbox_sequence,e.event_id,e.event_digest) + = (s.outbox_stream_key,s.last_outbox_sequence,s.last_event_id,s.last_event_digest))))) THEN + RAISE EXCEPTION 'Composite fence cutover lacks exact retained owner evidence' USING ERRCODE = '23514'; + END IF; +END; +$$; +INSERT INTO account_issuance_fence_provenance + (account_uuid, issuance_fence, source_version, prior_fence, cause_kind, + source_stream_key, event_sequence, event_id, event_digest, + prior_generation, generation, prior_authority_source_version, authority_source_version) +SELECT account_uuid, current_issuance_fence, current_issuance_fence_source_version, 0, 'CUTOVER', + outbox_stream_key, last_outbox_sequence, last_event_id, last_event_digest, + 0, current_generation, 0, current_source_version +FROM account_authority_source_records WHERE scope_kind = 'ACCOUNT'; + +CREATE FUNCTION account_fence_security_position_matches( + account_id UUID, fence BIGINT, fence_version BIGINT, stream TEXT, sequence BIGINT, + source_event_id TEXT, source_event_digest TEXT) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_issuance_fence_provenance p + WHERE p.account_uuid = account_id AND p.issuance_fence = fence AND p.source_version = fence_version + AND p.cause_kind IN ('BASELINE','CUTOVER','ACCOUNT') AND p.tenant_uuid IS NULL + AND p.source_stream_key = stream AND p.event_sequence = sequence + AND p.event_id IS NOT DISTINCT FROM source_event_id + AND p.event_digest IS NOT DISTINCT FROM source_event_digest); +$$; + +CREATE FUNCTION account_has_current_fence_provenance(account_id UUID, fence BIGINT, fence_version BIGINT) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_authority_issuance_fences f + JOIN account_issuance_fence_provenance p ON p.account_uuid = f.account_uuid + AND p.issuance_fence = f.issuance_fence AND p.source_version = f.source_version + WHERE f.account_uuid = account_id AND f.issuance_fence = fence AND f.source_version = fence_version + AND (p.event_sequence = 0 OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events e + WHERE (e.outbox_stream_key,e.outbox_sequence,e.event_id,e.event_digest) + = (p.source_stream_key,p.event_sequence,p.event_id,p.event_digest)))); +$$; + +CREATE FUNCTION account_fence_provenance_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE previous account_issuance_fence_provenance%ROWTYPE; +BEGIN + IF NEW.created_transaction_id <> txid_current() OR NEW.cause_kind = 'CUTOVER' THEN + RAISE EXCEPTION 'Fence provenance requires its original owner transaction' USING ERRCODE = '23514'; + END IF; + IF NEW.cause_kind = 'BASELINE' THEN + IF NEW.issuance_fence <> 1 OR NEW.source_version <> 1 OR NEW.prior_fence <> 0 + OR NEW.event_sequence <> 0 OR NEW.prior_generation <> 0 OR NEW.generation <> 1 + OR NEW.prior_authority_source_version <> 0 OR NEW.authority_source_version <> 1 + OR NEW.source_stream_key <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR NOT EXISTS (SELECT 1 FROM account_authority_source_records s + WHERE s.account_uuid = NEW.account_uuid AND s.scope_kind = 'ACCOUNT' + AND s.initialization_transaction_id = txid_current() AND s.last_outbox_sequence = 0) THEN + RAISE EXCEPTION 'Fence baseline requires fresh exact Account source' USING ERRCODE = '23514'; + END IF; + ELSE + SELECT * INTO previous FROM account_issuance_fence_provenance + WHERE account_uuid = NEW.account_uuid AND issuance_fence = NEW.prior_fence; + IF previous.account_uuid IS NULL OR NEW.issuance_fence <> NEW.prior_fence + 1 + OR NEW.source_version <> previous.source_version + 1 + OR NEW.generation <> NEW.prior_generation + 1 + OR NEW.authority_source_version <> NEW.prior_authority_source_version + 1 + OR NEW.event_sequence <= 0 THEN + RAISE EXCEPTION 'Fence provenance requires exact previous position and causal advance' USING ERRCODE = '23514'; + END IF; + IF NEW.source_stream_key <> ('account:auth-authority:v1:' || + CASE WHEN NEW.cause_kind = 'ACCOUNT' THEN 'account/' || NEW.account_uuid::TEXT + ELSE 'membership/' || NEW.account_uuid::TEXT || '/' || NEW.tenant_uuid::TEXT END) THEN + RAISE EXCEPTION 'Fence causal stream differs from its exact scope' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_fence_provenance_insert BEFORE INSERT ON account_issuance_fence_provenance +FOR EACH ROW EXECUTE FUNCTION account_fence_provenance_insert_guard(); + +CREATE FUNCTION account_fence_provenance_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Fence provenance is immutable' USING ERRCODE = '55000'; +END; +$$; +CREATE TRIGGER account_fence_provenance_no_change BEFORE UPDATE OR DELETE ON account_issuance_fence_provenance +FOR EACH ROW EXECUTE FUNCTION account_fence_provenance_immutable(); +CREATE TRIGGER account_fence_provenance_no_truncate BEFORE TRUNCATE ON account_issuance_fence_provenance +FOR EACH STATEMENT EXECUTE FUNCTION account_fence_provenance_immutable(); + +CREATE FUNCTION account_source_record_fence_provenance() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.scope_kind = 'ACCOUNT' THEN + INSERT INTO account_issuance_fence_provenance + (account_uuid, issuance_fence, source_version, prior_fence, cause_kind, + source_stream_key,event_sequence,event_id,event_digest, + prior_generation,generation,prior_authority_source_version,authority_source_version) + VALUES (NEW.account_uuid,NEW.current_issuance_fence,NEW.current_issuance_fence_source_version, + CASE WHEN TG_OP = 'INSERT' THEN 0 ELSE NEW.current_issuance_fence - 1 END, + CASE WHEN TG_OP = 'INSERT' THEN 'BASELINE' ELSE 'ACCOUNT' END, + NEW.outbox_stream_key,NEW.last_outbox_sequence,NEW.last_event_id,NEW.last_event_digest, + CASE WHEN TG_OP = 'INSERT' THEN 0 ELSE OLD.current_generation END,NEW.current_generation, + CASE WHEN TG_OP = 'INSERT' THEN 0 ELSE OLD.current_source_version END,NEW.current_source_version); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_source_record_provenance AFTER INSERT OR UPDATE ON account_authority_source_records +FOR EACH ROW EXECUTE FUNCTION account_source_record_fence_provenance(); + +CREATE FUNCTION account_fence_provenance_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE e account_authority_outbox_events%ROWTYPE; payload JSONB; wire TEXT; digest_field TEXT; +BEGIN + IF NOT account_has_current_fence_provenance(NEW.account_uuid,NEW.issuance_fence,NEW.source_version) THEN + RAISE EXCEPTION 'Fence provenance is not the exact committed current position' USING ERRCODE = '23514'; + END IF; + IF NEW.cause_kind = 'BASELINE' THEN RETURN NULL; END IF; + SELECT * INTO e FROM account_authority_outbox_events + WHERE (outbox_stream_key,outbox_sequence,event_id,event_digest) + = (NEW.source_stream_key,NEW.event_sequence,NEW.event_id,NEW.event_digest); + IF e.outbox_stream_key IS NULL THEN + RAISE EXCEPTION 'Fence provenance lacks exact causal event' USING ERRCODE = '23514'; + END IF; + payload := convert_from(e.payload,'UTF8')::JSONB; + IF payload->>'eventId' IS DISTINCT FROM NEW.event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.event_digest + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.source_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.event_sequence::TEXT + OR payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR (NEW.cause_kind = 'MEMBERSHIP' AND payload->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT) THEN + RAISE EXCEPTION 'Fence causal event identity or position differs' USING ERRCODE = '23514'; + END IF; + IF NEW.cause_kind = 'ACCOUNT' THEN + IF payload->>'eventType' IS NULL OR payload->>'eventType' NOT IN ('ACCOUNT_AUTHORITY_CHANGED','ACCOUNT_SECURITY_STATE_CHANGED', + 'PASSWORD_RESET_COMMITTED','LOGOUT_ALL_COMMITTED','ACCOUNT_RESTRICTION_CHANGED') + OR NOT EXISTS (SELECT 1 FROM account_authority_source_records s + WHERE s.scope_kind = 'ACCOUNT' AND s.account_uuid = NEW.account_uuid + AND (s.current_generation,s.current_source_version,s.current_issuance_fence, + s.last_outbox_sequence,s.last_event_id,s.last_event_digest) + = (NEW.generation,NEW.authority_source_version,NEW.issuance_fence, + NEW.event_sequence,NEW.event_id,NEW.event_digest)) THEN + RAISE EXCEPTION 'Security fence provenance differs from security source' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.cause_kind = 'MEMBERSHIP' THEN + -- The existing V1 codec hashes the RFC8785 preimage without the eventDigest member. + -- Its accountId is first, so eventDigest is exactly one comma-prefixed wire member. + wire := convert_from(e.payload,'UTF8'); + digest_field := ',"eventDigest":' || to_json(NEW.event_digest)::TEXT; + IF (length(wire) - length(replace(wire,digest_field,''))) / length(digest_field) <> 1 + OR 'sha256:' || encode(sha256(convert_to(replace(wire,digest_field,''),'UTF8')),'hex') <> NEW.event_digest THEN + RAISE EXCEPTION 'Membership fence event digest differs from its exact wire preimage' USING ERRCODE = '23514'; + END IF; + IF payload->>'requestId' IS DISTINCT FROM e.request_id + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-authority-event/v1' + OR payload->>'sourceScope' IS DISTINCT FROM 'membership/' || NEW.account_uuid::TEXT || '/' || NEW.tenant_uuid::TEXT + OR payload->>'eventType' IS DISTINCT FROM 'MEMBERSHIP_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->'callerBoundAuthorityInvalidated' IS DISTINCT FROM 'true'::JSONB + OR payload->>'membershipAuthorityGeneration' IS DISTINCT FROM NEW.generation::TEXT + OR NOT EXISTS (SELECT 1 FROM account_authority_generations g + WHERE g.scope_kind = 'MEMBERSHIP' AND g.account_uuid = NEW.account_uuid AND g.tenant_uuid = NEW.tenant_uuid + AND (g.generation,g.source_version) = (NEW.generation,NEW.authority_source_version)) + OR NOT EXISTS (SELECT 1 FROM account_leave_operations op + WHERE 'leave:' || op.request_id = e.request_id AND op.account_uuid = NEW.account_uuid AND op.tenant_uuid = NEW.tenant_uuid + AND op.status = 'COMMITTED' AND op.outcome = 'LEFT' + AND (op.before_membership_generation,op.membership_authority_generation,op.before_fence,op.issuance_fence) + = (NEW.prior_generation,NEW.generation,NEW.prior_fence,NEW.issuance_fence) + AND (op.membership_event_stream_key,op.event_sequence,op.event_id,op.event_digest) + = (NEW.source_stream_key,NEW.event_sequence,NEW.event_id,NEW.event_digest)) THEN + RAISE EXCEPTION 'Membership fence requires its exact atomic LEAVE receipt' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_fence_provenance_consistent AFTER INSERT ON account_issuance_fence_provenance +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_fence_provenance_consistency(); + +ALTER TABLE account_authority_source_records DROP CONSTRAINT account_authority_source_current_check; +ALTER TABLE account_authority_source_records ADD CONSTRAINT account_authority_source_current_check CHECK ( + current_generation > 0 AND current_source_version > 0 AND last_outbox_sequence >= 0 + AND current_generation = baseline_generation + last_outbox_sequence + AND current_source_version = baseline_source_version + last_outbox_sequence + AND (scope_kind <> 'ACCOUNT' OR (current_issuance_fence >= baseline_issuance_fence + last_outbox_sequence + AND current_issuance_fence_source_version = current_issuance_fence))); + +CREATE OR REPLACE FUNCTION account_authority_source_fence_consistency_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE s account_authority_source_records%ROWTYPE; +BEGIN + SELECT * INTO s FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid; + IF NOT account_has_current_fence_provenance(NEW.account_uuid,NEW.issuance_fence,NEW.source_version) + OR s.outbox_stream_key IS NULL OR s.current_issuance_fence > NEW.issuance_fence + OR NOT account_fence_security_position_matches(NEW.account_uuid,s.current_issuance_fence, + s.current_issuance_fence_source_version,s.outbox_stream_key,s.last_outbox_sequence,s.last_event_id,s.last_event_digest) THEN + RAISE EXCEPTION 'Account issuance fence advance lacks exact owner source evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_fence_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_leave_operation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE expected_digest TEXT; segments TEXT[]; segment TEXT; framed TEXT := ''; +BEGIN + IF TG_OP IN ('DELETE','TRUNCATE') THEN + RAISE EXCEPTION 'LEAVE operation history is immutable' USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'UPDATE' AND ( + OLD.status = 'COMMITTED' + OR (NEW.request_id,NEW.account_id,NEW.account_uuid,NEW.tenant_uuid,NEW.caller_binding,NEW.request_digest,NEW.created_at) + IS DISTINCT FROM (OLD.request_id,OLD.account_id,OLD.account_uuid,OLD.tenant_uuid,OLD.caller_binding,OLD.request_digest,OLD.created_at)) THEN + RAISE EXCEPTION 'LEAVE operation identity or terminal result is immutable' USING ERRCODE = '23514'; + END IF; + IF NEW.account_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.tenant_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR char_length(NEW.request_id) NOT BETWEEN 1 AND 256 OR NEW.request_id ~ '^[[:space:]]*$' + OR char_length(NEW.caller_binding) NOT BETWEEN 1 AND 512 OR NEW.caller_binding ~ '^[[:space:]]*$' + OR NOT EXISTS (SELECT 1 FROM accounts a WHERE a.id = NEW.account_id AND a.account_uuid = NEW.account_uuid + AND a.account_uuid_source_numeric_id = a.id) THEN + RAISE EXCEPTION 'LEAVE requires exact caller-bound canonical Account identity' USING ERRCODE = '23514'; + END IF; + segments := ARRAY['account-leave-membership/v1','LEAVE',NEW.request_id, + NEW.account_uuid::TEXT,NEW.tenant_uuid::TEXT,NEW.caller_binding]; + FOREACH segment IN ARRAY segments LOOP + framed := framed || octet_length(convert_to(segment,'UTF8'))::TEXT || ':' || segment; + END LOOP; + expected_digest := 'sha256:' || encode(sha256(convert_to(framed,'UTF8')),'hex'); + IF NEW.request_digest <> expected_digest THEN + RAISE EXCEPTION 'LEAVE request digest differs from exact identity' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'LEAVE must begin as an exact pending intent' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'PENDING' THEN + IF num_nonnulls(NEW.outcome,NEW.membership_id,NEW.before_membership_version, + NEW.before_membership_generation,NEW.before_fence,NEW.membership_version, + NEW.membership_authority_generation,NEW.issuance_fence,NEW.membership_event_stream_key, + NEW.event_sequence,NEW.event_id,NEW.event_digest,NEW.audit_event_id,NEW.audit_payload_digest) <> 0 THEN + RAISE EXCEPTION 'Pending LEAVE cannot carry terminal evidence' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.outcome IS NULL OR NEW.before_fence IS NULL OR NEW.issuance_fence IS NULL THEN + RAISE EXCEPTION 'Committed LEAVE requires exact outcome and fence positions' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_leave_identity BEFORE INSERT OR UPDATE OR DELETE ON account_leave_operations +FOR EACH ROW EXECUTE FUNCTION account_leave_operation_guard(); +CREATE TRIGGER account_leave_no_truncate BEFORE TRUNCATE ON account_leave_operations +FOR EACH STATEMENT EXECUTE FUNCTION account_leave_operation_guard(); + +CREATE FUNCTION account_leave_terminal_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE member account_tenant_membership%ROWTYPE; + pair account_membership_pair_authority%ROWTYPE; + event account_authority_outbox_events%ROWTYPE; + prior account_authority_outbox_events%ROWTYPE; + payload JSONB; prior_payload JSONB; +BEGIN + -- The original PENDING insert may have reached its terminal result in this transaction. + -- Check only the terminal transition, never reinterpret historical terminals on replay. + IF NEW.status <> 'COMMITTED' THEN RETURN NULL; END IF; + IF NOT account_has_current_fence_provenance(NEW.account_uuid,NEW.issuance_fence,NEW.issuance_fence) THEN + RAISE EXCEPTION 'LEAVE terminal lacks the exact current composite fence' USING ERRCODE = '23514'; + END IF; + SELECT * INTO member FROM account_tenant_membership + WHERE account_id = NEW.account_id AND tenant_uuid = NEW.tenant_uuid; + IF NEW.outcome = 'ALREADY_LEFT' THEN + IF NEW.before_fence <> NEW.issuance_fence + OR num_nonnulls(NEW.membership_event_stream_key,NEW.event_sequence,NEW.event_id,NEW.event_digest, + NEW.audit_event_id,NEW.audit_payload_digest) <> 0 + OR (member.id IS NULL AND num_nonnulls(NEW.membership_id,NEW.before_membership_version, + NEW.before_membership_generation,NEW.membership_version,NEW.membership_authority_generation) <> 0) + OR (member.id IS NOT NULL AND ( + member.lifecycle_state <> 'INACTIVE' OR member.gameplay_admission_allowed + OR member.tenant_id IS NOT NULL OR member.tenant_provenance_kind <> 'FRESH_GAME_DESIGN' + OR (NEW.membership_id,NEW.before_membership_version,NEW.membership_version, + NEW.before_membership_generation,NEW.membership_authority_generation) + IS DISTINCT FROM (member.id,member.membership_version,member.membership_version, + member.membership_authority_generation,member.membership_authority_generation))) THEN + RAISE EXCEPTION 'Already-left outcome cannot move authority or invent a transition' USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + SELECT * INTO pair FROM account_membership_pair_authority + WHERE account_uuid = NEW.account_uuid AND tenant_uuid = NEW.tenant_uuid; + SELECT * INTO event FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.membership_event_stream_key AND outbox_sequence = NEW.event_sequence; + SELECT * INTO prior FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.membership_event_stream_key AND outbox_sequence = NEW.event_sequence - 1; + payload := convert_from(event.payload,'UTF8')::JSONB; + prior_payload := convert_from(prior.payload,'UTF8')::JSONB; + IF member.id IS NULL OR pair.account_uuid IS NULL OR event.event_id IS NULL OR prior.event_id IS NULL + OR num_nonnulls(NEW.membership_id,NEW.before_membership_version,NEW.before_membership_generation, + NEW.membership_version,NEW.membership_authority_generation,NEW.event_sequence,NEW.event_id, + NEW.event_digest,NEW.audit_event_id,NEW.audit_payload_digest) <> 10 + OR NEW.membership_version <> NEW.before_membership_version + 1 + OR NEW.membership_authority_generation <> NEW.before_membership_generation + 1 + OR NEW.issuance_fence <> NEW.before_fence + 1 + OR member.tenant_id IS NOT NULL OR member.tenant_provenance_kind <> 'FRESH_GAME_DESIGN' + OR member.lifecycle_state <> 'INACTIVE' OR member.gameplay_admission_allowed + OR (member.id,member.membership_version,member.membership_authority_generation) + IS DISTINCT FROM (NEW.membership_id,NEW.membership_version,NEW.membership_authority_generation) + OR NOT pair.membership_exists OR NOT pair.last_transition_invalidated + OR (pair.membership_version,pair.membership_authority_generation,pair.last_event_sequence,pair.last_event_id,pair.last_event_digest) + IS DISTINCT FROM (NEW.membership_version,NEW.membership_authority_generation,NEW.event_sequence,NEW.event_id,NEW.event_digest) + OR (pair.tenant_provenance_kind,pair.tenant_source_operation_id,pair.tenant_provenance_digest) + IS DISTINCT FROM (member.tenant_provenance_kind,member.tenant_source_operation_id,member.tenant_provenance_digest) + OR (event.event_id,event.event_digest,event.request_id) + IS DISTINCT FROM (NEW.event_id,NEW.event_digest,'leave:' || NEW.request_id) + OR payload->>'eventType' IS DISTINCT FROM 'MEMBERSHIP_CHANGED' + OR payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'membershipLifecycleState' IS DISTINCT FROM 'INACTIVE' + OR payload->'membershipExists' IS DISTINCT FROM 'true'::JSONB + OR payload->'gameplayAdmissionAllowed' IS DISTINCT FROM 'false'::JSONB + OR payload->'callerBoundAuthorityInvalidated' IS DISTINCT FROM 'true'::JSONB + OR payload->'roles' IS DISTINCT FROM '[]'::JSONB + OR payload->'membershipVersion'->>NEW.tenant_uuid::TEXT IS DISTINCT FROM NEW.membership_version::TEXT + OR payload->>'membershipAuthorityGeneration' IS DISTINCT FROM NEW.membership_authority_generation::TEXT + OR payload->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR prior_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR prior_payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR prior_payload->>'eventType' IS NULL + OR prior_payload->>'eventType' NOT IN ('MEMBERSHIP_CHANGED','MEMBERSHIP_AUTHORITY_CHECKPOINT') + OR prior_payload->>'membershipLifecycleState' IS DISTINCT FROM 'ACTIVE' + OR prior_payload->'membershipVersion'->>NEW.tenant_uuid::TEXT IS DISTINCT FROM NEW.before_membership_version::TEXT + OR prior_payload->>'membershipAuthorityGeneration' IS DISTINCT FROM NEW.before_membership_generation::TEXT + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams s + WHERE s.outbox_stream_key = NEW.membership_event_stream_key AND s.last_sequence = NEW.event_sequence) + OR NOT EXISTS (SELECT 1 FROM account_tenant_membership_role_snapshots r + WHERE r.membership_id = member.id AND r.snapshot_version = NEW.membership_version) + OR EXISTS (SELECT 1 FROM account_tenant_membership_role_snapshot_roles r WHERE r.membership_id = member.id) + OR NOT EXISTS (SELECT 1 FROM account_issuance_fence_provenance p + WHERE p.account_uuid = NEW.account_uuid AND p.issuance_fence = NEW.issuance_fence + AND p.prior_fence = NEW.before_fence AND p.cause_kind = 'MEMBERSHIP' AND p.tenant_uuid = NEW.tenant_uuid + AND (p.source_stream_key,p.event_sequence,p.event_id,p.event_digest) + = (NEW.membership_event_stream_key,NEW.event_sequence,NEW.event_id,NEW.event_digest)) + OR NOT EXISTS (SELECT 1 FROM account_audit_outbox a + WHERE a.audit_event_id = NEW.audit_event_id AND a.payload_digest = NEW.audit_payload_digest + AND a.scope = 'tenant' AND a.tenant_identity_version = 2 AND a.tenant_id IS NULL AND a.tenant_uuid = NEW.tenant_uuid + AND a.producer_service = 'account-service' AND a.event_type = 'ACCOUNT_LEFT_TENANT_MEMBERSHIP' + AND a.schema_version = 1 AND a.payload_digest_version = 1 AND a.delivery_status = 'PENDING' + AND a.payload::JSONB->>'accountId' = NEW.account_uuid::TEXT + AND a.payload::JSONB->>'tenantId' = NEW.tenant_uuid::TEXT + AND a.payload::JSONB->>'requestId' = NEW.request_id + AND a.payload::JSONB->>'requestDigest' = NEW.request_digest + AND a.payload::JSONB->>'membershipEventId' = NEW.event_id + AND a.payload::JSONB->>'membershipEventDigest' = NEW.event_digest) THEN + RAISE EXCEPTION 'LEAVE terminal differs from its atomic committed owner evidence' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_leave_terminal AFTER INSERT OR UPDATE ON account_leave_operations +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_leave_terminal_consistency(); + +-- Patch only the named fence-position assumptions in their latest installed definitions. +-- In particular this preserves V1046.11's separately qualified paid-checkpoint changes. +DO $patch_0$ +DECLARE definition TEXT; previous_clause TEXT := $old_0$NEW.current_issuance_fence <> OLD.current_issuance_fence + 1 + OR NEW.current_issuance_fence_source_version <> OLD.current_issuance_fence_source_version + 1$old_0$; + next_clause TEXT := $new_0$NEW.current_issuance_fence <= OLD.current_issuance_fence + OR NEW.current_issuance_fence_source_version <> NEW.current_issuance_fence + OR NOT EXISTS (SELECT 1 FROM account_authority_issuance_fences f + JOIN account_issuance_fence_provenance p ON p.account_uuid = f.account_uuid + AND p.issuance_fence = f.issuance_fence - 1 AND p.source_version = f.source_version - 1 + WHERE f.account_uuid = NEW.account_uuid + AND f.issuance_fence = NEW.current_issuance_fence + AND f.source_version = NEW.current_issuance_fence_source_version)$new_0$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_authority_source_record_update_guard()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_authority_source_record_update_guard (0)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_0$; +DO $patch_1$ +DECLARE definition TEXT; previous_clause TEXT := $old_1$IF fence_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR fence_row.source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version THEN$old_1$; + next_clause TEXT := $new_1$IF fence_row.issuance_fence < NEW.current_issuance_fence + OR NOT account_has_current_fence_provenance(NEW.account_uuid,fence_row.issuance_fence,fence_row.source_version) + OR NOT account_fence_security_position_matches(NEW.account_uuid,NEW.current_issuance_fence, + NEW.current_issuance_fence_source_version,NEW.outbox_stream_key,NEW.last_outbox_sequence, + NEW.last_event_id,NEW.last_event_digest) THEN$new_1$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_authority_source_record_consistency_guard()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_authority_source_record_consistency_guard (1)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_1$; +DO $patch_2$ +DECLARE definition TEXT; previous_clause TEXT := $old_2$ account_source account_authority_source_records%ROWTYPE;$old_2$; + next_clause TEXT := $new_2$ account_source account_authority_source_records%ROWTYPE; + composite_fence account_authority_issuance_fences%ROWTYPE;$new_2$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_paid_membership_checkpoint_consistency()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_paid_membership_checkpoint_consistency (2)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_2$; +DO $patch_3$ +DECLARE definition TEXT; previous_clause TEXT := $old_3$ IF issuer_source.scope_kind IS DISTINCT FROM 'ISSUER'$old_3$; + next_clause TEXT := $new_3$ SELECT * INTO composite_fence FROM account_authority_issuance_fences + WHERE account_uuid = pair.account_uuid FOR SHARE; + IF issuer_source.scope_kind IS DISTINCT FROM 'ISSUER' $new_3$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_paid_membership_checkpoint_consistency()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_paid_membership_checkpoint_consistency (3)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_3$; +DO $patch_4$ +DECLARE definition TEXT; previous_clause TEXT := $old_4$AND (fence.issuance_fence, fence.source_version) + = (account_source.current_issuance_fence, account_source.current_issuance_fence_source_version)$old_4$; + next_clause TEXT := $new_4$AND account_has_current_fence_provenance(pair.account_uuid,fence.issuance_fence,fence.source_version) + AND account_fence_security_position_matches(pair.account_uuid,account_source.current_issuance_fence, + account_source.current_issuance_fence_source_version,account_source.outbox_stream_key, + account_source.last_outbox_sequence,account_source.last_event_id,account_source.last_event_digest)$new_4$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_paid_membership_checkpoint_consistency()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_paid_membership_checkpoint_consistency (4)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_4$; +DO $patch_5$ +DECLARE definition TEXT; previous_clause TEXT := $old_5$ account_source.current_issuance_fence, pair.membership_authority_generation, member.lifecycle_state,$old_5$; + next_clause TEXT := $new_5$ composite_fence.issuance_fence, pair.membership_authority_generation, member.lifecycle_state,$new_5$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_paid_membership_checkpoint_consistency()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact single fence clause in account_paid_membership_checkpoint_consistency (5)'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_5$; + +-- V157 is the current gameplay delegation guard, replacing the earlier V147/V153 versions. +DO $patch_gameplay$ +DECLARE definition TEXT; previous_clause TEXT := $old$ OR current_issuance_fence <> source_account_issuance_fence + OR current_fence_source_version <> source_account_fence_source_version$old$; + next_clause TEXT := $new$ OR NOT account_has_current_fence_provenance(NEW.account_uuid,current_issuance_fence,current_fence_source_version) + OR NOT EXISTS (SELECT 1 FROM account_authority_source_records s + WHERE s.scope_kind = 'ACCOUNT' AND s.account_uuid = NEW.account_uuid + AND s.current_issuance_fence = source_account_issuance_fence + AND s.current_issuance_fence_source_version = source_account_fence_source_version + AND account_fence_security_position_matches(NEW.account_uuid,s.current_issuance_fence, + s.current_issuance_fence_source_version,s.outbox_stream_key,s.last_outbox_sequence, + s.last_event_id,s.last_event_digest))$new$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_gameplay_delegation_authority_guard()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected exact current gameplay delegation fence equality'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_gameplay$; + +-- A later security operation may start from unchanged generation-one security history after +-- a genuine membership invalidation. This is NOT the original Account/birth insertion guard: +-- keep all pristine security stream/baseline identity checks, and prove the live fence separately. +DO $patch_security_claim$ +DECLARE definition TEXT; previous_clause TEXT := $old$ IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.expected_fence <> 1 OR NEW.expected_fence_source_version <> 1 + OR octet_length(NEW.checkpoint_payload) <> 0$old$; + next_clause TEXT := $new$ IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NOT account_has_current_fence_provenance(NEW.account_uuid,NEW.expected_fence,NEW.expected_fence_source_version) + OR NOT account_fence_security_position_matches(NEW.account_uuid,1,1,key,0,NULL,NULL) + OR octet_length(NEW.checkpoint_payload) <> 0$new$; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) || '.account_security_state_operation_guard()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition,previous_clause,''))) / length(previous_clause) <> 1 THEN + RAISE EXCEPTION 'Expected one later security-operation pristine source claim'; + END IF; + EXECUTE replace(definition,previous_clause,next_clause); +END; +$patch_security_claim$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1051.1__connect_token_issuance_fence_capture.sql b/services/account-service/src/main/resources/db/migration/V1051.1__connect_token_issuance_fence_capture.sql new file mode 100644 index 0000000000..e01e94c0a2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1051.1__connect_token_issuance_fence_capture.sql @@ -0,0 +1,66 @@ +-- Record the original Account fence separately from replay evidence and response ciphertext. +-- Existing receipts retain an absent capture without a data rewrite or backfill. +ALTER TABLE connect_token_issuance_operation + ADD COLUMN issuance_fence_capture_schema TEXT, + ADD COLUMN issuance_fence_capture_account_uuid UUID, + ADD COLUMN issuance_fence_capture_value BIGINT, + ADD COLUMN issuance_fence_capture_source_version BIGINT, + ADD COLUMN issuance_fence_capture_digest BYTEA, + ADD CONSTRAINT connect_token_issuance_fence_capture_shape CHECK ( + num_nonnulls(issuance_fence_capture_schema, issuance_fence_capture_account_uuid, + issuance_fence_capture_value, issuance_fence_capture_source_version, + issuance_fence_capture_digest) = 0 + OR ( + num_nonnulls(issuance_fence_capture_schema, issuance_fence_capture_account_uuid, + issuance_fence_capture_value, issuance_fence_capture_source_version, + issuance_fence_capture_digest) = 5 + AND issuance_fence_capture_schema = 'account-connect-issuance-fence/v1' + AND issuance_fence_capture_account_uuid = account_uuid + AND issuance_fence_capture_account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND issuance_fence_capture_value > 0 + AND issuance_fence_capture_source_version > 0 + AND octet_length(issuance_fence_capture_digest) = 32)); + +-- [jooq ignore start] +CREATE FUNCTION connect_token_issuance_fence_capture_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF num_nonnulls(NEW.issuance_fence_capture_schema, NEW.issuance_fence_capture_account_uuid, + NEW.issuance_fence_capture_value, NEW.issuance_fence_capture_source_version, + NEW.issuance_fence_capture_digest) <> 0 THEN + RAISE EXCEPTION 'Connect fence capture requires an existing pending operation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF (NEW.issuance_fence_capture_schema, NEW.issuance_fence_capture_account_uuid, + NEW.issuance_fence_capture_value, NEW.issuance_fence_capture_source_version, + NEW.issuance_fence_capture_digest) + IS NOT DISTINCT FROM + (OLD.issuance_fence_capture_schema, OLD.issuance_fence_capture_account_uuid, + OLD.issuance_fence_capture_value, OLD.issuance_fence_capture_source_version, + OLD.issuance_fence_capture_digest) THEN + RETURN NEW; + END IF; + IF OLD.issuance_fence_capture_schema IS NOT NULL THEN + RAISE EXCEPTION 'Connect issuance fence capture is immutable' USING ERRCODE = '23514'; + END IF; + IF OLD.status <> 'PENDING' OR NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Connect fence capture requires an existing pending operation' + USING ERRCODE = '23514'; + END IF; + IF NOT account_has_current_fence_provenance(NEW.account_uuid, + NEW.issuance_fence_capture_value, NEW.issuance_fence_capture_source_version) THEN + RAISE EXCEPTION 'Connect fence capture requires current Account provenance' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER connect_token_issuance_fence_capture_mutation +BEFORE INSERT OR UPDATE ON connect_token_issuance_operation +FOR EACH ROW EXECUTE FUNCTION connect_token_issuance_fence_capture_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1051__connect_token_durable_receipts.sql b/services/account-service/src/main/resources/db/migration/V1051__connect_token_durable_receipts.sql new file mode 100644 index 0000000000..53ea4abbd3 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1051__connect_token_durable_receipts.sql @@ -0,0 +1,141 @@ +-- Dormant Account-owned storage. No issuer, registry writer, scheduler or cleanup is activated. +CREATE TABLE connect_token_issuance_operation ( + operation_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL, + connect_scope_id VARCHAR(2048) NOT NULL CHECK (octet_length(connect_scope_id) BETWEEN 1 AND 2048), + request_id VARCHAR(128) NOT NULL CHECK (octet_length(request_id) BETWEEN 1 AND 128), + request_digest_version SMALLINT NOT NULL CHECK (request_digest_version = 1), + request_digest TEXT NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + status TEXT NOT NULL CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED', 'ABORTED')), + token_jti UUID, + token_hash TEXT CHECK (token_hash ~ '^sha256:[0-9a-f]{64}$'), + replay_admission_fence BIGINT CHECK (replay_admission_fence > 0), + issuance_evidence BYTEA, + failure_code TEXT, + reconciliation_blocked BOOLEAN NOT NULL DEFAULT TRUE, + reconciliation_evidence BYTEA, + response_recovery_expires_at TIMESTAMPTZ NOT NULL, + receipt_retain_until TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + terminal_at TIMESTAMPTZ, + UNIQUE (account_uuid, tenant_uuid, connect_scope_id, request_id), + CHECK (response_recovery_expires_at > created_at + AND receipt_retain_until >= response_recovery_expires_at), + CHECK (issuance_evidence IS NULL OR octet_length(issuance_evidence) BETWEEN 1 AND 131072), + CHECK (reconciliation_evidence IS NULL OR octet_length(reconciliation_evidence) BETWEEN 1 AND 131072), + CHECK (reconciliation_blocked OR reconciliation_evidence IS NOT NULL), + CHECK ( + (status = 'PENDING' AND terminal_at IS NULL AND token_jti IS NULL + AND token_hash IS NULL AND replay_admission_fence IS NULL + AND issuance_evidence IS NULL AND failure_code IS NULL) + OR + (status = 'COMMITTED' AND terminal_at IS NOT NULL AND token_jti IS NOT NULL + AND token_hash IS NOT NULL AND replay_admission_fence IS NOT NULL + AND issuance_evidence IS NOT NULL AND failure_code IS NULL) + OR + (status IN ('FAILED', 'ABORTED') AND terminal_at IS NOT NULL AND token_jti IS NULL + AND token_hash IS NULL AND replay_admission_fence IS NULL AND issuance_evidence IS NULL + AND failure_code IS NOT NULL AND octet_length(failure_code) BETWEEN 1 AND 128)) +); + +-- Ciphertext is separate from the compact receipt; plaintext tokens have no storage field. +-- Cryptographic authentication and semantic evidence validation remain issuer responsibilities. +CREATE TABLE connect_token_response_envelope ( + operation_id UUID PRIMARY KEY REFERENCES connect_token_issuance_operation(operation_id) ON DELETE RESTRICT, + encryption_key_id TEXT NOT NULL CHECK (octet_length(encryption_key_id) BETWEEN 1 AND 256), + encryption_version SMALLINT NOT NULL CHECK (encryption_version > 0), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + authenticated_binding BYTEA NOT NULL CHECK (octet_length(authenticated_binding) BETWEEN 1 AND 131072) +); + +-- [jooq ignore start] +CREATE FUNCTION connect_token_operation_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Connect compact receipt cleanup requires an owner safe-watermark implementation' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' OR NOT NEW.reconciliation_blocked + OR NEW.reconciliation_evidence IS NOT NULL THEN + RAISE EXCEPTION 'Connect operation must begin pending and unreconciled' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF (NEW.operation_id, NEW.account_uuid, NEW.tenant_uuid, NEW.connect_scope_id, + NEW.request_id, NEW.request_digest_version, NEW.request_digest, NEW.created_at, + NEW.response_recovery_expires_at, NEW.receipt_retain_until) + IS DISTINCT FROM + (OLD.operation_id, OLD.account_uuid, OLD.tenant_uuid, OLD.connect_scope_id, + OLD.request_id, OLD.request_digest_version, OLD.request_digest, OLD.created_at, + OLD.response_recovery_expires_at, OLD.receipt_retain_until) THEN + RAISE EXCEPTION 'Connect operation identity and retention are immutable' USING ERRCODE = '23514'; + END IF; + IF OLD.status <> 'PENDING' THEN + -- Terminal outcome is permanent, including when current authority later denies replay. + IF (NEW.status, NEW.token_jti, NEW.token_hash, NEW.replay_admission_fence, + NEW.issuance_evidence, NEW.failure_code, NEW.terminal_at) + IS DISTINCT FROM + (OLD.status, OLD.token_jti, OLD.token_hash, OLD.replay_admission_fence, + OLD.issuance_evidence, OLD.failure_code, OLD.terminal_at) THEN + RAISE EXCEPTION 'Connect terminal outcome is immutable' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.status <> 'PENDING' THEN + NEW.terminal_at = CURRENT_TIMESTAMP; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION connect_token_envelope_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + op connect_token_issuance_operation%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Connect response envelope is immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT op FROM connect_token_issuance_operation + WHERE operation_id = CASE WHEN TG_OP = 'DELETE' THEN OLD.operation_id ELSE NEW.operation_id END + FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF op.status <> 'PENDING' THEN + RAISE EXCEPTION 'Connect response cannot be replaced after completion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF op.status NOT IN ('COMMITTED', 'FAILED') OR op.reconciliation_blocked + OR clock_timestamp() < op.response_recovery_expires_at THEN + RAISE EXCEPTION 'Connect response is held or within recovery horizon' USING ERRCODE = '23514'; + END IF; + RETURN OLD; +END; +$$; + +CREATE FUNCTION connect_token_completion_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + op connect_token_issuance_operation%ROWTYPE; +BEGIN + SELECT * INTO STRICT op FROM connect_token_issuance_operation WHERE operation_id = NEW.operation_id; + -- Only an outcome transition requires a retained response; later receipt-only reconciliation is valid. + IF NEW.status IN ('COMMITTED', 'FAILED') AND OLD.status = 'PENDING' + AND NOT EXISTS (SELECT 1 FROM connect_token_response_envelope WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Connect terminal response must be durably recorded before commit' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER connect_token_operation_mutation +BEFORE INSERT OR UPDATE OR DELETE ON connect_token_issuance_operation +FOR EACH ROW EXECUTE FUNCTION connect_token_operation_guard(); +CREATE TRIGGER connect_token_envelope_mutation +BEFORE INSERT OR UPDATE OR DELETE ON connect_token_response_envelope +FOR EACH ROW EXECUTE FUNCTION connect_token_envelope_guard(); +CREATE CONSTRAINT TRIGGER connect_token_terminal_response +AFTER UPDATE ON connect_token_issuance_operation DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION connect_token_completion_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 9e2f789e81..9debc04b28 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -170,8 +170,6 @@ components: connectScopeId: type: string description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. - jti: - type: string requestId: type: string issuedAt: @@ -319,6 +317,8 @@ components: type: string newPassword: type: string + minLength: 6 + maxLength: 100 required: [token, newPassword] UsernameRecoveryRequest: type: object @@ -806,9 +806,9 @@ paths: operationId: verifyEmail description: >- The public POST verifies an account-scoped email token without bearer - authentication. The configured verification email still links to - GET /auth/verify-email, which has no controller mapping; browser - handoff to the public POST remains unavailable. + authentication. Verification emails open the read-only frontend landing + at /verify-email with the token in its fragment. Only explicit user + submission sends the token to this POST endpoint. security: [] requestBody: required: true diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project-v2.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project-v2.lua new file mode 100644 index 0000000000..d22b1fe601 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project-v2.lua @@ -0,0 +1,150 @@ +local MAX_RECORD_BYTES = 8192 +-- Issuer v2: the Java owner verifies the complete retained canonical issuer event, then +-- this script atomically fences that exact prior byte image. Payload stays v1. +-- Account source projections use account.account-generation-projection.v1. + +local function exact_fields(value, required, optional) + if type(value) ~= 'table' then return false end + local allowed = {} + for _, field in ipairs(required) do allowed[field] = true end + for _, field in ipairs(optional or {}) do allowed[field] = true end + for field, _ in pairs(value) do + if type(field) ~= 'string' or not allowed[field] then return false end + end + for _, field in ipairs(required) do + if value[field] == nil then return false end + end + return true +end + +local function positive_decimal(value) + if type(value) ~= 'string' + or string.match(value, '^[1-9][0-9]*$') == nil then + return false + end + return true +end + +local function nonnegative_decimal(value) + return type(value) == 'string' + and (value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil) +end + +local function decrement_decimal(value) + local digits = {} + for index = 1, string.len(value) do + digits[index] = tonumber(string.sub(value, index, index)) + end + local index = #digits + while index > 0 and digits[index] == 0 do + digits[index] = 9 + index = index - 1 + end + if index == 0 then return nil end + digits[index] = digits[index] - 1 + local result = '' + local first = 1 + while first < #digits and digits[first] == 0 do first = first + 1 end + for position = first, #digits do result = result .. tostring(digits[position]) end + return result +end + +local function generation_greater(left, right) + if string.len(left) ~= string.len(right) then + return string.len(left) > string.len(right) + end + return left > right +end + +local function validate_record(record, key) + if type(record) ~= 'string' or string.len(record) == 0 or string.len(record) > MAX_RECORD_BYTES then + return nil + end + local ok, value = pcall(cjson.decode, record) + if not ok or type(value) ~= 'table' then return nil end + + local scope = nil + local scope_id = nil + local expected_stream = nil + local issuer_prefix = 'session:auth:generation:issuer:' + if string.sub(key, 1, string.len(issuer_prefix)) == issuer_prefix then + scope = 'issuer' + scope_id = string.sub(key, string.len(issuer_prefix) + 1) + if scope_id ~= 'firemud-account-service' then return nil end + expected_stream = 'account:auth-authority:v1:issuer/' .. scope_id + else + return nil + end + + local required = { + 'schemaVersion', 'issuerId', 'issuerAuthGeneration', 'sourceVersion', + 'outboxStreamKey', 'lastAppliedSourceOutboxSequence' + } + local optional = {'lastAppliedSourceEventId', 'lastAppliedSourceEventDigest', 'sourceEvent'} + if not exact_fields(value, required, optional) + or value.schemaVersion ~= 'account-auth-issuer-generation-projection/v1' + or value.issuerId ~= scope_id + or not positive_decimal(value.issuerAuthGeneration) + or not positive_decimal(value.sourceVersion) + or value.outboxStreamKey ~= expected_stream + or not nonnegative_decimal(value.lastAppliedSourceOutboxSequence) then return nil end + if value.lastAppliedSourceOutboxSequence == '0' then + if value.issuerAuthGeneration ~= '1' or value.sourceVersion ~= '1' + or value.lastAppliedSourceEventId ~= nil or value.lastAppliedSourceEventDigest ~= nil + or value.sourceEvent ~= nil then return nil end + else + if value.issuerAuthGeneration == '1' or value.sourceVersion == '1' + or type(value.lastAppliedSourceEventId) ~= 'string' + or string.len(value.lastAppliedSourceEventId) == 0 + or type(value.lastAppliedSourceEventDigest) ~= 'string' + or string.match(value.lastAppliedSourceEventDigest, '^sha256:[0-9a-f]+$') == nil + or string.len(value.lastAppliedSourceEventDigest) ~= 71 + or type(value.sourceEvent) ~= 'string' or string.len(value.sourceEvent) == 0 then return nil end + end + + return value +end + +if #KEYS ~= 1 or #ARGV ~= 3 then return -4 end +local mode = ARGV[1] +local expected = ARGV[2] +local candidate = ARGV[3] +if mode == 'ABSENT' then + if expected ~= '' or candidate == '' then return -4 end +elseif mode == 'PRESENT' then + if expected == '' or candidate == '' then return -4 end +elseif mode == 'VERIFY' then + if expected == '' or candidate ~= '' then return -4 end + candidate = expected +else + return -4 +end +if string.len(expected) > MAX_RECORD_BYTES then return -4 end +local key = KEYS[1] +local generation_prefix = 'session:auth:generation:' +if string.len(key) > 256 + or string.sub(key, 1, string.len(generation_prefix)) ~= generation_prefix then return -4 end +local incoming = validate_record(candidate, key) +if not incoming then return -4 end + +local current = redis.call('GET', key) +-- Never overwrite a value different from the exact bytes validated by the owner. +-- This refuses a missing or changed current value and concurrent initialization, without retries. +if mode == 'ABSENT' then + if current then return -3 end +elseif not current or current ~= expected then + return -3 +end +if current then + local existing = validate_record(current, key) + if not existing or redis.call('PTTL', key) ~= -1 then return -5 end + if generation_greater(existing.issuerAuthGeneration, incoming.issuerAuthGeneration) then return -1 end + if existing.issuerAuthGeneration == incoming.issuerAuthGeneration then + if current == candidate then return 0 end + return -2 + end +end + +local stored = redis.call('SET', key, candidate) +if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -3 end +return 1 diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json new file mode 100644 index 0000000000..ff705049a4 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json @@ -0,0 +1,75 @@ +{ + "scriptId": "account.game-session-delegation-authority-project-issuer.v2", + "resourcePath": "redis/lua/account-game-session-delegation-authority-project-v2.lua", + "sha256": "4a19728c0d6f1495adc188f908909a01d6bca0fddb733b9e2c3a8b43f8cdcb85", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "authorityProjection", + "ownedPrefix": "session:auth:generation:issuer:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "expectedMode" + }, + { + "name": "expectedBytes" + }, + { + "name": "candidateBytes" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "PROJECTION_ADVANCED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "EXACT_PROJECTION_RETRY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "STALE_GENERATION", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "EQUAL_GENERATION_CONFLICT", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "CONDITIONAL_STORE_FAILED", + "category": "CONTENTION", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "STORED_PROJECTION_MALFORMED", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "Missing or stale source projection denies delegation use until Account reprojects exact owner evidence.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v2", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountjwtmaterializer/CanonicalMaterializerDriver.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountjwtmaterializer/CanonicalMaterializerDriver.java new file mode 100644 index 0000000000..5bac5841fd --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountjwtmaterializer/CanonicalMaterializerDriver.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.accountjwtmaterializer; + +import com.google.protobuf.Message; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Test-only bridge to the unchanged package-private materializer, with controlled Secret storage. + */ +public final class CanonicalMaterializerDriver { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final ProtectedBinding.Snapshot snapshot; + private final MemorySecretApi secret; + private final BiFunction invoke; + + public CanonicalMaterializerDriver( + String namespace, + String clusterUid, + String namespaceUid, + String trustDigest, + String trustRevision, + String secretUid, + BiFunction invoke) { + this.invoke = invoke; + String peer = "spiffe://firemud/ns/" + namespace + "/sa/jwt-signer-materializer"; + String dns = "account-service." + namespace + ".svc.cluster.local"; + var binding = + new ProtectedBinding.Binding( + trustRevision, + "prod", + "prod-cluster-1", + namespace, + clusterUid, + namespaceUid, + clusterUid, + "jwt-signer-materializer", + namespaceUid, + peer, + "d".repeat(64), + List.of("d".repeat(64)), + trustDigest, + dns + ":6565", + dns, + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + List.of("e".repeat(64)), + Path.of("unused-ca"), + Path.of("unused-certificate"), + Path.of("unused-key"), + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("unused-api-ca"), + Path.of("unused-token")); + snapshot = new ProtectedBinding.Snapshot(binding, "controlled-test-binding"); + var metadata = new LinkedHashMap(); + metadata.put("name", SecretState.NAME); + metadata.put("namespace", namespace); + metadata.put("uid", secretUid); + metadata.put("resourceVersion", "12"); + metadata.put("annotations", new LinkedHashMap()); + var resource = new LinkedHashMap(); + resource.put("apiVersion", "v1"); + resource.put("kind", "Secret"); + resource.put("type", "Opaque"); + resource.put("metadata", metadata); + resource.put("data", new LinkedHashMap()); + secret = new MemorySecretApi(resource, namespace); + } + + public String observe() { + return new Materializer(snapshot, new Owner(), secret).observeSecretOnce().name(); + } + + public String reconcile() { + return new Materializer(snapshot, new Owner(), secret).reconcileOnce().name(); + } + + public int patches() { + return secret.patchCount; + } + + public void loseNextPatchReply() { + secret.throwAfterApply = true; + } + + public byte[] pendingBundle() { + return secret.read().slotBytes(SecretState.PENDING); + } + + private final class Owner implements Materializer.AccountOperations { + public EnrollBootstrapResponse enrollBootstrap() { + return (EnrollBootstrapResponse) + invoke.apply("enroll", EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build()); + } + + public GetCurrentGenerationRequestResponse getCurrentGenerationRequest() { + return (GetCurrentGenerationRequestResponse) + invoke.apply( + "generation", + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build()); + } + + public GetCurrentGenerationRequestResponse recordSecretObservation( + String operation, String digest, String uid, String rv) { + return (GetCurrentGenerationRequestResponse) + invoke.apply( + "observe", + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(operation) + .setOperationDigest(digest) + .setSecretUid(uid) + .setObservedResourceVersion(rv) + .build()); + } + + public RecordGenerationResultResponse recordGenerationResult( + String operation, String digest, String uid, String prior, String observed, String jwk) { + return (RecordGenerationResultResponse) + invoke.apply( + "record", + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(operation) + .setGenerationRequestDigest(digest) + .setSecretUid(uid) + .setExpectedPriorResourceVersion(prior) + .setObservedResourceVersion(observed) + .setPublicJwkJson(jwk) + .build()); + } + + public GetCurrentPromotionRequestResponse getCurrentPromotionRequest() { + return (GetCurrentPromotionRequestResponse) + invoke.apply( + "promotion", + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build()); + } + + public RecordPrivatePromotionResultResponse recordPrivatePromotionResult( + GetCurrentPromotionRequestResponse request, + String uid, + String prior, + String observed, + SignerKeyBundle.PublicIdentity current, + SignerKeyBundle.PublicIdentity previous, + List slots) { + var builder = + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(request.getPromotionOperationId()) + .setPromotionRequestDigest(request.getPromotionRequestDigest()) + .setGenerationOperationId(request.getGenerationOperationId()) + .setGenerationOperationDigest(request.getGenerationOperationDigest()) + .setSecretUid(uid) + .setExpectedPriorResourceVersion(prior) + .setObservedResourceVersion(observed) + .setCurrent(identity(current)) + .addAllResultingSlots(slots); + if (previous != null) builder.setPrevious(identity(previous)); + return (RecordPrivatePromotionResultResponse) invoke.apply("promote", builder.build()); + } + } + + private static PromotionPublicKeyIdentity identity(SignerKeyBundle.PublicIdentity value) { + return PromotionPublicKeyIdentity.newBuilder() + .setGeneration(value.generation()) + .setKid(value.kid()) + .setPublicKeyFingerprint(value.fingerprint()) + .build(); + } + + public byte[] currentBundle() { + return secret.read().slotBytes(SecretState.CURRENT); + } + + private static byte[] json(Object value) { + return JSON.writeValueAsString(value).getBytes(StandardCharsets.UTF_8); + } + + private static final class MemorySecretApi implements Materializer.KubernetesOperations { + private final Map resource; + private final String namespace; + private int patchCount; + private boolean throwAfterApply; + + MemorySecretApi(Map resource, String namespace) { + this.namespace = namespace; + this.resource = resource; + } + + @Override + public void verifyClusterIdentity() {} + + @Override + public SecretState getFixedSecret() { + return read(); + } + + SecretState read() { + return SecretState.parse(json(resource), namespace); + } + + @Override + @SuppressWarnings("unchecked") + public void patchFixedSecret(SecretState before, byte[] mergePatch) { + patchCount++; + try { + JsonNode patch; + try { + patch = JSON.readTree(mergePatch); + } catch (RuntimeException ex) { + throw new IllegalStateException("simulated malformed patch"); + } + JsonNode metadataPatch = patch.get("metadata"); + Map metadata = (Map) resource.get("metadata"); + if (!before.uid().equals(metadata.get("uid")) + || !before.resourceVersion().equals(metadata.get("resourceVersion")) + || !before.uid().equals(metadataPatch.get("uid").textValue()) + || !before.resourceVersion().equals(metadataPatch.get("resourceVersion").textValue())) { + throw new IllegalStateException("simulated stale Secret precondition"); + } + Map annotations = (Map) metadata.get("annotations"); + if (annotations == null) { + annotations = new LinkedHashMap<>(); + metadata.put("annotations", annotations); + } + JsonNode annotationPatch = metadataPatch.get("annotations"); + for (Map.Entry entry : annotationPatch.properties()) { + annotations.put(entry.getKey(), entry.getValue().textValue()); + } + Map data = (Map) resource.get("data"); + for (Map.Entry entry : patch.get("data").properties()) { + if (entry.getValue().isNull()) { + data.remove(entry.getKey()); + } else { + data.put(entry.getKey(), entry.getValue().textValue()); + } + } + int next = Integer.parseInt(before.resourceVersion()) + 1; + metadata.put("resourceVersion", Integer.toString(next)); + if (throwAfterApply) { + throwAfterApply = false; + throw new IllegalStateException("simulated lost patch response"); + } + } finally { + java.util.Arrays.fill(mergePatch, (byte) 0); + } + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index f5952eeb40..dc1ac6d1a4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -20,9 +20,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiFunction; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.PasswordResetToken; @@ -32,6 +34,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; @@ -39,7 +42,11 @@ import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.LatestSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer.LogoutAllResult; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; @@ -58,6 +65,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -224,6 +233,127 @@ void exactRetryRecoversLostResponseWithoutAnySecondMutation() { .isEqualTo(journalBeforeRetry.get("source_change_binding", byte[].class)); } + @ParameterizedTest(name = "preserves both cutoffs when password reset is first: {0}") + @ValueSource(booleans = {true, false}) + void mixesActualResetAndLogoutAllProducersWithImmutableExactReplay(boolean resetFirst) { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + UUID logoutRequest = UUID.randomUUID(); + // The unregistered producer takes already-verified caller evidence from its caller. + String logoutTokenHash = sha256Hex("synthetic logout token:" + logoutRequest); + String profile = "control-ui"; + String logoutDigest = + AccountLogoutRequestDigest.accountLogoutAll(seed.accountUuid(), profile, logoutTokenHash); + String newPassword = "replacement-password"; + + var readback = + new AccountAuthoritySourceEventReadback( + fixture.outbox(), + fixture.operations(), + fixture.logoutAllOperations(), + fixture.securityStateOperations()); + var sourceReader = + new AccountAuthoritySourceReader( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + readback, + fixture.transactionManager()); + var logoutProducer = + new AccountLogoutAllAuthorityEventProducer( + fixture.accounts(), + fixture.authority(), + new AccountAuthoritySourceEvidenceRepository( + fixture.transactionDsl(), fixture.authority(), fixture.outbox()), + fixture.outbox(), + fixture.logoutAllOperations(), + readback, + fixture.transactionDsl(), + fixture.transactionManager()); + BiFunction logout = + (request, expected) -> + logoutProducer.commit( + request, + 1, + logoutDigest, + profile, + logoutTokenHash, + account(fixture, seed.accountId()), + expected); + + var baseline = sourceReader.readCurrent(seed.accountUuid()); + assertThat(baseline.outboxSequence()).isZero(); + assertThat(baseline.latestEvent()).isEmpty(); + assertCutoffState(baseline.sourceState(), seed.accountUuid(), 1L); + + if (resetFirst) { + reset(fixture, seed.rawToken(), newPassword); + } else { + assertThat(logout.apply(logoutRequest, baseline.sourceState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + } + var first = sourceReader.readCurrent(seed.accountUuid()); + assertThat(first.outboxSequence()).isEqualTo(1L); + assertCutoffState(first.sourceState(), seed.accountUuid(), 2L); + var firstEvent = first.latestEvent().orElseThrow(); + Object firstReceipt = + resetFirst ? resetReceipt(fixture, seed) : logoutReceipt(fixture, logoutRequest); + + if (resetFirst) { + assertThat(logout.apply(logoutRequest, first.sourceState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + } else { + reset(fixture, seed.rawToken(), newPassword); + } + var second = sourceReader.readCurrent(seed.accountUuid()); + assertThat(second.outboxSequence()).isEqualTo(2L); + assertThat(second.outboxStreamKey()).isEqualTo(first.outboxStreamKey()); + assertCutoffState(second.sourceState(), seed.accountUuid(), 3L); + assertThat(readAuthority(fixture, seed.accountUuid())).isEqualTo(second.sourceState()); + assertThat(countEvents(fixture, second.outboxStreamKey())).isEqualTo(2L); + assertThat(tokenExists(fixture, seed.rawToken())).isFalse(); + + PasswordResetReceipt resetReceipt = resetReceipt(fixture, seed); + LogoutAllReceipt logoutReceipt = logoutReceipt(fixture, logoutRequest); + assertThat(firstReceipt).isEqualTo(resetFirst ? resetReceipt : logoutReceipt); + assertThat(resetReceipt.outboxSequence()).isEqualTo(resetFirst ? 1L : 2L); + assertThat(logoutReceipt.outboxSequence()).isEqualTo(resetFirst ? 2L : 1L); + assertThat(resetReceipt.issuanceFence()).isEqualTo(resetFirst ? 2L : 3L); + assertThat(resetReceipt.issuanceFenceSourceVersion()).isEqualTo(resetFirst ? 2L : 3L); + assertThat(logoutReceipt.issuanceFence()).isEqualTo(resetFirst ? 3L : 2L); + assertThat(logoutReceipt.issuanceFenceSourceVersion()).isEqualTo(resetFirst ? 3L : 2L); + var historical = sourceReader.readCommittedEvent(seed.accountUuid(), 1L); + assertThat(historical.currentSnapshot()).isEqualTo(second); + assertThat(historical.requestedEvent()).isEqualTo(firstEvent); + var secondEvent = second.latestEvent().orElseThrow(); + assertThat(firstEvent.eventId()) + .isEqualTo(resetFirst ? resetReceipt.eventId() : logoutReceipt.eventId()); + assertThat(secondEvent.eventId()) + .isEqualTo(resetFirst ? logoutReceipt.eventId() : resetReceipt.eventId()); + + StoredState committed = snapshot(fixture, seed); + reset(fixture, seed.rawToken(), newPassword); + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + assertThat(sourceReader.readCommittedEvent(seed.accountUuid(), 1L)).isEqualTo(historical); + assertThat(resetReceipt(fixture, seed)).isEqualTo(resetReceipt); + + assertThat(logout.apply(logoutRequest, second.sourceState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + assertThat(sourceReader.readCommittedEvent(seed.accountUuid(), 1L)).isEqualTo(historical); + assertThat(logoutReceipt(fixture, logoutRequest)).isEqualTo(logoutReceipt); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "different-password")) + .isInstanceOf(OperationConflictException.class); + assertThatThrownBy(() -> logout.apply(UUID.randomUUID(), second.sourceState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class) + .hasMessageContaining("already bound to another logout-all request"); + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + assertThat(sourceReader.readCommittedEvent(seed.accountUuid(), 1L)).isEqualTo(historical); + assertThat(resetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequest)).isEqualTo(logoutReceipt); + } + @Test void concurrentExactRetriesCommitOneSourceMutation() throws Exception { Fixture fixture = newFixture(); @@ -330,6 +460,45 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(sameIntentAfterConflict.get("request_payload", byte[].class)) .isEqualTo(requestBytes); + var exactWaitingIntent = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken()))); + var exactWaitingSource = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes WHERE change_id = " + + "(SELECT source_change_id FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?)", + HexFormat.of().parseHex(tokenHash(seed.rawToken()))); + assertThat(exactWaitingIntent).hasSize(1); + assertThat(exactWaitingSource).hasSize(1); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "waiting-password")) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isEqualTo(exactWaitingIntent); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes WHERE change_id = " + + "(SELECT source_change_id FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?)", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isEqualTo(exactWaitingSource); + assertThat(snapshot(fixture, seed)) + .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 1L, 0L, 0L)); + transaction( fixture.transaction(), () -> { @@ -383,6 +552,245 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(committedV76Change.get("status", String.class)).isEqualTo("SOURCE_COMMITTED"); } + @Test + void mixedCommitOrderRetainsExactWaitingResetAndAllSourceBytesOnRetry() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + DraftAuthorizationFenceBinding binding = draftBinding(seed); + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(binding); + fixture.fences().claimCommitOrder(binding); + return null; + }); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "held-password")) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + var sourceBefore = snapshot(fixture, seed); + var intentBefore = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken()))); + var changeBefore = + fixture.setupDsl().fetch("SELECT * FROM account_draft_authorization_source_changes"); + assertThat(intentBefore).hasSize(1); + assertThat(intentBefore.getFirst().get("status", String.class)).isEqualTo("WAITING"); + assertThat(changeBefore).hasSize(1); + Outcome designOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + var world = ownerOutcome(binding, Owner.WORLD, worldOutcome); + var design = ownerOutcome(binding, Owner.GAME_DESIGN, designOutcome); + transaction( + fixture.transaction(), + () -> { + fixture.fences().recordOwnerReadback(binding, world); + fixture.fences().recordOwnerReadback(binding, design); + return null; + }); + for (int retry = 0; retry < 2; retry++) { + assertThat( + transaction(fixture.transaction(), () -> fixture.fences().readSettlement(binding))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "held-password")) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + // The current owner must also refuse an explicit no-mutation terminal while mixed. + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + var pending = + fixture + .sourceChanges() + .findByTokenHash(tokenHash(seed.rawToken())) + .orElseThrow(); + fixture + .sourceChanges() + .markSourceAborted( + pending, + DraftAuthorizationFenceRepository.SourceChangeAbortReason + .DEFINITIVE_ABORT); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Owner outcomes unresolved"); + assertThat(snapshot(fixture, seed)).isEqualTo(sourceBefore); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isEqualTo(intentBefore); + assertThat( + fixture + .setupDsl() + .fetch("SELECT * FROM account_draft_authorization_source_changes")) + .isEqualTo(changeBefore); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .fences() + .readOwnerResult(binding, Owner.WORLD) + .orElseThrow() + .readback())) + .containsExactly(world.canonicalBytes()); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .fences() + .readOwnerResult(binding, Owner.GAME_DESIGN) + .orElseThrow() + .readback())) + .containsExactly(design.canonicalBytes()); + } + } + } + + @Test + void mixedCommitOrderKeepsLogoutSourceIntentAndOriginalOwnerEvidenceUnchanged() { + // Reuse the real Account/source fixture. Presented token and owner authority are stipulated. + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + DraftAuthorizationFenceBinding binding = draftBinding(seed); + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(binding); + fixture.fences().claimCommitOrder(binding); + return null; + }); + var account = fixture.accounts().findById(seed.accountId()).orElseThrow(); + var expectedState = readAuthority(fixture, seed.accountUuid()); + var producer = + new net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer( + fixture.accounts(), + fixture.authority(), + new AccountAuthoritySourceEvidenceRepository( + fixture.transactionDsl(), fixture.authority(), fixture.outbox()), + fixture.outbox(), + fixture.logoutAllOperations(), + new net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback( + fixture.outbox(), + fixture.operations(), + fixture.logoutAllOperations(), + fixture.securityStateOperations()), + fixture.transactionDsl(), + fixture.transactionManager()); + UUID request = UUID.randomUUID(); + String tokenHash = sha256Hex("synthetic logout token:" + request); + String requestDigest = + net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest.accountLogoutAll( + seed.accountUuid(), "control-ui", tokenHash); + Runnable attempt = + () -> + producer.commit( + request, 1, requestDigest, "control-ui", tokenHash, account, expectedState); + assertThatThrownBy(attempt::run) + .isInstanceOf( + net.firedevops.firemud.accountservice.service + .AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException.class); + var before = snapshot(fixture, seed); + var intent = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_logout_all_draft_source_changes WHERE request_id = ?", + request); + var changes = + fixture.setupDsl().fetch("SELECT * FROM account_draft_authorization_source_changes"); + assertThat(intent).hasSize(1); + assertThat(intent.getFirst().get("status", String.class)).isEqualTo("WAITING"); + assertThat(changes).hasSize(1); + var world = ownerOutcome(binding, Owner.WORLD, worldOutcome); + transaction( + fixture.transaction(), + () -> { + fixture.fences().recordOwnerReadback(binding, world); + return null; + }); + assertThatThrownBy(attempt::run) + .isInstanceOf( + net.firedevops.firemud.accountservice.service + .AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException.class); + var originalWorld = + transaction( + fixture.transaction(), + () -> fixture.fences().readOwnerResult(binding, Owner.WORLD).orElseThrow()); + var design = + ownerOutcome( + binding, + Owner.GAME_DESIGN, + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED); + transaction( + fixture.transaction(), + () -> { + fixture.fences().recordOwnerReadback(binding, design); + return null; + }); + for (int retry = 0; retry < 2; retry++) { + assertThat( + transaction(fixture.transaction(), () -> fixture.fences().readSettlement(binding))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThatThrownBy(attempt::run) + .isInstanceOf( + net.firedevops.firemud.accountservice.service + .AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException + .class); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_logout_all_draft_source_changes WHERE request_id = ?", + request)) + .isEqualTo(intent); + assertThat( + fixture + .setupDsl() + .fetch("SELECT * FROM account_draft_authorization_source_changes")) + .isEqualTo(changes); + var retainedWorld = + transaction( + fixture.transaction(), + () -> fixture.fences().readOwnerResult(binding, Owner.WORLD).orElseThrow()); + assertThat(retainedWorld.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(retainedWorld.readback()).containsExactly(world.canonicalBytes()); + assertThat(retainedWorld.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .fences() + .readOwnerResult(binding, Owner.GAME_DESIGN) + .orElseThrow() + .readback())) + .containsExactly(design.canonicalBytes()); + assertThat( + fixture + .setupDsl() + .fetchCount(org.jooq.impl.DSL.table("account_logout_all_operation_receipts"))) + .isZero(); + assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isZero(); + } + } + } + @Test void overlappingWaitingSourceChangeMakesPasswordResetRetryableAndRollsBack() { Fixture fixture = newFixture(); @@ -532,6 +940,64 @@ void expiredWaitingResetAbortsAndDeletesOnlyItsExactOriginalToken() { return null; }); + var beforeAbortedTransaction = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash)); + var beforeSourceAbort = + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes WHERE change_id = " + + "(SELECT source_change_id FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?)", + HexFormat.of().parseHex(tokenHash)); + assertThat(beforeAbortedTransaction).hasSize(1); + assertThat(beforeSourceAbort).hasSize(1); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + var intent = fixture.sourceChanges().findByTokenHash(tokenHash).orElseThrow(); + fixture + .sourceChanges() + .markSourceAborted( + intent, + DraftAuthorizationFenceRepository.SourceChangeAbortReason.EXPIRED); + assertThat( + fixture + .sourceChanges() + .findByTokenHash(tokenHash) + .orElseThrow() + .status()) + .isEqualTo("SOURCE_ABORTED"); + throw new IllegalStateException("deliberate failure after source abort"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("deliberate failure after source abort"); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash))) + .isEqualTo(beforeAbortedTransaction); + assertThat( + fixture + .setupDsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes WHERE change_id = " + + "(SELECT source_change_id FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?)", + HexFormat.of().parseHex(tokenHash))) + .isEqualTo(beforeSourceAbort); + assertThat(tokenExists(fixture, seed.rawToken())).isTrue(); + assertThat(snapshot(fixture, seed)) + .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 1L, 0L, 0L)); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "expired-password")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Token expired"); @@ -938,6 +1404,27 @@ private ScopeState readAuthority(Fixture fixture, UUID accountUuid) { fixture.transaction(), () -> fixture.authority().read(AuthorityScope.account(accountUuid))); } + private void assertCutoffState(ScopeState state, UUID accountUuid, long revision) { + assertThat(state.scope()).isEqualTo(AuthorityScope.account(accountUuid)); + assertThat(state.generation()).isEqualTo(revision); + assertThat(state.sourceVersion()).isEqualTo(revision); + assertThat(state.issuanceFence().accountId()).isEqualTo(accountUuid); + assertThat(state.issuanceFence().value()).isEqualTo(revision); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(revision); + } + + private PasswordResetReceipt resetReceipt(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), + () -> fixture.operations().findByTokenHash(tokenHash(seed.rawToken())).orElseThrow()); + } + + private LogoutAllReceipt logoutReceipt(Fixture fixture, UUID request) { + return transaction( + fixture.transaction(), + () -> fixture.logoutAllOperations().findByRequestId(request).orElseThrow()); + } + private boolean tokenExists(Fixture fixture, String rawToken) { return transaction( fixture.transaction(), () -> fixture.tokens().findByToken(rawToken).isPresent()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..f9a9064e04 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,1522 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Component fixtures stipulate authenticated current-source capture and authenticated definitive + * owner readback. They do not implement or prove those absent producers, RPC or source-writer + * gates. + */ +class DraftAuthorizationFencePostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + OwnerReadback worldAbort = + ownerReadback(binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {31}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {32}); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + verify(gameDesignClient, times(2)).read(any()); + verify(worldClient).read(any()); + } + + @Test + void mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + OwnerReadback originalWorldCommit = + ownerReadback(binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {41, 42}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {43}); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence(request, originalWorldCommit); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()) + .containsExactly(originalWorldCommit.canonicalBytes())); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + verify(gameDesignClient).read(any()); + verify(worldClient).read(any()); + } + + @Test + void concurrentExactConsumerRetriesReturnTheSameOriginalSettlement() throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + OwnerReadback worldAbort = + ownerReadback(binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {51}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {52}); + CountDownLatch concurrentWorldReads = new CountDownLatch(2); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + concurrentWorldReads.countDown(); + await(concurrentWorldReads); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + var second = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + List attempts = + List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); + assertThat(attempts) + .allSatisfy( + attempt -> { + assertThat(attempt.failure()).isNull(); + assertThat(attempt.settlement()).isEqualTo(Settlement.FAILED_NONPUBLICATION); + }); + } + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + } + + @Test + void concurrentConflictingOwnerEvidenceRejectsRetryAndPreservesWinningBytes() throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {61}); + CountDownLatch concurrentWorldReads = new CountDownLatch(2); + AtomicInteger resultSequence = new AtomicInteger(); + Map returnedWorldResults = new ConcurrentHashMap<>(); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + int resultNumber = resultSequence.incrementAndGet(); + OwnerReadback worldAbort = + ownerReadback( + binding, + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {(byte) (60 + resultNumber)}); + returnedWorldResults.put(request.readRequestId(), worldAbort); + concurrentWorldReads.countDown(); + await(concurrentWorldReads); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + List attempts; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + var second = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + attempts = List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); + } + List successes = + attempts.stream().filter(attempt -> attempt.failure() == null).toList(); + List rejected = + attempts.stream().filter(attempt -> attempt.failure() != null).toList(); + assertThat(successes).hasSize(1); + assertThat(successes.getFirst().settlement()).isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(rejected).hasSize(1); + assertThat(rejected.getFirst().failure()) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> + assertThat(failure.getMessage()) + .isIn( + "Concurrent owner recovery changed immutable evidence", + "Changed owner terminal evidence")); + byte[] storedWorldReadback = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow() + .readback(); + assertThat(returnedWorldResults.values()) + .anySatisfy( + returned -> assertThat(returned.canonicalBytes()).containsExactly(storedWorldReadback)); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + } + + @Test + void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + Context restarted = + new Context( + context.dsl(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isFalse(); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat( + tx(restarted, () -> restarted.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertSourceGuardBlocked(restarted, change); + // Missing GD evidence models timeout/unavailable/absent owner row: no terminality is + // synthesized. + assertThat(tx(restarted, () -> restarted.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {5}); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isTrue(); + tx( + restarted, + () -> { + restarted.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(restarted, () -> restarted.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(restarted, () -> restarted.repository().claimCommitOrder(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + assertThatThrownBy( + () -> owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {22}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(committed.binding()).containsExactly(waiting.binding()); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var replay = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(replay.committedAt()).isEqualTo(committed.committedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {23})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var originalWorld = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + Outcome gameDesignOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + var held = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(held.status()).isEqualTo("WAITING"); + assertThat(held.binding()).containsExactly(waiting.binding()); + assertThat(held.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var replay = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(replay.readback()).containsExactly(originalWorld.readback()); + assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + owner( + context, + binding, + Owner.GAME_DESIGN, + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED, + new byte[] {2}); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertSourceGuardBlocked(context, change); + } + } + + @Test + void changedCompleteBindingsConflictWithoutRewritingOriginal() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(context); + var stored = tx(context, () -> context.repository().reserve(original)); + assertThat(tx(context, () -> context.repository().readSettlement(original))) + .isEqualTo(Settlement.PENDING); + for (int field = 0; field < 6; field++) { + DraftAuthorizationFenceBinding changed = changed(original, field); + assertThatThrownBy(() -> tx(context, () -> context.repository().reserve(changed))) + .isInstanceOf(IllegalArgumentException.class); + } + var replay = tx(context, () -> context.repository().reserve(original)); + assertThat(replay.binding()).containsExactly(stored.binding()); + assertThat(replay.reservedAt()).isEqualTo(stored.reservedAt()); + } + + @Test + void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { + Context context = context(); + DraftAuthorizationFenceBinding b = binding(context); + for (int field = 0; field < 9; field++) { + int changedField = field; + byte[] bytes = field == 6 ? new byte[] {11} : b.gameDesignBinding(); + if (field == 8) { + bytes = + new String(bytes, StandardCharsets.UTF_8) + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8); + } + byte[] gameDesign = bytes; + byte[] input = field == 5 ? new byte[] {10} : gameDesign; + String digest = + field == 7 + ? DraftAuthorizationFenceBinding.digest(new byte[] {12}) + : DraftAuthorizationFenceBinding.digest(input); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .repository() + .reserve( + new DraftAuthorizationFenceBinding( + b.operationId(), + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + b.fenceId(), + b.actorAccountId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "different/base" : b.baseCommitId(), + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources())))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_sources"))) + .isZero(); + } + var stored = tx(context, () -> context.repository().reserve(b)); + assertThat(tx(context, () -> context.repository().reserve(b)).binding()) + .containsExactly(stored.binding()); + } + + @Test + void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(context); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().reserve(original); + context.repository().requestSourceChange(change(original)); + throw new IllegalStateException("injected rollback"); + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> tx(context, () -> context.repository().read(original))) + .isInstanceOf(IllegalArgumentException.class); + tx(context, () -> context.repository().reserve(original)); + tx(context, () -> context.repository().requestSourceChange(change(original))); + DraftAuthorizationFenceBinding independent = binding(context); + tx(context, () -> context.repository().reserve(independent)); + assertThat(tx(context, () -> context.repository().claimCommitOrder(independent)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + } + + @Test + void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var original = tx(context, () -> context.repository().readSourceChange(first)); + + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var exactRetry = tx(context, () -> context.repository().readSourceChange(first)); + assertThat(exactRetry.binding()).containsExactly(original.binding()); + assertThat(exactRetry.requestedAt()).isEqualTo(original.requestedAt()); + + // This storage fixture stipulates definitive owner evidence; it does not authenticate it. + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + tx( + context, + () -> { + context.repository().markSourceCommitted(first); + return null; + }); + assertThat(tx(context, () -> context.repository().requestSourceChange(second))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources() + throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var firstTask = + executor.submit( + () -> + tx( + context, + () -> { + boolean permitted = context.repository().requestSourceChange(first); + firstClaimed.countDown(); + await(secondStarted); + return permitted; + })); + var secondTask = + executor.submit( + () -> { + await(firstClaimed); + secondStarted.countDown(); + assertThatThrownBy( + () -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + }); + assertThat(firstTask.get(15, TimeUnit.SECONDS)).isFalse(); + secondTask.get(15, TimeUnit.SECONDS); + } + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + SourceChange disjoint = change(binding(context)); + assertThat(tx(context, () -> context.repository().requestSourceChange(disjoint))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { + for (boolean commitWins : List.of(true, false)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + CountDownLatch firstOrdered = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> + tx( + context, + () -> { + if (commitWins) { + context.repository().claimCommitOrder(binding); + } else { + context.repository().requestSourceChange(change); + } + firstOrdered.countDown(); + await(secondStarted); + return null; + })); + var second = + executor.submit( + () -> { + await(firstOrdered); + secondStarted.countDown(); + if (commitWins) { + return tx(context, () -> context.repository().requestSourceChange(change)); + } + assertThatThrownBy( + () -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + return false; + }); + first.get(15, TimeUnit.SECONDS); + assertThat(second.get(15, TimeUnit.SECONDS)).isFalse(); + } + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(commitWins ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER); + } + } + + @Test + void originalBindingSurvivesRestartAndAbsenceRemainsUnknownUnderOwnerTransaction() { + Context context = context(); + var binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + Context restarted = + new Context( + context.dsl(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + var restored = + tx(restarted, () -> restarted.repository().readOriginalBinding(binding.operationId())) + .orElseThrow(); + assertThat(restored.canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(tx(restarted, () -> restarted.repository().readOriginalBinding(UUID.randomUUID()))) + .isEmpty(); + assertThatThrownBy(() -> restarted.repository().readOriginalBinding(binding.operationId())) + .isInstanceOf(IllegalStateException.class); + restarted.transaction().setReadOnly(true); + try { + assertThatThrownBy( + () -> + tx( + restarted, + () -> restarted.repository().readOriginalBinding(binding.operationId()))) + .isInstanceOf(IllegalStateException.class); + } finally { + restarted.transaction().setReadOnly(false); + } + assertThatThrownBy( + () -> tx(restarted, () -> restarted.repository().readUnresolvedOperations(null, 0))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> tx(restarted, () -> restarted.repository().readUnresolvedOperations(null, 101))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void discoveryPagesOriginalPendingOperationsAndExcludesEverySettledVector() { + Context context = context(); + var reserved = binding(context); + var committedUnknown = binding(context); + var revokedUnknown = binding(context); + var revokedContradiction = binding(context); + var committed = binding(context); + var mixed = binding(context); + var aborted = binding(context); + var revokedAborted = binding(context); + List all = + List.of( + reserved, + committedUnknown, + revokedUnknown, + revokedContradiction, + committed, + mixed, + aborted, + revokedAborted); + // One timestamp tests the UUID tie-breaker rather than relying on clock resolution. + tx( + context, + () -> { + for (var b : all) context.repository().reserve(b); + return null; + }); + for (var b : List.of(committedUnknown, committed, mixed, aborted)) { + tx(context, () -> context.repository().claimCommitOrder(b)); + } + for (var b : List.of(revokedUnknown, revokedContradiction, revokedAborted)) { + tx(context, () -> context.repository().requestSourceChange(change(b))); + } + owner(context, committedUnknown, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, revokedContradiction, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner( + context, + revokedContradiction, + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {2}); + for (var b : List.of(committed, mixed, aborted, revokedAborted)) { + owner( + context, + b, + Owner.WORLD, + b == committed || b == mixed ? Outcome.COMMITTED : Outcome.DEFINITIVELY_ABORTED, + new byte[] {1}); + owner( + context, + b, + Owner.GAME_DESIGN, + b == committed ? Outcome.COMMITTED : Outcome.DEFINITIVELY_ABORTED, + new byte[] {2}); + } + var expected = + List.of(reserved, committedUnknown, revokedUnknown, revokedContradiction, mixed).stream() + .sorted(java.util.Comparator.comparing(b -> b.operationId().toString())) + .toList(); + var first = tx(context, () -> context.repository().readUnresolvedOperations(null, 2)); + var second = + tx( + context, + () -> context.repository().readUnresolvedOperations(first.getLast().cursor(), 3)); + assertThat(first).hasSize(2); + assertThat(second).hasSize(3); + var combined = java.util.stream.Stream.concat(first.stream(), second.stream()).toList(); + assertThat(combined.stream().map(item -> item.binding().operationId()).toList()) + .containsExactlyElementsOf( + expected.stream().map(DraftAuthorizationFenceBinding::operationId).toList()); + for (int i = 0; i < expected.size(); i++) { + assertThat(combined.get(i).binding().canonicalBytes()) + .containsExactly(expected.get(i).canonicalBytes()); + } + assertThat( + tx( + context, + () -> context.repository().readUnresolvedOperations(second.getLast().cursor(), 2))) + .isEmpty(); + owner(context, committedUnknown, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readUnresolvedOperations(null, 100))) + .extracting(item -> item.binding().operationId()) + .doesNotContain(committedUnknown.operationId()); + } + + @Test + void originalRecoveryRejectsMalformedBytesAndEveryConflictingIdentityColumn() { + for (int field = 0; field < 5; field++) { + Context context = context(); + var b = binding(context); + UUID operation = field == 0 ? UUID.randomUUID() : b.operationId(); + UUID request = field == 1 ? UUID.randomUUID() : b.requestId(); + UUID commit = field == 2 ? UUID.randomUUID() : b.commitId(); + UUID fence = field == 3 ? UUID.randomUUID() : b.fenceId(); + byte[] stored = field == 4 ? new byte[] {1} : b.canonicalBytes(); + // The production guard permits first insertion of opaque bytes; recovery must verify them. + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_fences" + + " (operation_id, request_id, commit_id, fence_id, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, 'RESERVED')", + operation, + request, + commit, + fence, + stored)); + assertThatThrownBy( + () -> tx(context, () -> context.repository().readOriginalBinding(operation))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> tx(context, () -> context.repository().readUnresolvedOperations(null, 10))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn() { + Context context = context(); + var b = binding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var readback = + new OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + b.operationId(), + b.commitId(), + b.fenceId(), + b.inputDigest(), + b.canonicalBytes(), + new byte[] {1}); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks" + + " (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'DEFINITIVELY_ABORTED', ?)", + b.operationId(), + readback.canonicalBytes()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))).isEmpty(); + } + + @Test + void v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults() { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(tx(context, () -> context.repository().readUnresolvedOperations(null, 100))) + .extracting(item -> item.binding().operationId()) + .contains(b.operationId()); + var entity = ownerReadback(b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + // Structurally substituted owner, digest, full binding, result and trailing frames all fail. + for (byte[] invalid : + List.of( + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length - 1), + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length + 1), + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {3}).canonicalBytes(), + ownerReadback(binding(context), Owner.WORLD, Outcome.COMMITTED, new byte[] {3}) + .canonicalBytes())) { + assertThatThrownBy(() -> insertOwner(context, b, "ENTITY", "COMMITTED", invalid)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> insertOwner(context, b, "AUTOMATION", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + assertThatThrownBy( + () -> insertOwner(context, b, "ENTITY", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {4})) + .isInstanceOf(IllegalArgumentException.class); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + } + + @Test + void v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback() { + Context context = context(); + var prior = multiOwnerBinding(context); + var b = + new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + "0", + prior.gameDesignBinding(), + prior.normalizedInput(), + prior.inputDigest(), + prior.sources()) + .withRequiredOwners(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(readback.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + @Test + void rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation() { + for (int sourceShape = 0; sourceShape < 4; sourceShape++) { + Context context = context(); + var b = multiOwnerBinding(context); + var source = b.sources().getFirst(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_fences" + + " (operation_id, request_id, commit_id, fence_id, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, 'RESERVED')", + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + b.canonicalBytes()); + if (sourceShape != 0) { + String key = sourceShape == 2 ? source.key() + "/changed" : source.key(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT (source_key) DO NOTHING", + key); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + key, + sourceShape == 1 ? new byte[] {99} : source.canonicalBytes()); + if (sourceShape == 3) { + String extraKey = source.key() + "/extra"; + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT (source_key) DO NOTHING", + extraKey); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + extraKey, + source.canonicalBytes()); + } + } + context + .dsl() + .execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER'," + + " ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + b.operationId()); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + assertThatThrownBy( + () -> insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + b.operationId())) + .get(0, Integer.class)) + .isZero(); + } + } + + @Test + void v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners() { + Context context = context(); + var b = multiOwnerBinding(context); + for (var labels : + List.of( + List.of("GAME_DESIGN", "WORLD"), + List.of("GAME_DESIGN", "WORLD", "ENTITY", "AUTOMATION"), + List.of("GAME_DESIGN", "WORLD", "WORLD"), + List.of("GAME_DESIGN", "ENTITY", "WORLD"))) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(b.canonicalBytes()); + var output = new java.io.ByteArrayOutputStream(); + for (int i = 0; i < 15 + b.sources().size(); i++) { + DraftAuthorizationFenceBinding.frame(output, reader.bytes()); + } + DraftAuthorizationFenceBinding.frame(output, Integer.toString(labels.size())); + labels.forEach(label -> DraftAuthorizationFenceBinding.frame(output, label)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetch( + "SELECT account_draft_authorization_required_owners(?::bytea)", + output.toByteArray()))) + .isInstanceOf(DataAccessException.class); + } + } + + @Test + void v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering() { + for (boolean commitOrder : List.of(true, false)) { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + if (commitOrder) tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertSourceGuardBlocked(context, change); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(context, () -> context.repository().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + } + + @Test + void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertSourceGuardBlocked(context, change); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_ABORTED'," + + " aborted_at = CURRENT_TIMESTAMP, abort_reason = 'DEFINITIVE_ABORT' WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> + assertThat(result.readback()) + .containsExactly( + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}) + .canonicalBytes())); + } + + @Test + void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { + Context context = context("75"); + var b = binding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var original = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + var checksums = + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history ORDER BY installed_rank"); + String schema = + Objects.requireNonNull(context.dsl().fetchOne("SELECT current_schema()")) + .get(0, String.class); + Flyway.configure() + .dataSource(POSTGRES.dataSource(schema)) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("76") + .load() + .migrate(); + assertThat( + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history WHERE version = '76'")) + .hasSize(1); + assertThat( + context + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '76' ORDER BY installed_rank")) + .isEqualTo(checksums); + assertThat(tx(context, () -> context.repository().read(b)).binding()) + .containsExactly(b.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(original.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + private void insertOwner( + Context context, + DraftAuthorizationFenceBinding binding, + String owner, + String outcome, + byte[] bytes) { + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + owner, + outcome, + bytes)); + } + + private void assertSourceGuardBlocked(Context context, SourceChange change) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + } + + private Context context() { + return context("latest"); + } + + private Context context(String target) { + String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private DraftAuthorizationFenceBinding binding(Context context) { + // Database-owned UUID/provenance satisfies the current Account-before-source lock. + // The captured source epochs and authenticated owner evidence remain fixture stipulations. + UUID suffix = UUID.randomUUID(); + var row = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, email_verified, " + + "login_auth_modes, lifecycle_state) VALUES (?, ?, 'test-verifier', " + + "'player', FALSE, 'PASSWORD,EMAIL_OTP', 'active') RETURNING account_uuid, id, " + + "account_uuid_source_numeric_id, account_uuid_provenance", + "draft-fence-" + suffix, + suffix + "@example.test")); + UUID account = Objects.requireNonNull(row.get("account_uuid", UUID.class)); + assertThat(row.get("id", Long.class)).isPositive(); + assertThat(row.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(row.get("id", Long.class)); + assertThat(row.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}); + DraftCommitBinding complete = + completeBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + "world-payload", + UUID.randomUUID()); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private DraftAuthorizationFenceBinding multiOwnerBinding(Context context) { + var prior = binding(context); + var complete = + DraftCommitBinding.fromStored( + new String(prior.gameDesignBinding(), StandardCharsets.UTF_8), prior.inputDigest()); + var entity = DraftCommitBinding.Owner.ENTITY_MANAGEMENT; + var multi = + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + List.of( + complete.revisions().getFirst(), + new RevisionPayload("1", UUID.randomUUID(), entity, "entity-payload")), + List.of( + complete.affectedUnits().getFirst(), + new AffectedUnit(entity, "entity", "entity-1", "aggregate", "entity-1", "0"))); + return new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + prior.expectedDraftEpoch(), + multi.canonicalBytes(), + multi.canonicalBytes(), + multi.digest(), + prior.sources()) + .withRequiredOwners(); + } + + private DraftAuthorizationFenceBinding changed(DraftAuthorizationFenceBinding b, int field) { + SourceEvidence prior = b.sources().getFirst(); + SourceEvidence changedSource = + new SourceEvidence( + prior.kind(), + prior.scopeId(), + "4", + prior.sourceVersion(), + prior.checkpointStream(), + prior.checkpointSequence(), + prior.evidence()); + DraftCommitBinding priorComplete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + DraftCommitBinding complete = + completeBinding( + field == 1 ? UUID.randomUUID() : b.tenantId(), + field == 2 ? UUID.randomUUID() : b.versionId(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + field == 4 ? "changed-world-payload" : priorComplete.revisions().getFirst().payload(), + field == 5 ? UUID.randomUUID() : priorComplete.revisions().getFirst().revisionId()); + return new DraftAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + field == 0 ? UUID.randomUUID() : b.actorAccountId(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + b.baseCommitId(), + b.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + field == 3 ? List.of(changedSource) : b.sources()); + } + + private DraftCommitBinding completeBinding( + UUID tenant, + UUID version, + UUID request, + UUID commit, + String base, + String payload, + UUID revision) { + return DraftCommitBinding.create( + new TargetProof(tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + base, + List.of( + new RevisionPayload("0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, payload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + } + + private SourceChange change(DraftAuthorizationFenceBinding binding) { + return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + } + + private void owner( + Context context, + DraftAuthorizationFenceBinding b, + Owner owner, + Outcome outcome, + byte[] bytes) { + OwnerReadback readback = ownerReadback(b, owner, outcome, bytes); + tx( + context, + () -> { + context.repository().recordOwnerReadback(b, readback); + return null; + }); + } + + private static OwnerReadback ownerReadback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome, byte[] result) { + return new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static WorldDraftTerminalReadEvidence worldEvidence( + WorldDraftTerminalReadEvidence.Request request, OwnerReadback readback) { + if (readback.outcome() != Outcome.COMMITTED) { + return new WorldDraftTerminalReadEvidence(request, Optional.of(readback)); + } + WorldDraftTerminalReadEvidence response = mock(WorldDraftTerminalReadEvidence.class); + when(response.request()).thenReturn(request); + when(response.ownerReadback()).thenReturn(Optional.of(readback)); + return response; + } + + private static void assertOutsideOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static ReconciliationAttempt reconcileAttempt( + AccountDraftTerminalReconciliationService service, UUID operationId) { + try { + return new ReconciliationAttempt(service.reconcile(operationId).orElseThrow(), null); + } catch (RuntimeException failure) { + return new ReconciliationAttempt(null, failure); + } + } + + private static T tx(Context context, Supplier work) { + return context.transaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Ordering fixture timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DSLContext dsl, + DraftAuthorizationFenceRepository repository, + TransactionTemplate transaction) {} + + private record ReconciliationAttempt(Settlement settlement, RuntimeException failure) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateStoragePostgresIntegrationTest.java new file mode 100644 index 0000000000..18b0bf1a65 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateStoragePostgresIntegrationTest.java @@ -0,0 +1,450 @@ +package integration.net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.*; + +import com.google.protobuf.ByteString; +import java.sql.*; +import java.time.Instant; +import java.util.*; +import net.firedevops.firemud.account.v1.*; +import net.firedevops.firemud.entitymanagement.v1.*; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL storage/binding proof with stipulated source snapshots, not authenticated owners. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountCharacterCreateStoragePostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @BeforeAll + static void migrate() throws Exception { + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas("public") + .defaultSchema("public") + .placeholders(Map.of("serviceSchema", "public")) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .table("flyway_schema_history_account_service") + .target("1048.1") + .load() + .migrate(); + String existing = "ACCOUNT:" + UUID.randomUUID(); + String before; + try (var c = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + try (var p = + c.prepareStatement( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)")) { + p.setString(1, existing); + p.executeUpdate(); + } + try (var p = + c.prepareStatement( + "SELECT to_jsonb(s)::text || '/' || xmin::text FROM account_draft_authorization_source_locks s WHERE source_key=?")) { + p.setString(1, existing); + try (var result = p.executeQuery()) { + assertThat(result.next()).isTrue(); + before = result.getString(1); + } + } + } + var current = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas("public") + .defaultSchema("public") + .placeholders(Map.of("serviceSchema", "public")) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .table("flyway_schema_history_account_service") + .load(); + current.migrate(); + current.validate(); + try (var c = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var p = + c.prepareStatement( + "SELECT to_jsonb(s)::text || '/' || xmin::text FROM account_draft_authorization_source_locks s WHERE source_key=?")) { + p.setString(1, existing); + try (var result = p.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getString(1)).isEqualTo(before); + } + } + } + + private Connection connection() throws SQLException { + return DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + } + + private void execute(Connection c, String sql, Object... args) throws SQLException { + try (var p = c.prepareStatement(sql)) { + for (int i = 0; i < args.length; i++) p.setObject(i + 1, args[i]); + p.execute(); + } + } + + private record Fixture( + UUID account, + UUID tenant, + UUID operation, + UUID protection, + long fence, + byte[] membership, + byte[] entitlement, + ReadOriginalCharacterCreateResponse original, + ReadOriginalCharacterCreateProtectionResponse proof) {} + + private Fixture fixture(Connection c) throws SQLException { + UUID account = UUID.randomUUID(), + tenant = UUID.randomUUID(), + operation = UUID.randomUUID(), + request = UUID.randomUUID(), + protection = UUID.randomUUID(); + byte[] member = + ("{\"accountId\":\"" + + account + + "\",\"tenantId\":\"" + + tenant + + "\",\"issuerId\":\"firemud-account-service\",\"realmGrantApplicability\":\"NOT_APPLICABLE_PUBLIC_PRODUCTION\",\"membershipExists\":true,\"membershipLifecycleState\":\"ACTIVE\",\"gameplayAdmissionAllowed\":true}") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] entitlement = "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + action = {1}, + source = {2}; + String digest = "a".repeat(64); + execute( + c, + "INSERT INTO account_character_create_intents(operation_id,target_namespace,account_uuid,tenant_uuid,request_id,connect_scope_id,purpose,action_bytes,mutation_digest,original_source_readback) VALUES (?,'proof',?,?,?,'scope','CHARACTER_CREATE',?,?,?)", + operation, + account, + tenant, + request, + action, + digest, + source); + execute( + c, + "INSERT INTO account_character_create_protections(protection_id,operation_id,membership_snapshot,entitlement_snapshot) VALUES (?,?,?,?)", + protection, + operation, + member, + entitlement); + long fence; + Instant acquired; + try (var p = + c.prepareStatement( + "SELECT protection_fence,acquired_at FROM account_character_create_protections WHERE protection_id=?")) { + p.setObject(1, protection); + try (var rs = p.executeQuery()) { + assertThat(rs.next()).isTrue(); + fence = rs.getLong(1); + acquired = rs.getTimestamp(2).toInstant(); + } + } + var original = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace("proof") + .setOperationId(operation.toString()) + .setCreateCharacterRequestId(request.toString()) + .setConnectScopeId("scope") + .setAuthenticatedAccountId(account.toString()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(action)) + .setMutationDigest(digest) + .setOriginalSourceReadback(ByteString.copyFrom(source)) + .build(); + var proof = + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(original) + .setAccountProtectionId(protection.toString()) + .setAccountProtectionFence(fence) + .setAcquiredAt(acquired.toString()) + .setOriginalMembershipSnapshot(ByteString.copyFrom(member)) + .setOriginalEntitlementSnapshot(ByteString.copyFrom(entitlement)) + .build(); + return new Fixture( + account, tenant, operation, protection, fence, member, entitlement, original, proof); + } + + private EntityCharacterCreateTerminal terminal(Fixture f) { + var gs = + CharacterCreateTargetProtection.newBuilder() + .setAccountProtection(f.proof()) + .setGameSessionProtectionId(UUID.randomUUID().toString()) + .setGameSessionProtectionFence(1) + .setAcquiredAt(Instant.now().toString()) + .setOriginalTargetEvidence(ByteString.copyFromUtf8("controlled")) + .build(); + var world = + WorldCharacterCreateLifecycleProtection.newBuilder() + .setAccountProtection(f.proof()) + .setWorldProtectionId(UUID.randomUUID().toString()) + .setWorldProtectionFence(1) + .setAcquiredAt(Instant.now().toString()) + .setOriginalLifecycleEvidence(ByteString.copyFromUtf8("controlled")) + .build(); + var selector = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace("proof") + .setOperationId(f.operation().toString()) + .setMutationDigest(f.original().getMutationDigest()); + var request = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(selector) + .setAccountProtection( + CharacterCreateProtectionReference.newBuilder() + .setProtectionId(f.protection().toString()) + .setProtectionFence(f.fence())) + .setGameSessionProtection( + CharacterCreateProtectionReference.newBuilder() + .setProtectionId(gs.getGameSessionProtectionId()) + .setProtectionFence(1)) + .setWorldProtection( + CharacterCreateProtectionReference.newBuilder() + .setProtectionId(world.getWorldProtectionId()) + .setProtectionFence(1)); + return EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(request) + .setAccountOriginal(f.original()) + .setOriginalAccountProtection(f.proof().toByteString()) + .setOriginalGameSessionProtection(gs.toByteString()) + .setOriginalWorldProtection(world.toByteString()) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(UUID.randomUUID().toString()) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1) + .setCompletedAt(Instant.now().toString()) + .setEntitySourceReceiptDigest("sha256:" + "b".repeat(64)) + .build(); + } + + private void settle(Connection c, Fixture f, EntityCharacterCreateTerminal t, byte[] bytes) + throws SQLException { + execute( + c, + "INSERT INTO account_character_create_settlements(protection_id,protection_fence,operation_id,original_membership_snapshot,original_entitlement_snapshot,original_action,original_source_readback,entity_terminal_id,entity_terminal_fence,outcome,terminal_bytes,terminal_digest) VALUES (?,?,?,?,?,?,?,?,?, 'COMMITTED',?, 'sha256:' || encode(sha256(?),'hex'))", + f.protection(), + f.fence(), + f.operation(), + f.membership(), + f.entitlement(), + f.original().getOriginalAction().toByteArray(), + f.original().getOriginalSourceReadback().toByteArray(), + UUID.fromString(t.getTerminalId()), + t.getTerminalFence(), + bytes, + bytes); + } + + private void sourceWriteBoundary(Connection c, Fixture f) throws SQLException { + execute( + c, + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", + "ACCOUNT:" + f.account()); + } + + @Test + void unrelatedPendingCreationsCoexistButEachActualSourceWriterRemainsBlocked() throws Exception { + try (var c = connection()) { + var a = fixture(c); + var b = fixture(c); + assertThat(a.protection()).isNotEqualTo(b.protection()); + assertThatThrownBy(() -> sourceWriteBoundary(c, a)) + .isInstanceOf(SQLException.class) + .extracting(x -> ((SQLException) x).getSQLState()) + .isEqualTo("55P03"); + assertThatThrownBy(() -> sourceWriteBoundary(c, b)) + .isInstanceOf(SQLException.class) + .extracting(x -> ((SQLException) x).getSQLState()) + .isEqualTo("55P03"); + } + } + + @Test + void malformedOrMismatchedTerminalNeverReleasesSourcesAndExactTerminalDoes() throws Exception { + try (var c = connection()) { + var f = fixture(c); + var t = terminal(f); + assertThatThrownBy(() -> settle(c, f, t, new byte[] {1})).isInstanceOf(SQLException.class); + assertThatThrownBy(() -> sourceWriteBoundary(c, f)).isInstanceOf(SQLException.class); + var wrong = t.toBuilder().setTerminalId(UUID.randomUUID().toString()).build(); + assertThatThrownBy(() -> settle(c, f, t, wrong.toByteArray())) + .isInstanceOf(SQLException.class); + assertThatThrownBy(() -> sourceWriteBoundary(c, f)).isInstanceOf(SQLException.class); + settle(c, f, t, t.toByteArray()); + sourceWriteBoundary(c, f); + assertThatThrownBy( + () -> + execute( + c, + "DELETE FROM account_character_create_settlements WHERE protection_id=?", + f.protection())) + .isInstanceOf(SQLException.class); + } + } + + @Test + void actualRepositoryAcquiresTwoUnrelatedPendingProtectionsThroughSharedIssuerLock() + throws Exception { + var source = + new org.springframework.jdbc.datasource.DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var proxy = new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy(source); + var dsl = org.jooq.impl.DSL.using(proxy, org.jooq.SQLDialect.POSTGRES); + var tx = + new org.springframework.transaction.support.TransactionTemplate( + new org.springframework.jdbc.datasource.DataSourceTransactionManager(source)); + tx.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + var members = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountCanonicalRuntimeMembershipSnapshotRepository.class); + var demos = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository + .class); + var repository = + new net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateRepository( + dsl, members, demos); + var first = + net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateTestActions + .intent("proof", UUID.randomUUID(), UUID.randomUUID(), Instant.now().plusSeconds(300)); + var second = + net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateTestActions + .intent("proof", UUID.randomUUID(), UUID.randomUUID(), Instant.now().plusSeconds(300)); + for (var intent : List.of(first, second)) { + var member = membership(intent.accountId(), intent.tenantId()); + assertThat( + net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.validate(member)) + .isPresent(); + org.mockito.Mockito.when(members.readCurrent(intent.accountId(), intent.tenantId())) + .thenReturn(member); + var demo = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot.class); + var tenant = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence.class); + org.mockito.Mockito.when(tenant.targetNamespace()).thenReturn("proof"); + org.mockito.Mockito.when(demo.canonicalTenantId()).thenReturn(intent.tenantId()); + org.mockito.Mockito.when(demo.sourceEvidence()).thenReturn(tenant); + org.mockito.Mockito.when(demo.gameplayAvailable()).thenReturn(true); + org.mockito.Mockito.when(demo.allowNewGameplayBindings()).thenReturn(true); + org.mockito.Mockito.when(demo.status()).thenReturn("ACTIVE"); + org.mockito.Mockito.when(demos.readCurrent(intent.tenantId())).thenReturn(demo); + tx.executeWithoutResult(status -> repository.retain(intent)); + } + var a = java.util.Objects.requireNonNull(tx.execute(status -> repository.acquire(first))); + var b = java.util.Objects.requireNonNull(tx.execute(status -> repository.acquire(second))); + assertThat(a.protectionId()).isNotEqualTo(b.protectionId()); + assertThat( + java.util.Objects.requireNonNull(tx.execute(status -> repository.acquire(first))) + .sameBinding(a)) + .isTrue(); + org.mockito.Mockito.verify(members).readCurrent(first.accountId(), first.tenantId()); + org.mockito.Mockito.verify(members).readCurrent(second.accountId(), second.tenantId()); + assertThatThrownBy( + () -> + tx.executeWithoutResult( + status -> + dsl.fetch( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", + "ACCOUNT:" + first.accountId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + private static net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Snapshot + membership(UUID account, UUID tenant) { + String a = account.toString(), t = tenant.toString(); + String prefix = + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .EVENT_STREAM_PREFIX; + String stream = prefix + "membership/" + a + "/" + t; + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of(t, "1")); + tuple.put("membershipAuthorityGeneration", Map.of(t, "1")); + tuple.put("privateRealmGrantVersions", List.of()); + Map event = new LinkedHashMap<>(); + event.put( + "schemaVersion", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .SCHEMA_VERSION); + event.put( + "eventType", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", "membership-event-1"); + event.put("requestId", "membership-request-1"); + event.put("outboxStreamKey", stream); + event.put("outboxSequence", "1"); + event.put("sourceScope", "membership/" + a + "/" + t); + event.put("accountId", a); + event.put("tenantId", t); + event.put("membershipExists", true); + event.put("membershipLifecycleState", "ACTIVE"); + event.put("membershipVersion", Map.of(t, "1")); + event.put("membershipAuthorityGeneration", "1"); + event.put("authorityTuple", tuple); + event.put("issuanceFence", "1"); + event.put("roles", List.of("player")); + event.put("gameplayAdmissionAllowed", true); + event.put("callerBoundAuthorityInvalidated", false); + var sealed = + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.seal(event); + return new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + "firemud-account-service", + a, + t, + true, + "ACTIVE", + true, + Map.of(t, "1"), + "1", + List.of("player"), + new net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .AuthorityTuple( + "1", + "1", + Map.of(t, "1"), + Map.of(t, "1"), + List.of(), + Optional.empty(), + Optional.empty()), + "1", + List.of( + new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + prefix + "account/" + a, "0"), + new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + prefix + "issuer/firemud-account-service", "0"), + new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(stream, "1"), + new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + prefix + "tenant/" + t, "0")), + List.of( + new net.firedevops.firemud.common.account.authority + .RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + stream, "1", sealed.eventId(), sealed.eventDigest(), sealed.canonicalJson()))); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java new file mode 100644 index 0000000000..403fc11f21 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -0,0 +1,724 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * PostgreSQL workflow proof. Operator publication and authenticated identity rows are explicit + * test-only upstream fixtures; these tests do not prove live legal publication or identity. + */ +class AccountHostedTermsPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "account-hosted-terms-isolated-test"; + + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exception { + Database db = database("84"); + UUID accountId = insertAccount(db); + IndividualCreatorPartySource party = + party(UUID.randomUUID(), accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map accountBefore = + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap(); + Map partyBefore = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceBefore = (byte[]) partyBefore.remove("source_payload"); + + migrate(db, "85"); + + assertThat( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap()) + .isEqualTo(accountBefore); + Map partyAfter = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceAfter = (byte[]) partyAfter.remove("source_payload"); + assertThat(partyAfter).isEqualTo(partyBefore); + assertThat(partySourceAfter).containsExactly(partySourceBefore); + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + + UUID firstRequest = UUID.randomUUID(); + byte[] originalDocument = new byte[] {0, 1, 2, (byte) 0xff, 13, 10}; + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + AccountHostedTermsService.PublicationResult first = service.publish(firstRequest); + assertThat(first.status()).isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(first.candidate().documentBytes()).containsExactly(originalDocument); + assertThat(first.candidate().documentDigest()) + .isEqualTo(HostedTermsEncoding.digest(originalDocument)); + assertThat(service.publish(firstRequest)).isEqualTo(first); // lost-result exact recovery + publications.put( + firstRequest, + publication( + scopeId, + "changed request payload".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + assertThatThrownBy(() -> service.publish(firstRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + first.candidate().effectiveAt())); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isEqualTo(1); + + UUID firstActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction firstAction = + action(firstActionId, accountId, partyId, scopeId, first.candidate(), true); + actions.put(firstActionId, firstAction); + var accepted = service.accept(firstActionId); + assertThat(accepted.evidenceId()).isNotNull(); + assertThat(accepted.termsVersionId()).isEqualTo(first.candidate().versionId()); + assertThat(accepted.acceptedAt()).isNotNull(); // generated by PostgreSQL, not the caller action + assertThat(service.accept(firstActionId)).isEqualTo(accepted); + actions.put( + firstActionId, + new AccountHostedTermsService.AcceptanceAction( + firstAction.actionRequestId(), + true, + firstAction.accountId(), + firstAction.creatorPartyId(), + firstAction.hostedScopeId(), + firstAction.shownVersionId(), + HostedTermsEncoding.digest("changed shown document".getBytes()), + firstAction.shownOperatorLegalIdentity(), + firstAction.shownOperatorIdentityVersion(), + firstAction.authenticatedActionReference(), + firstAction.authenticatedActionVersion(), + firstAction.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(firstActionId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(1); + var current = service.requireCurrentness(scopeId, partyId); + assertThat(current.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(current.materialGeneration()).isEqualTo(1); + + UUID secondRequest = UUID.randomUUID(); + publications.put( + secondRequest, + publication( + scopeId, + "material-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(3))); + AccountHostedTermsService.PublicationResult material = service.publish(secondRequest); + assertThat(material.candidate().sourceVersion()).isEqualTo(2); + assertThat(material.candidate().materialGeneration()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + + UUID secondActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction secondAction = + action(secondActionId, accountId, partyId, scopeId, material.candidate(), true); + actions.put(secondActionId, secondAction); + var reaccepted = service.accept(secondActionId); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); + + UUID thirdRequest = UUID.randomUUID(); + publications.put( + thirdRequest, + publication( + scopeId, + "nonmaterial-v3".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(2))); + AccountHostedTermsService.PublicationResult nonmaterial = service.publish(thirdRequest); + assertThat(nonmaterial.candidate().sourceVersion()).isEqualTo(3); + assertThat(nonmaterial.candidate().materialGeneration()).isEqualTo(2); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); // prior exact acceptance remains in active ancestry + + UUID operatorChangeRequest = UUID.randomUUID(); + publications.put( + operatorChangeRequest, + publication( + scopeId, + "operator-change-v4".getBytes(), + "Replacement Test Operator", + 2, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(1))); + AccountHostedTermsService.PublicationResult operatorChange = + service.publish(operatorChangeRequest); + assertThat(operatorChange.candidate().sourceVersion()).isEqualTo(4); + assertThat(operatorChange.candidate().materialGeneration()).isEqualTo(3); + assertThat(operatorChange.candidate().operatorLegalIdentity()) + .isEqualTo("Replacement Test Operator"); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + } + + @Test + void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity() + throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID publicationId = UUID.randomUUID(); + publications.put( + publicationId, + publication( + scopeId, + "test-terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion terms = service.publish(publicationId).candidate(); + + UUID negativeId = UUID.randomUUID(); + actions.put(negativeId, action(negativeId, accountId, partyId, scopeId, terms, false)); + assertThatThrownBy(() -> service.accept(negativeId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + + UUID wrongAccountId = UUID.randomUUID(); + UUID wrongSignerId = UUID.randomUUID(); + actions.put( + wrongSignerId, action(wrongSignerId, wrongAccountId, partyId, scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongSignerId)) + .isInstanceOf(IllegalStateException.class); + + UUID wrongPartyId = UUID.randomUUID(); + actions.put( + wrongPartyId, action(wrongPartyId, accountId, UUID.randomUUID(), scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongPartyId)) + .isInstanceOf(IllegalStateException.class); + + UUID mismatchId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction correct = + action(mismatchId, accountId, partyId, scopeId, terms, true); + actions.put( + mismatchId, + new AccountHostedTermsService.AcceptanceAction( + correct.actionRequestId(), + true, + correct.accountId(), + correct.creatorPartyId(), + correct.hostedScopeId(), + correct.shownVersionId(), + HostedTermsEncoding.digest("different document".getBytes()), + correct.shownOperatorLegalIdentity(), + correct.shownOperatorIdentityVersion(), + correct.authenticatedActionReference(), + correct.authenticatedActionVersion(), + correct.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(mismatchId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID initialRequest = UUID.randomUUID(); + publications.put( + initialRequest, + publication( + scopeId, + "test-terms-v1".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion initial = service.publish(initialRequest).candidate(); + UUID actionId = UUID.randomUUID(); + actions.put(actionId, action(actionId, accountId, partyId, scopeId, initial, true)); + var accepted = service.accept(actionId); + + UUID futureRequest = UUID.randomUUID(); + Instant deadline = databaseNow(db).plusSeconds(5).truncatedTo(ChronoUnit.MICROS); + publications.put( + futureRequest, + publication( + scopeId, + "test-terms-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + AccountHostedTermsService.PublicationResult scheduled = service.publish(futureRequest); + assertThat(scheduled.status()).isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + UUID advanceAcceptanceId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction advanceAcceptance = + action(advanceAcceptanceId, accountId, partyId, scopeId, scheduled.candidate(), true); + actions.put(advanceAcceptanceId, advanceAcceptance); + var acceptedInAdvance = service.accept(advanceAcceptanceId); + assertThat(acceptedInAdvance.termsVersionId()).isEqualTo(scheduled.candidate().versionId()); + var beforeDeadline = service.requireCurrentness(scopeId, partyId); + assertThat(beforeDeadline.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(beforeDeadline.validUntil()).isEqualTo(deadline); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(2); + assertThat(service.resumePublication(futureRequest).status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + + assertThat( + currentnessBlockedAcrossEffectiveDateIsDenied(db, service, scopeId, partyId, deadline)) + .isTrue(); + } + + private static boolean currentnessBlockedAcrossEffectiveDateIsDenied( + Database db, AccountHostedTermsService service, UUID scopeId, UUID partyId, Instant deadline) + throws Exception { + CountDownLatch scopeLocked = new CountDownLatch(1); + CountDownLatch releaseScope = new CountDownLatch(1); + AtomicInteger blockerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + db.transactions() + .executeWithoutResult( + ignored -> { + blockerPid.set( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class)); + db.dsl() + .fetchOne( + "SELECT hosted_scope_id FROM account_hosted_terms_scopes " + + "WHERE hosted_scope_id = ? FOR UPDATE", + scopeId); + scopeLocked.countDown(); + awaitLatch(releaseScope, "Hosted scope blocker was not released"); + })); + try { + assertThat(scopeLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future waiter = + executor.submit(() -> service.requireCurrentness(scopeId, partyId)); + Record waiting = awaitHostedScopeLockWait(db, blockerPid.get(), deadline); + assertThat(waiting.get("query_start", OffsetDateTime.class).toInstant()) + .as("currentness lock wait must begin before the disclosed effective date") + .isBefore(deadline); + + awaitDatabaseTime(db, deadline); + releaseScope.countDown(); + try { + waiter.get(5, TimeUnit.SECONDS); + throw new AssertionError("Currentness returned after the disclosed terms deadline"); + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + blocker.get(5, TimeUnit.SECONDS); + return true; + } finally { + releaseScope.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Record awaitHostedScopeLockWait(Database db, int blockerPid, Instant deadline) + throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < timeoutAt) { + Record waiting = + db.dsl() + .fetchOne( + "SELECT waiting.pid, waiting.query_start, waiting.xact_start " + + "FROM pg_stat_activity waiting " + + "WHERE waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%account_hosted_terms_scopes%' " + + "AND waiting.query ILIKE '%for update%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)) LIMIT 1", + blockerPid); + if (waiting != null) { + assertThat(waiting.get("xact_start", OffsetDateTime.class).toInstant()) + .as("currentness transaction must also have begun before the deadline") + .isBefore(deadline); + return waiting; + } + Thread.sleep(10L); + } + throw new AssertionError("Currentness did not reach the hosted-scope lock wait"); + } + + private static void awaitDatabaseTime(Database db, Instant deadline) throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < timeoutAt) { + Instant databaseTime = databaseNow(db); + if (!databaseTime.isBefore(deadline)) { + return; + } + Thread.sleep(10L); + } + throw new AssertionError("PostgreSQL clock did not reach the disclosed effective date"); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant(); + } + + private static void awaitLatch(CountDownLatch latch, String message) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException(message); + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(message, failure); + } + } + + @Test + void ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent() throws Exception { + Database db = database("latest"); + HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); + UUID scopeId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + byte[] request = "test-only publication".getBytes(); + HostedTermsCatalogVersion candidate = + catalogCandidate( + scopeId, + "test-only terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1), + UUID.randomUUID()); + + assertThatThrownBy( + () -> + tx( + db, + () -> + db.transactions() + .executeWithoutResult( + status -> { + repository.ensureScope(scopeId); + repository.claimPublication(requestId, scopeId, request); + repository.lockScope(scopeId); + repository.insertCandidate(candidate); + throw new IllegalStateException("test-only rollback"); + }))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("rollback"); + + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + } + + private static AccountHostedTermsService service( + Database db, + Map publications, + Map actions) { + IndividualCreatorPartyRepository individualParties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + individualParties, + new DraftAuthorizationFenceRepository(db.dsl()), + requestId -> + Objects.requireNonNull(publications.get(requestId), "test-only operator fixture"), + actionId -> + Objects.requireNonNull(actions.get(actionId), "test-only identity/action fixture")); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + operator, + operatorVersion, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL + ? null + : "test-only-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static HostedTermsCatalogVersion catalogCandidate( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt, + UUID versionId) { + return new HostedTermsCatalogVersion( + versionId, + scope, + null, + operator, + operatorVersion, + document, + HostedTermsEncoding.digest(document), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID actionId, + UUID accountId, + UUID partyId, + UUID scopeId, + HostedTermsCatalogVersion terms, + boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + actionId, + affirmative, + accountId, + partyId, + scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-only-authenticated-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party( + UUID partyId, UUID accountId, long identityVersion, String evidenceRef) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + identityVersion, + "test-only-verification-policy", + 1L, + evidenceRef, + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + private static UUID insertAccount(Database db) { + UUID accountId = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + accountId, + "hosted-" + accountId.toString().substring(0, 8), + accountId + "@example.test"); + return accountId; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull( + Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class)); + } + + private static Database database(String target) throws Exception { + String schema = "hosted_terms_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + migrate(db, target); + return db; + } + + private static void migrate(Database db, String target) { + Flyway.configure() + .dataSource(db.source()) + .schemas(db.schema()) + .defaultSchema(db.schema()) + .placeholders(Map.of("serviceSchema", db.schema())) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(status -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java new file mode 100644 index 0000000000..4aac4bba0f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -0,0 +1,648 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** PostgreSQL proof with explicitly test-only environment publisher and identity authorities. */ +class HostedTermsEnvironmentBindingPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "hosted-terms-binding-isolated-test"; + + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions() + throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("production")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + assertThat(count(db, "account_hosted_terms_environment_binding_heads")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_binding_publications")).isZero(); + + UUID firstTermsRequest = UUID.randomUUID(); + catalogPublications.put( + firstTermsRequest, + publication( + scopeId, + "test-only terms version one".getBytes(), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion firstCatalog = service.publish(firstTermsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, firstCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID firstBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstBindingEvidence = + bindingEvidence("production", firstCatalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + var firstBinding = service.publishEnvironmentBinding(firstBindingRequest); + assertThat(firstBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(firstBinding.candidate().sourceVersion()).isOne(); + assertThat(firstBinding.exactReceipt()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + assertThat(service.publishEnvironmentBinding(firstBindingRequest)).isEqualTo(firstBinding); + assertThat( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_binding_id FROM account_hosted_terms_environment_binding_heads " + + "WHERE environment_boundary = 'production'")) + .get("current_binding_id", UUID.class)) + .isEqualTo(firstBinding.candidate().bindingId()); + + HostedTermsEnvironmentBinding.PublicationEvidence changedRetry = + bindingEvidence("production", firstCatalog, null, null, "changed-test-publisher"); + bindingPublications.put(firstBindingRequest, changedRetry); + assertThatThrownBy(() -> service.publishEnvironmentBinding(firstBindingRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + + var current = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(current.environment().environmentBoundary()).isEqualTo("production"); + assertThat(current.binding()).isEqualTo(firstBinding.candidate()); + assertThat(current.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(current.sourceEvidence()).hasSize(3); + assertThat(current.sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()) + .containsExactly( + HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo(scopeId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains("account-hosted-terms-currentness-source/v2") + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.acceptance(acceptance))); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.CREATOR_PARTY); + assertThat(source.scopeId()).isEqualTo(partyId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(CreatorPartyEncoding.party(party)); + }); + + UUID nextTermsRequest = UUID.randomUUID(); + catalogPublications.put( + nextTermsRequest, + publication( + scopeId, + "test-only nonmaterial terms version two".getBytes(), + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(5))); + HostedTermsCatalogVersion secondCatalog = service.publish(nextTermsRequest).candidate(); + assertThat(secondCatalog.sourceVersion()).isEqualTo(2); + assertThat(secondCatalog.materialGeneration()).isEqualTo(1); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed catalog authority"); + + UUID secondBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondBindingEvidence = + bindingEvidence( + "production", + secondCatalog, + firstBinding.candidate().bindingId(), + firstBinding.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondBindingRequest, secondBindingEvidence); + var secondBinding = service.publishEnvironmentBinding(secondBindingRequest); + assertThat(secondBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(secondBinding.candidate().sourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().catalogSourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().predecessorBindingId()) + .isEqualTo(firstBinding.candidate().bindingId()); + assertThat(service.publishEnvironmentBinding(secondBindingRequest)).isEqualTo(secondBinding); + HostedTermsEnvironmentBindingRepository bindingRepository = + new HostedTermsEnvironmentBindingRepository(db.dsl()); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isEqualTo(2); + HostedTermsEnvironmentBinding retainedBinding = + db.transactions() + .execute( + ignored -> + bindingRepository.readBinding( + "production", firstBinding.candidate().bindingId())); + assertThat(retainedBinding).isEqualTo(firstBinding.candidate()); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding()) + .isEqualTo(secondBinding.candidate()); + + boundary.set(currentBoundary("unbound-test-environment")); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("head is unavailable"); + } + + @Test + void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("settlement-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID termsRequest = UUID.randomUUID(); + catalogPublications.put( + termsRequest, + publication( + scopeId, + "test-only terms for settlement proof".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion catalog = service.publish(termsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, catalog)); + service.accept(acceptanceRequest); + + UUID firstRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstEvidence = + bindingEvidence( + "settlement-test-environment", catalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstRequest, firstEvidence); + var first = service.publishEnvironmentBinding(firstRequest); + var captured = service.requireCurrentnessForCurrentEnvironment(partyId); + + // This is an explicit isolated-test fence fixture, not proof of the missing authenticated + // Draft producer. The Account binding update still uses the real PostgreSQL owner/fence repos. + DraftAuthorizationFenceBinding pendingDraft = + testDraftBinding(accountId, captured.sourceEvidence()); + var draftFences = new DraftAuthorizationFenceRepository(db.dsl()); + tx(db, () -> draftFences.reserve(pendingDraft)); + + UUID secondRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondEvidence = + bindingEvidence( + "settlement-test-environment", + catalog, + first.candidate().bindingId(), + first.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondRequest, secondEvidence); + var pendingBinding = service.publishEnvironmentBinding(secondRequest); + assertThat(pendingBinding.status()) + .isEqualTo( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + assertThat(pendingBinding.candidate().sourceVersion()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is unresolved"); + String pendingDraftOrdering = + db.transactions().execute(ignored -> draftFences.read(pendingDraft).ordering().name()); + assertThat(pendingDraftOrdering).isEqualTo("REVOKE_ORDER"); + DraftAuthorizationFenceRepository.Settlement pendingSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(pendingSettlement).isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + + // Explicitly simulated terminal abort evidence satisfies both original required owners. + tx( + db, + () -> { + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.WORLD, new byte[] {1})); + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.GAME_DESIGN, new byte[] {2})); + }); + assertThat(service.resumeEnvironmentBinding(secondRequest).status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + DraftAuthorizationFenceRepository.Settlement completedSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(completedSettlement) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.FAILED_NONPUBLICATION); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding().sourceVersion()) + .isEqualTo(2); + } + + @Test + void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("deadline-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID initialRequest = UUID.randomUUID(); + catalogPublications.put( + initialRequest, + publication( + scopeId, + "test-only current terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion currentCatalog = service.publish(initialRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, currentCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID bindingRequest = UUID.randomUUID(); + bindingPublications.put( + bindingRequest, + bindingEvidence( + "deadline-test-environment", currentCatalog, null, null, "test-only-publisher")); + service.publishEnvironmentBinding(bindingRequest); + + Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); + UUID scheduledRequest = UUID.randomUUID(); + catalogPublications.put( + scheduledRequest, + publication( + scopeId, + "test-only scheduled terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + HostedTermsCatalogVersion scheduled = service.publish(scheduledRequest).candidate(); + + var currentness = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(currentness.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(currentness.terms().validUntil()).isEqualTo(scheduled.effectiveAt()); + assertThat(currentness.terms().disclosedDeadline()).isEqualTo(scheduled); + byte[] exactTermsSource = + HostedTermsEncoding.currentnessSource(currentCatalog, acceptance, scheduled); + assertThat(currentness.terms().exactCurrentnessSource()).containsExactly(exactTermsSource); + assertThat(currentness.sourceEvidence()) + .filteredOn(source -> source.scopeId().equals(scopeId.toString())) + .singleElement() + .satisfies( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(exactTermsSource); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.catalog(scheduled))); + }); + } + + private static DraftAuthorizationFenceBinding testDraftBinding( + UUID actorAccountId, List sources) { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "opaque/base:1", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + requestId, + commitId, + UUID.randomUUID(), + actorAccountId, + tenantId, + versionId, + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + } + + private static OwnerReadback testReadback( + DraftAuthorizationFenceBinding binding, Owner owner, byte[] exactTestResult) { + return new OwnerReadback( + owner, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + exactTestResult); + } + + private static AccountHostedTermsService service( + Database db, + Map catalogPublications, + Map actions, + Map bindingPublications, + AtomicReference boundary) { + IndividualCreatorPartyRepository parties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + parties, + new DraftAuthorizationFenceRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + catalogPublications.get(request), "test-only catalog fixture"); + }, + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + actions.get(request), "test-only affirmative action fixture"); + }, + new HostedTermsEnvironmentBindingRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + bindingPublications.get(request), "test-only owner fixture"); + }, + () -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull(boundary.get()); + }); + } + + private static void assertOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Owner authority must be resolved outside Account locks"); + } + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary( + String boundary) { + byte[] ownerEvidence = ("test-only-boundary:" + boundary).getBytes(); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + boundary, + "test-only-environment-owner/" + boundary, + "test-only-current-boundary-observation/" + boundary, + ownerEvidence, + HostedTermsEncoding.digest(ownerEvidence)); + } + + private static HostedTermsEnvironmentBinding.PublicationEvidence bindingEvidence( + String boundary, + HostedTermsCatalogVersion catalog, + UUID predecessorBindingId, + Long predecessorSourceVersion, + String publisher) { + return new HostedTermsEnvironmentBinding.PublicationEvidence( + boundary, + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + publisher, + "test-only-publication-event/" + UUID.randomUUID(), + predecessorBindingId, + predecessorSourceVersion); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator Legal Name", + 1, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-legal-publication", + 1, + "test-only-notice", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID requestId, UUID accountId, UUID partyId, HostedTermsCatalogVersion catalog) { + return new AccountHostedTermsService.AcceptanceAction( + requestId, + true, + accountId, + partyId, + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-authenticated-individual-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-only-identity-policy", + 1L, + "test-only-verified-identity-evidence", + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] payload = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + payload, + CreatorPartyEncoding.digest(payload)); + } + + private static UUID insertAccount(Database db) { + UUID id = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + id, + "hosted-binding-" + id.toString().substring(0, 8), + id + "@example.test"); + return id; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant() + .truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class); + } + + private static Database database(String target) throws Exception { + String schema = "terms_binding_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + return db; + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(ignored -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index a052837a81..0c3146d0e4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -27,6 +27,9 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountEvent; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -518,6 +521,16 @@ void freshAccountWithNullGlobalRoleKeepsGenericEventOutOfCurrentness() { @Test void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOriginalHold() { + assertIssuerSourceRemainsHeld(null); + } + + @Test + void bothMixedOwnerVectorsKeepActualIssuerMutationAndRetryFenced() { + assertIssuerSourceRemainsHeld(Outcome.COMMITTED); + assertIssuerSourceRemainsHeld(Outcome.DEFINITIVELY_ABORTED); + } + + private void assertIssuerSourceRemainsHeld(Outcome worldOutcome) { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -591,6 +604,28 @@ void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOri fences.reserve(holder); fences.claimCommitOrder(holder); }); + if (worldOutcome != null) { + // Stipulated owner terminal evidence only, never an authenticated publisher. + for (Owner owner : List.of(Owner.WORLD, Owner.GAME_DESIGN)) { + Outcome outcome = + owner == Owner.WORLD + ? worldOutcome + : worldOutcome == Outcome.COMMITTED + ? Outcome.DEFINITIVELY_ABORTED + : Outcome.COMMITTED; + var readback = + new OwnerReadback( + owner, + outcome, + holder.operationId(), + holder.commitId(), + holder.fenceId(), + holder.inputDigest(), + holder.canonicalBytes(), + ("retained-" + owner + "-" + outcome).getBytes(StandardCharsets.UTF_8)); + transaction.executeWithoutResult(status -> fences.recordOwnerReadback(holder, readback)); + } + } Map>> retained = new java.util.LinkedHashMap<>(); for (String table : List.of( @@ -612,21 +647,23 @@ void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOri } var observed = transaction.execute(status -> sources.initializeIssuerIfAbsent(ISSUER)); assertThat(observed).isEqualTo(original); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - sources.appendIssuerAuthorityChange( - ISSUER, - "SIGNER_COMPROMISE", - "blocked-held-issuer-" + UUID.randomUUID()))) - .rootCause() - .isInstanceOf(org.postgresql.util.PSQLException.class) - .hasMessageContaining("Required creator source is held until every original owner settles") - .satisfies( - failure -> - assertThat(((org.postgresql.util.PSQLException) failure).getSQLState()) - .isEqualTo("55P03")); + String blockedRequestId = "blocked-held-issuer-" + UUID.randomUUID(); + for (int attempt = 0; attempt < 2; attempt++) { + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> + sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", blockedRequestId))) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining( + "Required creator source is held until every original owner settles") + .satisfies( + failure -> + assertThat(((org.postgresql.util.PSQLException) failure).getSQLState()) + .isEqualTo("55P03")); + } assertThat( Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 7359405b7e..8f93ec0580 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import java.time.Duration; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -11,6 +12,11 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; @@ -558,7 +564,9 @@ void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { assertThat(scopeRowCount(setupDsl, v2Scope.connectScopeId())).isEqualTo(1); } - @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.ParameterizedTest( + name = + "definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite[{index}] bound={0}") @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite( boolean bound) { @@ -879,7 +887,8 @@ void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerm f.assertNoSuccessEffects(); } - @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.ParameterizedTest( + name = "journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction[{index}] bound={0}") @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean bound) { JournalFixture f = journalFixture(); @@ -916,6 +925,106 @@ void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean boun f.assertNoSuccessEffects(); } + @Test + void competingExactIntentAndPolicyWritesRetainOnePendingRequestWithoutSuccessEffects() + throws Exception { + JournalFixture fixture = journalFixture(); + String requestId = fixture.requestId() + "-raced"; + var operations = fixture.operations(); + var scope = fixture.scope(); + String caller = fixture.caller(); + + assertThat( + raceExactOwnerWrite( + fixture, () -> operations.insertCanonicalIntent(requestId, scope, caller))) + .containsExactly(true, false); + + List competingPolicy = + raceExactOwnerWrite( + fixture, + () -> operations.bindCanonicalPolicyEvidence(requestId, scope, caller, true, 17L)); + CanonicalJoinOperationEvidence evidence = competingPolicy.getFirst(); + assertThat(competingPolicy).containsExactly(evidence, evidence); + assertThat(evidence.status()).isEqualTo("PENDING"); + assertThat(evidence.intentDigest()) + .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, caller)); + assertThat(evidence.requestDigest()) + .isEqualTo( + AccountJoinDigest.requestV2( + scope, caller, AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, true, 17L)); + assertThat(evidence.membershipId()).isNull(); + assertThat(evidence.terminalProof()).isNull(); + + String physicalRow = + "SELECT row_to_json(j)::text, xmin::text FROM account_join_operations j WHERE request_id = ?"; + var committed = retainedPhysicalRow(fixture.dsl(), physicalRow, requestId); + CanonicalJoinOperationEvidence replay = + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence(requestId, scope, caller, true, 17L)); + assertThat(replay).isEqualTo(evidence); + assertThat(retainedPhysicalRow(fixture.dsl(), physicalRow, requestId)).isEqualTo(committed); + fixture.assertNoSuccessEffects(); + } + + private static List raceExactOwnerWrite(JournalFixture fixture, Supplier write) + throws Exception { + try (var executor = Executors.newSingleThreadExecutor()) { + var waitingPid = new CompletableFuture(); + var waitingResult = new CompletableFuture(); + T winner = + fixture + .transaction() + .execute( + status -> { + int blockingPid = ownerBackendPid(fixture.owner()); + T result = Objects.requireNonNull(write.get()); + executor.submit( + () -> { + try { + waitingResult.complete( + fixture + .transaction() + .execute( + waitingStatus -> { + waitingPid.complete(ownerBackendPid(fixture.owner())); + return write.get(); + })); + } catch (RuntimeException failure) { + waitingPid.completeExceptionally(failure); + waitingResult.completeExceptionally(failure); + } + }); + assertThat(awaitOwnerBlock(fixture.dsl(), blockingPid, waitingPid)).isTrue(); + return result; + }); + return List.of(Objects.requireNonNull(winner), waitingResult.get(15, TimeUnit.SECONDS)); + } + } + + private static int ownerBackendPid(DSLContext owner) { + return owner.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + } + + private static boolean awaitOwnerBlock( + DSLContext setup, int blockingPid, CompletableFuture waitingPid) { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (System.nanoTime() < deadline) { + int pid = waitingPid.getNow(0); + if (pid > 0 + && Boolean.TRUE.equals( + setup + .fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", blockingPid, pid) + .get(0, Boolean.class))) { + return true; + } + LockSupport.parkNanos(Duration.ofMillis(25).toNanos()); + } + return false; + } + private JournalFixture journalFixture() { String schema = createSchema("canonical_join_scope_"); var source = postgres.dataSource(schema); @@ -958,12 +1067,13 @@ private JournalFixture journalFixture() { operations.insertCanonicalIntent(requestId, scope, caller); }); return new JournalFixture( - setup, transaction, operations, scopes, scope, privateAccountId, requestId, caller); + setup, owner, transaction, operations, scopes, scope, privateAccountId, requestId, caller); } /** Physical journal storage proof only; supplied caller/scope selectors do not authenticate. */ private record JournalFixture( DSLContext dsl, + DSLContext owner, TransactionTemplate transaction, AccountJoinOperationRepository operations, AccountConnectScopeRepository scopes, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java index 9d0cb16e1e..dbcd341cab 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java @@ -166,6 +166,137 @@ void missingCommittedRoleSnapshotFailsClosed() { .hasMessageContaining("Committed current membership role snapshot is absent"); } + @Test + void capturesTwoActualOwnersInEitherDirectionWithoutChangingStoredRows() { + Fixture f = newFixture(); + f.commitFirstJoin(); + Account target = f.commitSecondMember(); + List before = f.schemaImage(); + var forward = + f.inTransaction( + () -> + f.capture.capture( + f.account.getAccountUuid(), target.getAccountUuid(), f.tenantUuid)); + var reverse = + f.inTransaction( + () -> + f.capture.capture( + target.getAccountUuid(), f.account.getAccountUuid(), f.tenantUuid)); + assertThat( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode(forward)) + .containsExactly( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode( + new net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.Pair( + reverse.target(), reverse.actor()))); + byte[] bytes = + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode(forward); + assertThat( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.decode( + bytes))) + .containsExactly(bytes); + assertThat(f.schemaImage()).isEqualTo(before); + assertThatThrownBy( + () -> + f.capture.capture( + f.account.getAccountUuid(), target.getAccountUuid(), f.tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owner transaction"); + } + + @Test + void reverseCaptureContendersBothWaitOnFirstCanonicalOwnerBeforeAnySecondOwnerLock() + throws Exception { + Fixture f = newFixture(); + f.commitFirstJoin(); + Account target = f.commitSecondMember(); + UUID actor = f.account.getAccountUuid(), other = target.getAccountUuid(); + var ordered = + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureBounds.orderedAccounts( + actor, other); + var executor = java.util.concurrent.Executors.newFixedThreadPool(2); + var firstPid = new java.util.concurrent.atomic.AtomicInteger(); + var secondPid = new java.util.concurrent.atomic.AtomicInteger(); + var jobs = + new java.util.ArrayList< + java.util.concurrent.Future< + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.Pair>>(); + List before = f.schemaImage(); + try { + f.inTransaction( + () -> { + f.dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid=? FOR UPDATE", + ordered.getFirst()); + jobs.add( + executor.submit( + () -> + f.inTransaction( + () -> { + f.dsl.execute("SET LOCAL lock_timeout='8s'"); + firstPid.set( + Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class)); + return f.capture.capture(actor, other, f.tenantUuid); + }))); + jobs.add( + executor.submit( + () -> + f.inTransaction( + () -> { + f.dsl.execute("SET LOCAL lock_timeout='8s'"); + secondPid.set( + Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class)); + return f.capture.capture(other, actor, f.tenantUuid); + }))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5); + boolean bothBlocked = false; + while (System.nanoTime() < deadline) { + if (firstPid.get() > 0 && secondPid.get() > 0) { + int blocked = + Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT count(*) AS n FROM pg_stat_activity WHERE pid IN (?,?) AND wait_event_type='Lock' AND cardinality(pg_blocking_pids(pid))>0", + firstPid.get(), + secondPid.get())) + .get("n", Integer.class); + if (blocked == 2) { + bothBlocked = true; + break; + } + } + java.util.concurrent.locks.LockSupport.parkNanos( + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10)); + } + assertThat(bothBlocked).isTrue(); + assertThat(firstPid.get()).isNotEqualTo(secondPid.get()); + // A reversed-order implementation would already own the second row and NOWAIT would + // fail. + assertThat( + f.dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid=? FOR UPDATE NOWAIT", + ordered.getLast())) + .isNotNull(); + return null; + }); + var forward = jobs.get(0).get(10, java.util.concurrent.TimeUnit.SECONDS); + var reverse = jobs.get(1).get(10, java.util.concurrent.TimeUnit.SECONDS); + assertThat( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode(forward)) + .containsExactly( + net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.encode( + new net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.Pair( + reverse.target(), reverse.actor()))); + assertThat(f.schemaImage()).isEqualTo(before); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(12, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + private Fixture newFixture() { return new Fixture(newTestContext()); } @@ -205,6 +336,10 @@ private static final class Fixture { private final AccountJoinOperationRepository operations; private final AccountCanonicalFirstJoinTerminalCoordinator terminalCoordinator; private final AccountCanonicalRuntimeMembershipSnapshotService snapshots; + private final net.firedevops.firemud.accountservice.tenantrole.AccountTransferCaptureRepository + capture; + private final AccountConnectScopeRepository connectScopes; + private DemoTenantEntitlementSnapshot entitlement; private final Account account; private final UUID tenantUuid = UUID.randomUUID(); private final FreshTenantCreationEvidence tenantEvidence; @@ -236,7 +371,7 @@ private Fixture(TestContext context) { org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class); var retainedIdentityResolver = new AccountTenantIdentityResolver(legacyAssociationRepository, TEST_NAMESPACE); - var connectScopes = + this.connectScopes = new AccountConnectScopeRepository(dsl, retainedIdentityResolver, freshTenants); this.operations = new AccountJoinOperationRepository(dsl, connectScopes); var producer = @@ -272,6 +407,9 @@ private Fixture(TestContext context) { pairs, roles, outbox); + this.capture = + new net.firedevops.firemud.accountservice.tenantrole.AccountTransferCaptureRepository( + dsl, snapshotRepository, generations, pairs, roles); this.snapshots = new AccountCanonicalRuntimeMembershipSnapshotService( snapshotRepository, transactionManager); @@ -310,7 +448,7 @@ private void seedOwnerRowsAndOperation(AccountConnectScopeRepository connectScop operations.insertCanonicalIntent(requestId, scope, callerBinding); return null; }); - DemoTenantEntitlementSnapshot entitlement = + this.entitlement = inTransaction( () -> demoEntitlements.provision( @@ -327,6 +465,30 @@ private void seedOwnerRowsAndOperation(AccountConnectScopeRepository connectScop }); } + private Account commitSecondMember() { + Account second = createAccount(); + var secondScope = canonicalScope(second.getAccountUuid(), tenantUuid); + String request = UUID.randomUUID().toString(); + String caller = "second-controlled-caller-" + UUID.randomUUID(); + inTransaction( + () -> { + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + second.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(second.getId(), secondScope, provenance); + operations.insertCanonicalIntent(request, secondScope, caller); + operations.bindCanonicalPolicyEvidence( + request, + secondScope, + caller, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + terminalCoordinator.commitCanonicalFirstJoin(secondScope, request, caller); + return null; + }); + return second; + } + private void enrollAbsenceBaseline() { inTransaction( () -> { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCapturePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCapturePostgresIntegrationTest.java new file mode 100644 index 0000000000..270fe9477d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceCapturePostgresIntegrationTest.java @@ -0,0 +1,345 @@ +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.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceCaptureRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier.Lookup; +import net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; +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 AccountConnectIssuanceFenceCapturePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void firstCaptureAndExactRetryPreserveTheOriginalReceipt() { + DSLContext db = database("1051.1"); + UUID operation = UUID.randomUUID(); + UUID account = createAccount(db).getAccountUuid(); + Lookup identity = insertPending(db, operation, account); + IssuanceFence baseline = new IssuanceFence(account, 1, 1); + + assertThat(read(db, operation, identity)).isEmpty(); + assertThatThrownBy( + () -> + new AccountConnectIssuanceFenceCaptureRepository(db) + .capture(operation, identity, baseline)) + .hasMessageContaining("existing Account transaction"); + assertThatThrownBy(() -> capture(db, operation, identity, new IssuanceFence(account, 1, 2))) + .hasMessageContaining("differs or lacks provenance"); + assertThat(read(db, operation, identity)).isEmpty(); + + var captured = capture(db, operation, identity, baseline); + assertThat(captured.operationId()).isEqualTo(operation); + assertThat(captured.identity()).isEqualTo(identity); + assertThat(captured.fence()).isEqualTo(baseline); + assertThat(captured.digest()).matches("[0-9a-f]{64}"); + String after = receipt(db, operation); + assertThat(capture(db, operation, identity, baseline)).isEqualTo(captured); + assertThat(read(db, operation, identity)).contains(captured); + assertThat(receipt(db, operation)).isEqualTo(after); + assertThat(db.fetchValue("SELECT count(*) FROM connect_token_response_envelope")).isEqualTo(0L); + } + + @Test + void concurrentExactCaptureWaitsForThePendingReceiptAndReadsTheWinner() throws Exception { + DSLContext db = database("1051.1"); + UUID operation = UUID.randomUUID(); + UUID account = createAccount(db).getAccountUuid(); + Lookup identity = insertPending(db, operation, account); + IssuanceFence fence = new IssuanceFence(account, 1, 1); + String schema = db.fetchSingle("SELECT current_schema()").get(0, String.class); + + try (var executor = Executors.newSingleThreadExecutor()) { + CompletableFuture retry = + db.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int blocker = tx.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + new AccountConnectIssuanceFenceCaptureRepository(tx) + .capture(operation, identity, fence); + CompletableFuture pending = + CompletableFuture.supplyAsync( + () -> capture(db, operation, identity, fence), executor); + boolean blocked = false; + for (int i = 0; i < 100 && !blocked; i++) { + blocked = + Boolean.TRUE.equals( + db.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE wait_event_type='Lock' AND application_name=? " + + "AND query LIKE 'SELECT status, issuance_fence_capture_schema%' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + schema, blocker) + .get(0, Boolean.class)); + if (!blocked) Thread.sleep(20); + } + assertThat(blocked).as("exact retry waits for the receipt lock").isTrue(); + return pending; + }); + assertThat(read(db, operation, identity)).contains(retry.get(10, TimeUnit.SECONDS)); + } + } + + @Test + void changedCurrentFenceCannotReplaceTheOriginalAndOnlyExactHistoryReadsBack() { + DSLContext db = database("1051.1"); + Account account = createAccount(db); + UUID operation = UUID.randomUUID(); + Lookup identity = insertPending(db, operation, account.getAccountUuid()); + IssuanceFence baseline = new IssuanceFence(account.getAccountUuid(), 1, 1); + var captured = capture(db, operation, identity, baseline); + + account.setEmailVerified(true); + saveAccount(db, account); + IssuanceFence current = new IssuanceFence(account.getAccountUuid(), 2, 2); + String after = receipt(db, operation); + assertThatThrownBy(() -> capture(db, operation, identity, baseline)) + .hasMessageContaining("differs or lacks provenance"); + assertThatThrownBy(() -> capture(db, operation, identity, current)) + .hasMessageContaining("captured with different evidence"); + + Lookup changedDigest = + new Lookup( + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId(), + identity.digestVersion(), + "sha256:" + "1".repeat(64)); + Lookup changedScope = + ConnectTokenRequestFingerprint.lookup( + identity.accountId(), identity.tenantId(), "other scope", identity.requestId()); + assertThatThrownBy(() -> read(db, operation, changedDigest)) + .hasMessageContaining("identity differs"); + assertThatThrownBy(() -> capture(db, operation, changedScope, current)) + .hasMessageContaining("identity differs"); + assertThatThrownBy(() -> read(db, UUID.randomUUID(), identity)) + .hasMessageContaining("is missing"); + assertThat(read(db, operation, identity)).contains(captured); + assertThat(receipt(db, operation)).isEqualTo(after); + + abort(db, operation); + assertThat(read(db, operation, identity)).contains(captured); + assertThatThrownBy(() -> capture(db, operation, identity, current)) + .hasMessageContaining("requires a pending operation"); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET issuance_fence_capture_digest=? " + + "WHERE operation_id=?", + new byte[32], + operation)) + .hasMessageContaining("capture is immutable"); + } + + @Test + void missingAuthorityCannotPopulateCapture() { + DSLContext db = database("1051.1"); + UUID operation = UUID.randomUUID(); + UUID retainedAccount = + db.fetchSingle( + "INSERT INTO accounts(username,email,password_hash) " + + "VALUES ('retained-account','retained@example.test','fixture') RETURNING account_uuid") + .get(0, UUID.class); + Lookup identity = insertPending(db, operation, retainedAccount); + + assertThatThrownBy( + () -> capture(db, operation, identity, new IssuanceFence(retainedAccount, 1, 1))) + .hasMessageContaining("fence is unavailable"); + assertThat(read(db, operation, identity)).isEmpty(); + } + + @Test + void migrationPreservesUncapturedPendingAndTerminalRowsAndExistingReplayEvidence() { + DSLContext db = database("1051"); + UUID account = createAccount(db).getAccountUuid(); + UUID pending = UUID.randomUUID(); + UUID committed = UUID.randomUUID(); + Lookup pendingIdentity = insertPending(db, pending, account); + Lookup committedIdentity = insertPending(db, committed, account); + db.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute( + "INSERT INTO connect_token_response_envelope VALUES (?, 'fixture-key',1,?,?)", + committed, + new byte[] {1}, + new byte[] {2}); + tx.execute( + "UPDATE connect_token_issuance_operation SET status='COMMITTED',token_jti=?," + + "token_hash=?,replay_admission_fence=77,issuance_evidence=? WHERE operation_id=?", + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + new byte[] {3}, + committed); + }); + var receiptRows = previousReceiptRows(db); + var envelopes = envelopeRows(db); + + String schema = db.fetchSingle("SELECT current_schema()").get(0, String.class); + migration(schema).target("1051.1").load().migrate(); + assertThat(previousReceiptRows(db)).isEqualTo(receiptRows); + assertThat(envelopeRows(db)).isEqualTo(envelopes); + assertThat(read(db, pending, pendingIdentity)).isEmpty(); + assertThat(read(db, committed, committedIdentity)).isEmpty(); + IssuanceFence baseline = new IssuanceFence(account, 1, 1); + assertThatThrownBy(() -> capture(db, committed, committedIdentity, baseline)) + .hasMessageContaining("requires a pending operation"); + + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET " + + "issuance_fence_capture_schema='account-connect-issuance-fence/v1'," + + "issuance_fence_capture_account_uuid=account_uuid,issuance_fence_capture_value=1," + + "issuance_fence_capture_source_version=1,issuance_fence_capture_digest=? " + + "WHERE operation_id=?", + new byte[32], + committed)) + .hasMessageContaining("requires an existing pending operation"); + assertThat(capture(db, pending, pendingIdentity, baseline).fence()).isEqualTo(baseline); + assertThat(read(db, committed, committedIdentity)).isEmpty(); + } + + private static Account createAccount(DSLContext db) { + String name = "capture-" + UUID.randomUUID(); + Account account = new Account(); + account.setUsername(name); + account.setEmail(name + "@example.test"); + account.setPasswordHash("fixture-hash"); + return saveAccount(db, account); + } + + private static Account saveAccount(DSLContext db, Account account) { + String schema = db.fetchSingle("SELECT current_schema()").get(0, String.class); + DriverManagerDataSource source = dataSource(schema); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + var ownerDsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + return transaction.execute(status -> new AccountRepository(ownerDsl).save(account)); + } + + private static Lookup insertPending(DSLContext db, UUID operation, UUID account) { + Lookup identity = + ConnectTokenRequestFingerprint.lookup( + account, UUID.randomUUID(), "opaque-scope", "requête-雪"); + db.execute( + "INSERT INTO connect_token_issuance_operation " + + "(operation_id,account_uuid,tenant_uuid,connect_scope_id,request_id,request_digest_version," + + "request_digest,status,response_recovery_expires_at,receipt_retain_until) " + + "VALUES (?,?,?,?,?,?,?,'PENDING',CURRENT_TIMESTAMP + INTERVAL '1 minute'," + + "CURRENT_TIMESTAMP + INTERVAL '1 hour')", + operation, + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId(), + identity.digestVersion(), + identity.requestDigest()); + return identity; + } + + private static void abort(DSLContext db, UUID operation) { + db.execute( + "UPDATE connect_token_issuance_operation SET status='ABORTED',failure_code='UNKNOWN_COMMIT' " + + "WHERE operation_id=?", + operation); + } + + private static AccountConnectIssuanceFenceEvidence capture( + DSLContext db, UUID operation, Lookup identity, IssuanceFence fence) { + return db.transactionResult( + configuration -> + new AccountConnectIssuanceFenceCaptureRepository(DSL.using(configuration)) + .capture(operation, identity, fence)); + } + + private static Optional read( + DSLContext db, UUID operation, Lookup identity) { + return db.transactionResult( + configuration -> + new AccountConnectIssuanceFenceCaptureRepository(DSL.using(configuration)) + .read(operation, identity)); + } + + private static String receipt(DSLContext db, UUID operation) { + return db.fetchSingle( + "SELECT xmin::text || ':' || to_jsonb(op)::text FROM connect_token_issuance_operation op " + + "WHERE operation_id=?", + operation) + .get(0, String.class); + } + + private static List> previousReceiptRows(DSLContext db) { + return db.fetch( + "SELECT xmin::text, operation_id, account_uuid, tenant_uuid, connect_scope_id, request_id, " + + "request_digest_version, request_digest, status, token_jti, token_hash, replay_admission_fence, " + + "encode(issuance_evidence,'hex') AS issuance, failure_code, reconciliation_blocked, " + + "encode(reconciliation_evidence,'hex') AS reconciliation, " + + "response_recovery_expires_at, receipt_retain_until, created_at, terminal_at " + + "FROM connect_token_issuance_operation ORDER BY operation_id") + .intoMaps(); + } + + private static List> envelopeRows(DSLContext db) { + return db.fetch( + "SELECT operation_id, encryption_key_id, encryption_version, " + + "encode(encrypted_response,'hex') AS response, " + + "encode(authenticated_binding,'hex') AS binding FROM connect_token_response_envelope") + .intoMaps(); + } + + private static DSLContext database(String version) { + String schema = "connect_capture_" + UUID.randomUUID().toString().replace("-", ""); + migration(schema).target(version).load().migrate(); + return DSL.using(dataSource(schema), SQLDialect.POSTGRES); + } + + private static FluentConfiguration migration(String schema) { + return Flyway.configure() + .dataSource(dataSource(schema)) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Properties properties = new Properties(); + properties.setProperty("ApplicationName", schema); + source.setConnectionProperties(properties); + return source; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..9a3307bcd4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationPostgresIntegrationTest.java @@ -0,0 +1,370 @@ +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.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourceObservationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real existing-only, non-authorizing observation. No token, restriction receipt or enrollment. */ +class AccountControlUiCurrentSourceObservationPostgresIntegrationTest { + private static final String ISSUER = "firemud-account-service"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + postgres.start(); + } + + @AfterAll + static void stop() { + postgres.stop(); + } + + @Test + void exactFreshAndAdvancedExistingSourcesAreObservedWithoutAnySqlMutation() { + var f = fixture(); + UUID account = f.createAccount(); + var before = f.rows(); + var observation = f.tx.execute(status -> f.observer.observeExisting(account)); + assertThat(observation.accountId()).isEqualTo(account); + assertThat(observation.sources().issuer().checkpoint().sequence()).isZero(); + assertThat(observation.sources().account().checkpoint().sequence()).isZero(); + assertThat(observation.sources().issuanceFence().accountId()).isEqualTo(account); + assertThat(observation.globalRoleSourceVersion()).isPositive(); + assertThat(observation.toString()).contains("non-authorizing"); + assertThat(f.rows()).isEqualTo(before); + + f.tx.executeWithoutResult( + status -> + f.sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "observation-advance-" + UUID.randomUUID())); + var advancedRows = f.rows(); + var advanced = f.tx.execute(status -> f.observer.observeExisting(account)); + var owner = f.tx.execute(status -> f.sources.readCurrentCanonicalIssuerSource(ISSUER)); + assertThat(advanced.sources().issuer()).isEqualTo(owner.source()); + assertThat(advanced.sources().canonicalIssuerProjection().toJson()) + .isEqualTo( + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.fromSource( + owner) + .toJson()); + assertThat(advanced.sources().issuer().generation()).isEqualTo(2L); + assertThat(advanced.sources().account()).isEqualTo(observation.sources().account()); + assertThat(owner.latestEvent()).isPresent(); + assertThat(f.rows()).isEqualTo(advancedRows); + } + + @Test + void absentIdentityAndNonOwnerTransactionsCannotEnrollOrMutateSources() { + var f = fixture(); + UUID account = f.createAccount(); + var before = f.rows(); + assertThatThrownBy(() -> f.observer.observeExisting(account)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("observation unavailable"); + var readOnly = new TransactionTemplate(f.manager); + readOnly.setReadOnly(true); + assertThatThrownBy(() -> readOnly.execute(status -> f.observer.observeExisting(account))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("observation unavailable"); + var wrongIsolation = new TransactionTemplate(f.manager); + wrongIsolation.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy(() -> wrongIsolation.execute(status -> f.observer.observeExisting(account))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("observation unavailable"); + assertThatThrownBy(() -> f.tx.execute(status -> f.observer.observeExisting(UUID.randomUUID()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("observation unavailable"); + assertThat(f.rows()).isEqualTo(before); + } + + @Test + void exactCountersCannotHideMissingOrContradictoryIssuerHistoryInIsolatedReaderClones() { + var f = fixture(); + UUID account = f.createAccount(); + f.tx.executeWithoutResult( + status -> + f.sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "observed-event-" + UUID.randomUUID())); + var canonical = f.rows(); + for (boolean missing : List.of(true, false)) { + f.tx.executeWithoutResult( + status -> { + // Ordinary negative-input copies only: no production trigger, function or role is + // changed. + f.dsl.execute( + "CREATE TEMP TABLE account_authority_outbox_events ON COMMIT DROP AS SELECT * FROM " + + f.schema + + ".account_authority_outbox_events"); + assertThat( + f.dsl + .fetchSingle( + "SELECT 'account_authority_outbox_events'::regclass::oid = " + + "'pg_temp.account_authority_outbox_events'::regclass::oid") + .get(0, Boolean.class)) + .isTrue(); + // The unmodified clone must really route through the same canonical reader first. + assertThat(f.observer.observeExisting(account).sources().issuer().generation()) + .isEqualTo(2L); + if (missing) { + assertThat( + f.dsl.execute( + "DELETE FROM pg_temp.account_authority_outbox_events WHERE outbox_stream_key=?", + "account:auth-authority:v1:issuer/" + ISSUER)) + .isEqualTo(1); + } else { + assertThat( + f.dsl.execute( + "UPDATE pg_temp.account_authority_outbox_events SET event_digest=? WHERE outbox_stream_key=?", + "sha256:" + "0".repeat(64), + "account:auth-authority:v1:issuer/" + ISSUER)) + .isEqualTo(1); + } + var clone = + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS row, xmin::text AS xmin FROM pg_temp.account_authority_outbox_events t ORDER BY 1,2") + .intoMaps(); + assertThatThrownBy(() -> f.observer.observeExisting(account)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS row, xmin::text AS xmin FROM pg_temp.account_authority_outbox_events t ORDER BY 1,2") + .intoMaps()) + .isEqualTo(clone); + assertThat(f.rows()).isEqualTo(canonical); + }); + } + assertThat( + f.tx + .execute(status -> f.observer.observeExisting(account)) + .sources() + .issuer() + .generation()) + .isEqualTo(2L); + assertThat(f.rows()).isEqualTo(canonical); + } + + @Test + void missingExistingAccountSourceNeverEnrollsOrRepairsItsBaseline() { + var f = fixture(); + UUID account = f.createAccount(); + var original = f.rows(); + f.tx.executeWithoutResult( + status -> { + f.dsl.execute( + "CREATE TEMP TABLE account_authority_source_records ON COMMIT DROP AS SELECT * FROM " + + f.schema + + ".account_authority_source_records"); + assertThat( + f.dsl + .fetchSingle( + "SELECT 'account_authority_source_records'::regclass::oid = " + + "'pg_temp.account_authority_source_records'::regclass::oid") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.observer.observeExisting(account).accountId()).isEqualTo(account); + assertThat( + f.dsl.execute( + "DELETE FROM pg_temp.account_authority_source_records WHERE account_uuid=?", + account)) + .isEqualTo(1); + var missing = + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS row,xmin::text AS xmin FROM pg_temp.account_authority_source_records t ORDER BY 1,2") + .intoMaps(); + assertThatThrownBy(() -> f.observer.observeExisting(account)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS row,xmin::text AS xmin FROM pg_temp.account_authority_source_records t ORDER BY 1,2") + .intoMaps()) + .isEqualTo(missing); + assertThat(f.rows()).isEqualTo(original); + }); + assertThat(f.tx.execute(status -> f.observer.observeExisting(account)).accountId()) + .isEqualTo(account); + assertThat(f.rows()).isEqualTo(original); + } + + @Test + void actualConcurrentIssuerAdvanceWaitsForTheObservedCompositeCut() throws Exception { + var f = fixture(); + UUID account = f.createAccount(); + var ready = new CountDownLatch(1); + var release = new CountDownLatch(1); + var readerPid = new CompletableFuture(); + var writerPid = new CompletableFuture(); + var executor = Executors.newFixedThreadPool(2); + try { + var reader = + executor.submit( + () -> + f.tx.execute( + status -> { + readerPid.complete( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var cut = f.observer.observeExisting(account); + ready.countDown(); + try { + assertThat(release.await(30, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return cut; + })); + var writer = + executor.submit( + () -> { + assertThat(ready.await(30, TimeUnit.SECONDS)).isTrue(); + f.tx.executeWithoutResult( + status -> { + writerPid.complete( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + f.sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "waiting-" + UUID.randomUUID()); + }); + return null; + }); + int reading = readerPid.get(30, TimeUnit.SECONDS); + int writing = writerPid.get(30, TimeUnit.SECONDS); + boolean blocked = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (System.nanoTime() < deadline) { + var wait = + f.dsl.fetchOne( + "SELECT wait_event_type='Lock' AND ?=ANY(pg_blocking_pids(pid)) FROM pg_stat_activity WHERE pid=?", + reading, + writing); + if (wait != null && Boolean.TRUE.equals(wait.get(0, Boolean.class))) { + blocked = true; + break; + } + Thread.sleep(20); + } + assertThat(blocked) + .as("real PostgreSQL issuer writer blocked by observing transaction") + .isTrue(); + assertThat(writer.isDone()).isFalse(); + release.countDown(); + assertThat(reader.get(30, TimeUnit.SECONDS).sources().issuer().generation()).isEqualTo(1L); + writer.get(30, TimeUnit.SECONDS); + assertThat( + f.tx + .execute(status -> f.observer.observeExisting(account)) + .sources() + .issuer() + .generation()) + .isEqualTo(2L); + } finally { + release.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(15, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static Fixture fixture() { + String schema = "account_observe_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = postgres.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(source); + var tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var evidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + var accounts = new AccountRepository(dsl, evidence); + return new Fixture( + schema, + dsl, + manager, + tx, + evidence, + accounts, + new AccountControlUiCurrentSourceObservationRepository(dsl, accounts, evidence)); + } + + private record Fixture( + String schema, + DSLContext dsl, + DataSourceTransactionManager manager, + TransactionTemplate tx, + AccountAuthoritySourceEvidenceRepository sources, + AccountRepository accounts, + AccountControlUiCurrentSourceObservationRepository observer) { + UUID createAccount() { + return tx.execute( + status -> { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("observed-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-hash"); + return accounts.save(account).getAccountUuid(); + }); + } + + Map>> rows() { + var result = new java.util.TreeMap>>(); + for (String table : + dsl.fetch("SELECT tablename FROM pg_tables WHERE schemaname=? ORDER BY tablename", schema) + .getValues(0, String.class)) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(t)::text AS row,xmin::text AS xmin FROM " + + schema + + "." + + table + + " t ORDER BY 1,2") + .intoMaps()); + } + return result; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index b92719929e..d11922e38b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -75,6 +76,110 @@ void dropRunOwnedSchemas() { schemas.clear(); } + @Test + void v39PreservesRetainedAuditRowsAndRejectsMixedTenantIdentity() { + TestContext context = newTestContextAt("38"); + DSLContext dsl = context.dsl(); + UUID platformEventId = UUID.randomUUID(); + UUID numericEventId = UUID.randomUUID(); + String platformPayload = "{\"account\": \"retained platform evidence\"}"; + String numericPayload = "{\"membership\": \"retained tenant evidence\"}"; + dsl.execute( + """ + INSERT INTO account_audit_outbox + (audit_event_id, scope, tenant_id, producer_service, event_type, occurred_at, + schema_version, payload_digest_version, payload_digest, payload, attempt_count) + VALUES (?, 'platform', NULL, 'account-service', 'ACCOUNT_REGISTERED', + TIMESTAMP '2026-10-01 12:34:56.123456', 1, 1, ?, ?, 2), + (?, 'tenant', 73, 'account-service', 'ACCOUNT_JOINED_PUBLIC_PRODUCTION', + TIMESTAMP '2026-10-01 12:35:56.123456', 1, 1, ?, ?, 3) + """, + platformEventId, + AccountAuditDigest.ofPayload(platformPayload), + platformPayload, + numericEventId, + AccountAuditDigest.ofPayload(numericPayload), + numericPayload); + + String retainedRows = + """ + SELECT (to_jsonb(audit) - 'tenant_identity_version' - 'tenant_uuid')::text AS row_image, + audit.xmin::text AS row_version + FROM account_audit_outbox audit + ORDER BY audit_event_id + """; + String heapQuery = "SELECT pg_relation_filenode(?::regclass)::text"; + String auditRelation = context.schema() + ".account_audit_outbox"; + var before = dsl.fetch(retainedRows); + var heapBefore = dsl.fetchSingle(heapQuery, auditRelation); + assertThat(before).hasSize(2); + + migrateToVersion(context, "39"); + + assertThat(dsl.fetch(retainedRows)).isEqualTo(before); + assertThat(dsl.fetchSingle(heapQuery, auditRelation)).isEqualTo(heapBefore); + assertThat( + dsl.fetchSingle( + "SELECT column_default FROM information_schema.columns WHERE table_schema = ? " + + "AND table_name = 'account_audit_outbox' " + + "AND column_name = 'tenant_identity_version'", + context.schema()) + .get(0, String.class)) + .isNull(); + String fullRows = + """ + SELECT to_jsonb(audit)::text AS row_image, audit.xmin::text AS row_version, + tenant_identity_version, tenant_uuid + FROM account_audit_outbox audit + ORDER BY audit_event_id + """; + var upgraded = dsl.fetch(fullRows); + assertThat(upgraded) + .allSatisfy( + row -> { + assertThat(row.get("tenant_identity_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_uuid", UUID.class)).isNull(); + }); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_audit_outbox SET tenant_identity_version = 2, tenant_uuid = ? " + + "WHERE audit_event_id = ?", + UUID.randomUUID(), + numericEventId)) + .isInstanceOfSatisfying( + DataAccessException.class, + error -> { + assertThat(error.sqlState()).isEqualTo("23514"); + assertThat(error.getMessage()) + .contains("Retained Account audit identity cannot change representation"); + }); + assertThatThrownBy( + () -> + dsl.execute( + """ + INSERT INTO account_audit_outbox + (audit_event_id, scope, tenant_id, producer_service, event_type, + occurred_at, schema_version, payload_digest_version, payload_digest, + payload, tenant_identity_version, tenant_uuid) + SELECT ?, scope, NULL, producer_service, event_type, + occurred_at, schema_version, payload_digest_version, payload_digest, + payload, 2, ? + FROM account_audit_outbox WHERE audit_event_id = ? + """, + UUID.randomUUID(), + new UUID(0, 0), + numericEventId)) + .isInstanceOfSatisfying( + DataAccessException.class, + error -> { + assertThat(error.sqlState()).isEqualTo("23514"); + assertThat(error.getMessage()).contains("account_audit_outbox_scope_identity_check"); + }); + assertThat(dsl.fetch(fullRows)).isEqualTo(upgraded); + } + @Test void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { TestContext context = newTestContextAtV39(); @@ -342,6 +447,102 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .isZero(); } + @Test + void canonicalUpgradeWaitsForLegacyWriterAndPreservesItsUnverifiedIdentity() throws Exception { + TestContext context = newTestContextBeforeV38(); + DSLContext dsl = context.dsl(); + org.jooq.Record account = + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, role) VALUES (?, ?, ?, ?) " + + "RETURNING id, account_uuid", + "writer-" + UUID.randomUUID(), + "writer-" + UUID.randomUUID() + "@example.test", + "test-hash", + "platformAdmin"); + long accountId = Objects.requireNonNull(account).get("id", Long.class); + try (java.sql.Connection writer = context.dataSource().getConnection()) { + writer.setAutoCommit(false); + DSLContext writerDsl = DSL.using(writer, SQLDialect.POSTGRES); + int writerPid = writerDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + var original = + writerDsl.fetchSingle( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id, account_id, tenant_id, tenant_uuid, gameplay_admission_allowed, " + + "lifecycle_state, membership_version, membership_authority_generation, " + + "authority_provenance, xmin::text AS row_version", + accountId, + 7102L); + var originalRows = original.intoMap(); + long membershipId = original.get("id", Long.class); + var executor = Executors.newSingleThreadExecutor(); + try { + var migration = executor.submit(() -> migrateToVersion(context, "38")); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + boolean blocked = false; + while (System.nanoTime() < deadline) { + blocked = + Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE " + + "wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)))", + writerPid) + .get(0, Boolean.class)); + if (blocked) break; + Thread.sleep(10); + } + assertThat(blocked) + .as("canonical migration physically waits for its legacy writer") + .isTrue(); + assertThat(migration.isDone()).isFalse(); + writer.commit(); + migration.get(60, TimeUnit.SECONDS); + + // V38 waits for the committed writer without changing either evidence or row version. + assertThat(retainedMembership(context, membershipId).intoMap()).isEqualTo(originalRows); + migrateToVersion(context, "40"); + assertThat(retainedMembership(context, membershipId).intoMap()).isEqualTo(originalRows); + String originalHeap = membershipHeap(context); + + // V40.1 deliberately adds a STORED generated retention key, rewriting the physical heap. + // Logical identity/authority must remain exact; xmin is not immutable across that DDL. + migrateToVersion(context, "40.1"); + var rewritten = retainedMembership(context, membershipId).intoMap(); + var originalEvidence = new java.util.LinkedHashMap<>(originalRows); + var rewrittenEvidence = new java.util.LinkedHashMap<>(rewritten); + originalEvidence.remove("row_version"); + rewrittenEvidence.remove("row_version"); + assertThat(rewrittenEvidence).isEqualTo(originalEvidence); + assertThat(rewritten.get("row_version")).isNotEqualTo(originalRows.get("row_version")); + String rewrittenHeap = membershipHeap(context); + assertThat(rewrittenHeap).isNotEqualTo(originalHeap); + + migrateToLatest(context); + assertThat(retainedMembership(context, membershipId).intoMap()).isEqualTo(rewritten); + assertThat(membershipHeap(context)).isEqualTo(rewrittenHeap); + assertThat(original.get("tenant_uuid", UUID.class)).isNull(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_tenant_membership_role_snapshots " + + "WHERE membership_id = ?", + membershipId) + .fetchOne(0, Long.class)) + .isZero(); + assertThat(dsl.fetchCount(org.jooq.impl.DSL.table("account_authority_outbox_events"))) + .isZero(); + } finally { + try { + writer.rollback(); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + @Test void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { TestContext context = newTestContextAtV39(); @@ -454,6 +655,88 @@ void databaseRejectsDeletingAHeadWithRetainedHistoryWithoutChangingEvidence() { .isEqualTo(1L); } + @Test + void databaseRejectsRetainedEventMutationAndStillAllowsExactAppendAndStreamAdvance() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + DSLContext dsl = context.dsl(); + String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); + byte[] retainedPayload = new byte[] {31, 32, 33}; + // Component storage proof only: this does not execute or authorize a positive JOIN. + Event retained = + inTransaction( + transaction, + () -> + repository.append( + stream, + "immutable-request-1", + "immutable-event-1", + "immutable-digest-1", + retainedPayload)); + Checkpoint retainedCheckpoint = + new Checkpoint(stream, 1L, retained.eventId(), retained.eventDigest()); + + for (String statement : + List.of( + "UPDATE account_authority_outbox_events SET payload = decode('ffff', 'hex') " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + "DELETE FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1")) { + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> { + dsl.execute(statement, stream); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Account authority outbox event evidence is immutable"); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 1L))) + .contains(retained); + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))) + .contains(retainedCheckpoint); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + Event appended = + inTransaction( + transaction, + () -> + repository.append( + stream, + "immutable-request-2", + "immutable-event-2", + "immutable-digest-2", + new byte[] {41, 42, 43})); + assertThat(appended.outboxSequence()).isEqualTo(2L); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 1L))) + .contains(retained); + assertThat( + inTransaction(transaction, () -> repository.findEvent(stream, 1L)) + .orElseThrow() + .payload()) + .containsExactly(retainedPayload); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 2L))) + .contains(appended); + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))) + .contains(new Checkpoint(stream, 2L, appended.eventId(), appended.eventDigest())); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + } + @Test void databaseRejectsTruncatingOutboxHistoryAndPreservesEventsAndCheckpoint() { TestContext context = newTestContext(); @@ -776,14 +1059,39 @@ private TestContext newTestContextAt(String targetVersion) { } private void migrateToLatest(TestContext context) { - Flyway.configure() - .dataSource(context.dataSource()) - .schemas(context.schema()) - .defaultSchema(context.schema()) - .placeholders(Map.of("serviceSchema", context.schema())) - .locations("classpath:db/migration") - .load() - .migrate(); + migrateToVersion(context, null); + } + + private void migrateToVersion(TestContext context, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration"); + if (targetVersion != null) configuration.target(targetVersion); + configuration.load().migrate(); + } + + private org.jooq.Record retainedMembership(TestContext context, long membershipId) { + return context + .dsl() + .fetchSingle( + "SELECT id, account_id, tenant_id, tenant_uuid, gameplay_admission_allowed, " + + "lifecycle_state, membership_version, membership_authority_generation, " + + "authority_provenance, xmin::text AS row_version " + + "FROM account_tenant_membership WHERE id = ?", + membershipId); + } + + private String membershipHeap(TestContext context) { + return context + .dsl() + .fetchSingle( + "SELECT pg_relation_filenode(?::regclass)::text", + context.schema() + ".account_tenant_membership") + .get(0, String.class); } private String membershipStream(UUID accountId, UUID tenantId) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java index 8743b5b649..2b365783f1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java @@ -70,6 +70,28 @@ void actualNewInsertCommitsBothExplicitOwnerDecisionsCurrentHeadsAndOriginalEven context.dsl.fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isEqualTo(2); assertThat(context.dsl.fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(2); + // Each completed owner boundary retains exact provenance even though the final commit + // contains baseline plus both genuine category transitions in one Account transaction. + var provenance = + context.dsl.fetch( + "SELECT issuance_fence, prior_fence, cause_kind, event_sequence, generation, authority_source_version FROM account_issuance_fence_provenance WHERE account_uuid = ? ORDER BY issuance_fence", + result.accountUuid()); + assertThat(provenance.getValues("issuance_fence", Long.class)).containsExactly(1L, 2L, 3L); + assertThat(provenance.getValues("prior_fence", Long.class)).containsExactly(0L, 1L, 2L); + assertThat(provenance.getValues("cause_kind", String.class)) + .containsExactly("BASELINE", "ACCOUNT", "ACCOUNT"); + assertThat(provenance.getValues("event_sequence", Long.class)).containsExactly(0L, 1L, 2L); + assertThat(provenance.getValues("generation", Long.class)).containsExactly(1L, 2L, 3L); + assertThat(provenance.getValues("authority_source_version", Long.class)) + .containsExactly(1L, 2L, 3L); + assertThat( + context + .dsl + .fetchSingle( + "SELECT count(*) FROM account_issuance_fence_provenance p JOIN account_authority_outbox_events e ON (e.outbox_stream_key,e.outbox_sequence,e.event_id,e.event_digest) = (p.source_stream_key,p.event_sequence,p.event_id,p.event_digest) WHERE p.account_uuid = ? AND p.cause_kind = 'ACCOUNT'", + result.accountUuid()) + .get(0, Long.class)) + .isEqualTo(2L); context.transaction.executeWithoutResult( status -> { var roleSource = @@ -136,6 +158,33 @@ void actualNewInsertCommitsBothExplicitOwnerDecisionsCurrentHeadsAndOriginalEven .isEqualTo("active"); } + @Test + void currentSchemaMissingProvenanceConstraintFailsClosedWithoutEnrolling() throws Exception { + Context context = context(null); + controlledPolicies(context); + assertThatThrownBy( + () -> + context.transaction.executeWithoutResult( + status -> { + context.dsl.execute( + "DROP TRIGGER account_fence_provenance_consistent ON account_issuance_fence_provenance"); + producer(context).enroll(request()); + })) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("account_fence_provenance_consistent") + .hasMessageContaining("does not exist"); + assertNoEnrollmentState(context); + // The deliberate test-only DDL is rolled back with the refused owner transaction. + assertThat( + context + .dsl + .fetchSingle( + "SELECT count(*) FROM pg_trigger WHERE tgname = 'account_fence_provenance_consistent' AND tgrelid = 'account_issuance_fence_provenance'::regclass") + .get(0, Long.class)) + .isEqualTo(1L); + } + @Test void sourceGuardsStillRefuseGenerationOrFenceAdvanceWithoutExactSourceEvidenceAtCommit() throws Exception { @@ -587,7 +636,8 @@ private static void assertNoEnrollmentState(Context context) { "account_platform_restriction_operations", "account_platform_restriction_revisions", "account_platform_restriction_current_projections", - "account_authority_outbox_events" + "account_authority_outbox_events", + "account_issuance_fence_provenance" }) { assertThat(context.dsl.fetchCount(DSL.table(table))).as(table).isZero(); } @@ -608,7 +658,8 @@ private static void checkCompletedSourceBoundary(Context context) { // so their final refusal must come from the intended enrollment-completeness constraint. String constraints = "account_authority_source_generation_consistent, " - + "account_authority_source_fence_consistent, account_authority_source_record_consistent"; + + "account_authority_source_fence_consistent, account_authority_source_record_consistent, " + + "account_fence_provenance_consistent"; context.dsl.execute("SET CONSTRAINTS " + constraints + " IMMEDIATE"); context.dsl.execute("SET CONSTRAINTS " + constraints + " DEFERRED"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index e68ba4930b..c4c012d4e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -75,6 +75,8 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionAbortResolution; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; @@ -115,6 +117,8 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; @@ -262,6 +266,75 @@ void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners( .isEqualTo(current.leaseSourceFields()); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + value = SourceKind.class, + names = {"ACCOUNT", "GLOBAL_ROLES"}) + void waitingGlobalIntentDeniesNewSourcesAndOriginalCommitButNotCallerOnlyRecovery(SourceKind kind) + throws Exception { + Fixture fixture = newFixture(null, "latest", false, false, null); + var candidate = fixture.readCommittedCandidate(); + var current = fixture.readCurrent(candidate); + var lease = fixture.beginPendingAdmissionLease(current); + var change = fixture.retainWaitingSourceChange(kind, fixture.account.getAccountUuid()); + var before = fixture.sourceAndIssuanceImage(); + + assertThatThrownBy(() -> fixture.readCurrent(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay admission current sources are unavailable"); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources(lease, UUID.randomUUID(), TEST_NAMESPACE, candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay admission current sources are unavailable"); + assertThat(fixture.readLeaseOperation(lease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + assertThat(fixture.readLeaseOperation(lease).evidence().canonicalJson()) + .isEqualTo(lease.canonicalJson()); + fixture.inCurrentSources( + sources -> { + sources.requireCurrentAuthenticatedCallerOnly(candidate); + return null; + }); + assertThat(fixture.sourceAndIssuanceImage()).isEqualTo(before); + + fixture.transaction.execute( + status -> { + new DraftAuthorizationFenceRepository(fixture.dsl) + .markSourceAborted( + change, + DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + assertThat(fixture.readCurrent(candidate).leaseSourceFields()) + .isEqualTo(current.leaseSourceFields()); + assertThat( + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources(lease, UUID.randomUUID(), TEST_NAMESPACE, candidate) + .evidence()) + .isEqualTo(lease); + } + + @Test + void differentAccountAndTenantOnlyWaitingIntentDoNotBecomeGlobalAdmissionDenials() + throws Exception { + Fixture fixture = newFixture(); + var current = fixture.readCurrent(fixture.committedCandidate); + Account other = new Account(); + String suffix = UUID.randomUUID().toString(); + other.setUsername("other-" + suffix); + other.setEmail("other-" + suffix + "@example.test"); + other.setPasswordHash("controlled-fixture-password"); + var persisted = fixture.transaction.execute(status -> fixture.accounts.save(other)); + fixture.retainWaitingSourceChange(SourceKind.GLOBAL_ROLES, persisted.getAccountUuid()); + fixture.retainWaitingSourceChange(SourceKind.TENANT, fixture.tenantUuid); + var before = fixture.sourceAndIssuanceImage(); + assertThat(fixture.readCurrent(fixture.committedCandidate).leaseSourceFields()) + .isEqualTo(current.leaseSourceFields()); + assertThat(fixture.sourceAndIssuanceImage()).isEqualTo(before); + } + @Test void paidCurrentReadAndOriginalPhysicalCommitUseTheGenuineOwnerWithoutChangingSources() throws Exception { @@ -2126,6 +2199,16 @@ private Fixture newFixture( boolean currentScope, boolean capacityBootstrap) throws Exception { + return newFixture(redisClient, migrationTarget, currentScope, capacityBootstrap, "player"); + } + + private Fixture newFixture( + AccountGameplayDelegationRedisClient redisClient, + String migrationTarget, + boolean currentScope, + boolean capacityBootstrap, + String legacyRole) + throws Exception { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); runOwnedSchemas.add(schema); @@ -2150,7 +2233,8 @@ private Fixture newFixture( temporaryDirectory, redisClient, currentScope, - capacityBootstrap); + capacityBootstrap, + legacyRole); } private static int awaitBackendBlockedBy( @@ -2851,7 +2935,8 @@ private Fixture( Path temporaryDirectory, AccountGameplayDelegationRedisClient redisClient, boolean currentScope, - boolean capacityBootstrap) + boolean capacityBootstrap, + String legacyRole) throws Exception { this.capacityBootstrap = capacityBootstrap; this.schema = schema; @@ -2920,7 +3005,7 @@ private Fixture( newAccount.setUsername("current-source-" + suffix); newAccount.setEmail("current-source-" + suffix + "@example.test"); newAccount.setPasswordHash("integration-fixture-password-hash"); - newAccount.setRole("player"); + newAccount.setRole(legacyRole); this.account = transaction.execute(status -> accounts.save(newAccount)); var retainedScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); this.joinScope = @@ -3272,6 +3357,59 @@ private AccountGameplayAdmissionCurrentSources.Current readCurrent( tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate)); } + /** Real durable scoped evidence; deliberately stops before any source mutation. */ + private SourceChange retainWaitingSourceChange(SourceKind kind, UUID scopeId) { + return transaction.execute( + status -> { + SourceEvidence source; + if (kind == SourceKind.TENANT) { + var event = tenantAuthorityEvents.readCurrentByTenant(scopeId); + source = + new SourceEvidence( + kind, + scopeId.toString(), + Long.toString(event.tenantAuthorityGeneration()), + Long.toString(event.tenantAuthoritySourceVersion()), + event.outboxStreamKey(), + Long.toString(event.outboxSequence()), + event.payload()); + } else { + var state = generations.read(AuthorityScope.account(scopeId)); + var row = + dsl.fetchSingle( + "SELECT r.global_role_source_version, " + + "to_jsonb(a)::text AS account_evidence, to_jsonb(r)::text AS role_evidence " + + "FROM accounts a JOIN account_global_role_sources r USING (account_uuid) " + + "WHERE a.account_uuid = ?", + scopeId); + source = + new SourceEvidence( + kind, + scopeId.toString(), + kind == SourceKind.ACCOUNT ? Long.toString(state.generation()) : null, + Long.toString( + kind == SourceKind.ACCOUNT + ? state.sourceVersion() + : row.get("global_role_source_version", Long.class)), + null, + null, + row.get( + kind == SourceKind.ACCOUNT ? "account_evidence" : "role_evidence", + String.class) + .getBytes(StandardCharsets.UTF_8)); + } + var change = + new SourceChange( + UUID.randomUUID(), + List.of(source), + "controlled pending mutation".getBytes(StandardCharsets.UTF_8)); + var fences = new DraftAuthorizationFenceRepository(dsl); + assertThat(fences.requestSourceChange(change)).isTrue(); + assertThat(fences.readSourceChange(change).status()).isEqualTo("WAITING"); + return change; + }); + } + private T inCurrentSources( java.util.function.Function read) { return serializable.execute( @@ -3949,7 +4087,16 @@ private RedisHarness( } else if (key.equals( AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + GameSessionAccountDelegationProfile.ISSUER)) { - authorityProjectionBytes[0] = arguments[0].clone(); + assertThat(arguments.length).isEqualTo(3); + assertThat(arguments[1]).containsExactly(authorityProjectionBytes[0]); + String mode = new String(arguments[0], StandardCharsets.US_ASCII); + if ("VERIFY".equals(mode)) { + assertThat(arguments[2]).isEmpty(); + return 0L; + } + assertThat(mode).isEqualTo("PRESENT"); + assertThat(arguments[2]).isNotEmpty(); + authorityProjectionBytes[0] = arguments[2].clone(); } else if (key.equals( AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { if (arguments.length == 3 && arguments[2].length > 0) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 546b3af7e3..0ba166598f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -2,6 +2,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.Mockito.mock; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; @@ -10,6 +12,7 @@ import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.SQLException; +import java.sql.Statement; import java.time.Instant; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -19,6 +22,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; @@ -35,6 +41,7 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DelegatingDataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; @@ -578,6 +585,79 @@ void historicalRecoveryCannotSeeReceiptCommittedAfterItsFixedSnapshot() throws E } } + @Test + void v144AndCurrentMigrationsPreservePreReceiptOperationsWithoutInventingAcknowledgement() { + var context = context("143"); + var committed = pending(context, 15000); + UUID decision = UUID.randomUUID(); + context + .transaction() + .execute( + status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(committed, decision)); + var pending = pending(context, 15000); + assertThat(operation(context, committed).get("status")).isEqualTo("COMMITTED"); + assertThat(operation(context, pending).get("status")).isEqualTo("PENDING"); + var committedBefore = admissionOperationImage(context, committed); + var pendingBefore = admissionOperationImage(context, pending); + Integer originalRank = + context + .dsl() + .fetchSingle("SELECT max(installed_rank) FROM flyway_schema_history") + .get(0, Integer.class); + String retainedMigrations = + "SELECT to_jsonb(h)::text FROM flyway_schema_history h " + + "WHERE installed_rank <= ? ORDER BY installed_rank"; + var historyBefore = + context.dsl().fetch(retainedMigrations, originalRank).getValues(0, String.class); + assertThat( + context + .dsl() + .fetchCount(DSL.table("flyway_schema_history"), DSL.condition("version = '143'"))) + .isOne(); + + Flyway.configure() + .dataSource(context.admin()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); + + assertThat(context.dsl().fetch(retainedMigrations, originalRank).getValues(0, String.class)) + .containsExactlyElementsOf(historyBefore); + assertThat( + context + .dsl() + .fetchCount(DSL.table("flyway_schema_history"), DSL.condition("version = '144'"))) + .isOne(); + assertThat(admissionOperationImage(context, committed)).isEqualTo(committedBefore); + assertThat(admissionOperationImage(context, pending)).isEqualTo(pendingBefore); + var receiptTable = DSL.table("account_gameplay_admission_original_commit_ack_receipts"); + assertThat(context.dsl().fetchCount(receiptTable)).isZero(); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(committed, decision)) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + assertThat(context.dsl().fetchCount(receiptTable)).isZero(); + assertThat(admissionOperationImage(context, committed)).isEqualTo(committedBefore); + assertThat(admissionOperationImage(context, pending)).isEqualTo(pendingBefore); + } + + private static String admissionOperationImage( + Context context, AccountGameplayAdmissionLeaseEvidence evidence) { + return context + .dsl() + .fetchSingle( + "SELECT to_jsonb(o)::text || '|xmin=' || o.xmin::text " + + "FROM account_gameplay_admission_lease_operations o WHERE request_id = ?", + request(evidence)) + .get(0, String.class); + } + @Test void v1013QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { var context = context("1012"); @@ -844,6 +924,46 @@ private Connection delayedCommitConnection(Connection physical) { assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } + @Test + void lostPostAcknowledgementClockResponseCannotBeRemintedFromCommittedRetry() { + var context = context(); + var evidence = pending(context, 15000); + long originalExpiryMs = Long.parseLong((String) evidence.carrier().get("expiresAt")); + UUID decision = UUID.randomUUID(); + var sourcesBefore = sourceSnapshot(context); + var physicalCommits = new AtomicInteger(); + var lostClockResponses = new AtomicInteger(); + var source = + losePostCommitClockResponse( + context.admin(), originalExpiryMs, physicalCommits, lostClockResponses); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(source) + .execute(evidence, decision)) + .hasMessageContaining("post-COMMIT clock unavailable") + .hasRootCauseMessage("Post-COMMIT clock response lost"); + + assertThat(physicalCommits.get()).isOne(); + assertThat(lostClockResponses.get()).isOne(); + var committed = operation(context, evidence); + assertThat(committed.get("status")).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id")).isEqualTo(decision); + assertThat((String) committed.get("finalization_xid")).matches("[1-9][0-9]{0,19}"); + assertThat(committed.get("evidence_json")).isEqualTo(evidence.canonicalJson()); + assertThat(committed.get("expires_at_ms")).isEqualTo(originalExpiryMs); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, evidence)).isEqualTo(committed); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + @Test void lostOriginalCommitAcknowledgementCannotReconstructCapabilityOrRetryFinalization() { var context = context(); @@ -1460,6 +1580,77 @@ public Connection getConnection() throws SQLException { }; } + private static DataSource losePostCommitClockResponse( + DataSource delegate, + long originalExpiryMs, + AtomicInteger physicalCommits, + AtomicInteger lostClockResponses) { + return new DelegatingDataSource(delegate) { + @Override + public Connection getConnection() throws SQLException { + Connection physical = super.getConnection(); + try { + var committed = new AtomicBoolean(); + var physicalCalls = delegatesTo(physical); + return mock( + Connection.class, + call -> { + String method = call.getMethod().getName(); + if ("commit".equals(method)) { + physical.commit(); + physicalCommits.incrementAndGet(); + committed.set(true); + return null; + } + if ("createStatement".equals(method) + && call.getArguments().length == 0 + && committed.get()) { + return withPostCommitClockResponseLoss( + physical.createStatement(), originalExpiryMs, lostClockResponses); + } + return physicalCalls.answer(call); + }); + } catch (RuntimeException | Error failure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + }; + } + + private static Statement withPostCommitClockResponseLoss( + Statement physical, long originalExpiryMs, AtomicInteger lostClockResponses) { + try { + var physicalCalls = delegatesTo(physical); + return mock( + Statement.class, + call -> { + if ("executeQuery".equals(call.getMethod().getName()) + && "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint" + .equals(call.getArgument(0))) { + try (var reply = physical.executeQuery(call.getArgument(0))) { + assertThat(reply.next()).isTrue(); + assertThat(reply.getLong(1)).isPositive().isLessThan(originalExpiryMs); + } + lostClockResponses.incrementAndGet(); + throw new SQLException("Post-COMMIT clock response lost", "08006"); + } + return physicalCalls.answer(call); + }); + } catch (RuntimeException | Error failure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { return finalized(context, lifetime, 7L); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index dfd312e520..193fe320f0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -13,6 +13,7 @@ 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 static org.mockito.Mockito.when; import de.mkammerer.argon2.Argon2; @@ -43,6 +44,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -71,6 +73,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.StaleAuthorityException; @@ -128,6 +131,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.databind.json.JsonMapper; @@ -555,6 +559,160 @@ void deterministicOtpFixtureAndCanonicalLoginCommitBeforeReturningCredential() t assertThat(challenge.getId()).isNotNull(); } + @Test + void concurrentExactInitialLoginReplaysOneDurablePendingIntent() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + AccountAuthoritySourceEvidenceRepository sources = + sourceEvidence(dsl, new AccountAuthorityGenerationRepository(dsl)); + Account account = createEmailOtpAccount(context, sources); + AccountEmailLoginChallengeRepository challenges = + spy(new AccountEmailLoginChallengeRepository(dsl)); + AccountEmailLoginChallenge challenge = + persistEmailLoginChallenge(context, challenges, account.getId(), "123456"); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + CanonicalGameplayLoginRequest request = + canonicalLoginRequest(account.getEmail(), "123456", requestId, callerContextId); + + CountDownLatch pendingWritten = new CountDownLatch(1); + CountDownLatch contenderReady = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicInteger contenderPid = new AtomicInteger(); + AtomicReference firstIntent = new AtomicReference<>(); + AccountRepository accounts = spy(new AccountRepository(dsl, sources)); + doAnswer( + invocation -> { + int pid = + Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + if (!firstPid.compareAndSet(0, pid)) { + contenderPid.set(pid); + contenderReady.countDown(); + } + return invocation.callRealMethod(); + }) + .when(accounts) + .findByIdForUpdate(account.getId()); + doAnswer( + invocation -> { + invocation.callRealMethod(); + // PENDING insertion and OTP consumption are visible on this connection only. + firstIntent.set(readLoginIntent(dsl, requestId)); + pendingWritten.countDown(); + assertThat(releaseFirst.await(30, TimeUnit.SECONDS)).isTrue(); + return null; + }) + .when(challenges) + .delete(any(AccountEmailLoginChallenge.class)); + + AccountGameplayDelegationIssuanceRepository issuance = + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources), context.manager()); + AccountGameplayDelegationIssuanceCommitService commitOwner = + mock(AccountGameplayDelegationIssuanceCommitService.class); + AccountGameplayDelegationResponseRecoveryOwner responseOwner = + mock(AccountGameplayDelegationResponseRecoveryOwner.class); + String stopBeforeSigning = "Controlled stop before signing the replayable PENDING intent"; + when(commitOwner.commitPendingCandidate(requestId)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + throw new IllegalStateException(stopBeforeSigning); + }); + AccountGameplayCredentialRequestDigestKeySource digestKeys = integrationDigestKeySource(); + AccountGameplayCanonicalLoginOwner loginOwner = + new AccountGameplayCanonicalLoginOwner( + accounts, + issuance, + digestKeys, + commitOwner, + responseOwner, + context.manager(), + Clock.systemUTC()); + AtomicInteger replayVerifierCalls = new AtomicInteger(); + var replayVerifier = verifierMustNotRun(replayVerifierCalls); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + loginOwner.authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "123456"))); + assertThat(pendingWritten.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(firstIntent.get()).isNotNull(); + assertThat(readLoginIntent(dsl, requestId)).isNull(); + assertThat(challenges.findByAccountId(account.getId()).orElseThrow().getId()) + .isEqualTo(challenge.getId()); + + var contender = + executor.submit(() -> loginOwner.authenticate(request, CALLER_WORKLOAD, replayVerifier)); + assertThat(contenderReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(firstPid.get()).isPositive(); + assertThat(contenderPid.get()).isPositive().isNotEqualTo(firstPid.get()); + assertThat( + waitUntilBlockedBy( + dsl, contenderPid.get(), firstPid.get(), TimeUnit.SECONDS.toNanos(10))) + .as("exact LOGIN contender must wait on the first claimant's Account row") + .isTrue(); + verifyNoInteractions(commitOwner, responseOwner); + + releaseFirst.countDown(); + assertThatThrownBy(() -> first.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasRootCauseMessage(stopBeforeSigning); + assertThatThrownBy(() -> contender.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasRootCauseMessage(stopBeforeSigning); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + assertThatThrownBy(() -> loginOwner.authenticate(request, CALLER_WORKLOAD, replayVerifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(stopBeforeSigning); + CanonicalGameplayLoginRequest changedCredential = + canonicalLoginRequest(account.getEmail(), "654321", requestId, callerContextId); + assertThatThrownBy( + () -> loginOwner.authenticate(changedCredential, CALLER_WORKLOAD, replayVerifier)) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + assertThat(replayVerifierCalls).hasValue(0); + verify(challenges).delete(any(AccountEmailLoginChallenge.class)); + verify(commitOwner, times(3)).commitPendingCandidate(requestId); + verifyNoInteractions(responseOwner); + assertThat(challenges.findByAccountId(account.getId())).isEmpty(); + + var replay = + inTransaction( + context, () -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(replay.created()).isFalse(); + assertThat(replay.state()).isEqualTo(GameplayLoginReplayState.PENDING); + assertThat(replay.operation().candidateBound()).isFalse(); + assertThat(replay.identity().accountId()).isEqualTo(account.getAccountUuid()); + assertThat(replay.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(replay.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(replay.identity().credentialRequestBinding()) + .isEqualTo( + AccountGameplayCredentialRequestDigester.bind( + digestKeys.currentKey(), + request, + account.getEmail(), + CALLER_WORKLOAD, + account.getAccountUuid())); + assertThat(readLoginIntent(dsl, requestId)).isEqualTo(firstIntent.get()); + assertThat(dsl.fetchCount(DSL.table("account_gameplay_delegation_issuance_operations"))) + .isOne(); + assertThat(dsl.fetchCount(DSL.table("account_gameplay_delegation_response_envelopes"))) + .isZero(); + assertThat(dsl.fetchCount(DSL.table("account_gameplay_token_identity_fences"))).isZero(); + } + @Test void failureAfterOtpDeleteRollsBackCanonicalLoginAndOtpConsumption() throws Exception { TestContext context = newTestContext(); @@ -2364,6 +2522,14 @@ private static Map authorityTupleWithoutCutoff( return tuple; } + private static String readLoginIntent(DSLContext dsl, UUID requestId) { + return dsl.resultQuery( + "SELECT to_jsonb(issuance)::text FROM account_gameplay_delegation_issuance_operations " + + "issuance WHERE request_id = ?", + requestId) + .fetchOne(0, String.class); + } + private static RecordData readCandidate(DSLContext dsl, UUID requestId) { var row = Objects.requireNonNull( @@ -2663,7 +2829,16 @@ private RedisHarness( } else if (key.equals( AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + GameSessionAccountDelegationProfile.ISSUER)) { - authorityProjectionBytes[0] = arguments[0].clone(); + assertThat(arguments.length).isEqualTo(3); + assertThat(arguments[1]).containsExactly(authorityProjectionBytes[0]); + String mode = new String(arguments[0], StandardCharsets.US_ASCII); + if ("VERIFY".equals(mode)) { + assertThat(arguments[2]).isEmpty(); + return 0L; + } + assertThat(mode).isEqualTo("PRESENT"); + assertThat(arguments[2]).isNotEmpty(); + authorityProjectionBytes[0] = arguments[2].clone(); } else if (key.equals( AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { if (arguments.length == 3 && arguments[2].length > 0) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..3592f202df --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java @@ -0,0 +1,580 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountIssuerAuthoritySourceGrpcService; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical PostgreSQL proof for current issuer reads, exact retry fences and writer concurrency. + */ +class AccountIssuerSourceSnapshotReadPostgresIntegrationTest { + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String SCHEMA_PREFIX = "account_issuer_read"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configurePostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopOwnedContainer() { + POSTGRES.stop(); + } + + @Test + void readsOldestRetainedIssuerEventWithLaterHeadAndPreservesIssuerRows() { + TestContext context = newTestContext(); + var transaction = context.transaction(); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + initializeCanonicalIssuer(context); + + String oldestId = "oldest-issuer-change"; + transaction.executeWithoutResult( + status -> + context.sources().appendIssuerAuthorityChange(ISSUER, "SIGNER_COMPROMISE", oldestId)); + var original = + Objects.requireNonNull( + transaction.execute( + status -> context.sources().readCurrentCanonicalIssuerSource(ISSUER))); + var oldest = original.latestEvent().orElseThrow(); + assertThat(oldest.outboxSequence()).isEqualTo(1L); + assertThat(oldest.eventId()).isEqualTo(oldestId); + + String laterId = "later-issuer-change"; + transaction.executeWithoutResult( + status -> + context + .sources() + .appendIssuerAuthorityChange(ISSUER, "ISSUER_SECURITY_CHANGE", laterId)); + var head = + Objects.requireNonNull( + transaction.execute( + status -> context.sources().readCurrentCanonicalIssuerSource(ISSUER))); + var latest = head.latestEvent().orElseThrow(); + assertThat(latest.outboxSequence()).isEqualTo(2L); + assertThat(latest.eventId()).isEqualTo(laterId); + List before = context.issuerRowImages(); + + var readback = + Objects.requireNonNull( + transaction.execute( + status -> + context + .sources() + .readExactCanonicalIssuerEvent( + ISSUER, 1L, oldestId, oldest.eventDigest()))); + assertThat(readback.currentSnapshot()).isEqualTo(head); + assertThat(readback.selectedEvent().outboxSequence()).isEqualTo("1"); + assertThat(readback.selectedEvent().issuerAuthGeneration()).isEqualTo("2"); + assertThat(readback.selectedEvent().eventId()).isEqualTo(oldestId); + assertThat(readback.selectedEvent().eventDigest()).isEqualTo(oldest.eventDigest()); + assertThat(readback.selectedEvent().canonicalJsonUtf8()).isEqualTo(oldest.payload()); + + assertThatThrownBy( + () -> + transaction.execute( + status -> + context + .sources() + .readExactCanonicalIssuerEvent( + ISSUER, 1L, laterId, oldest.eventDigest()))) + .isInstanceOf(SourceEvidenceUnavailableException.class); + assertThatThrownBy( + () -> + transaction.execute( + status -> + context + .sources() + .readExactCanonicalIssuerEvent( + ISSUER, 1L, oldestId, latest.eventDigest()))) + .isInstanceOf(SourceEvidenceUnavailableException.class); + for (long unavailableSequence : new long[] {0L, 3L}) { + assertThatThrownBy( + () -> + transaction.execute( + status -> + context + .sources() + .readExactCanonicalIssuerEvent( + ISSUER, unavailableSequence, oldestId, oldest.eventDigest()))) + .isInstanceOf(SourceEvidenceUnavailableException.class); + } + assertThat(context.issuerRowImages()).isEqualTo(before); + } + + @Test + void genuineEnrollmentAdvancedEventAndWholeSnapshotRetryAreReadWithoutMutation() + throws Exception { + TestContext context = newTestContext(); + initializeCanonicalIssuer(context); + UUID operation = UUID.randomUUID(); + var baseline = withPeer(() -> context.owner().read(request(operation))); + + assertThat(baseline.evidence().issuerAuthGeneration()).isEqualTo("1"); + assertThat(baseline.evidence().sourceVersion()).isEqualTo("1"); + assertThat(baseline.evidence().lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(baseline.evidence().sourceEvent()).isEmpty(); + assertThat(baseline.evidence().callerWorkload()).isEqualTo(CALLER); + assertThat(context.sourceHead()).containsEntry("current_generation", 1L); + + var exactInitialRetry = + withPeer(() -> context.owner().read(request(operation, Optional.of(baseline.evidence())))); + assertThat(exactInitialRetry.evidence()).isEqualTo(baseline.evidence()); + + String mutationRequestId = "historical-issuer-change-" + UUID.randomUUID(); + context + .transaction() + .executeWithoutResult( + status -> + context + .sources() + .appendIssuerAuthorityChange(ISSUER, "SIGNER_COMPROMISE", mutationRequestId)); + + Map beforeStaleRetry = context.sourceHead(); + var advanced = withPeer(() -> context.owner().read(request(UUID.randomUUID()))); + assertThat(advanced.evidence().issuerAuthGeneration()).isEqualTo("2"); + assertThat(advanced.evidence().sourceVersion()).isEqualTo("2"); + assertThat(advanced.evidence().lastCommittedOutboxSequence()).isEqualTo("1"); + assertThat(advanced.evidence().sourceEvent()).isPresent(); + var event = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify( + advanced.evidence().sourceEvent().orElseThrow()); + assertThat(event.eventId()).isEqualTo(mutationRequestId); + assertThat(event.requestId()).isEqualTo(mutationRequestId); + assertThat(event.eventId()) + .isNotEqualTo(advanced.evidence().reconciliationOperationId().toString()); + assertThat(event.issuerId()).isEqualTo(ISSUER); + assertThat(event.outboxStreamKey()).isEqualTo(advanced.evidence().outboxStreamKey()); + assertThat(event.outboxSequence()).isEqualTo(advanced.evidence().lastCommittedOutboxSequence()); + assertThat(event.issuerAuthGeneration()).isEqualTo(advanced.evidence().issuerAuthGeneration()); + assertThat(event.sourceVersion()).isEqualTo(advanced.evidence().sourceVersion()); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + withPeer( + () -> context.owner().read(request(operation, Optional.of(baseline.evidence()))))); + assertThat(context.sourceHead()).isEqualTo(beforeStaleRetry); + + var exactAdvancedRetry = + withPeer( + () -> + context + .owner() + .read( + request( + advanced.evidence().reconciliationOperationId(), + Optional.of(advanced.evidence())))); + assertThat(exactAdvancedRetry.evidence()).isEqualTo(advanced.evidence()); + assertThat(context.sourceHead()).isEqualTo(beforeStaleRetry); + } + + @Test + void missingAndUnsupportedIssuerReadsDenyWithoutEnrollmentOrOutboxMutation() throws Exception { + TestContext context = newTestContext(); + Map before = context.allIssuerRows(); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> withPeer(() -> context.owner().read(request(UUID.randomUUID())))); + + // In-process adapter proof with a synthetic same-namespace peer; this does not exercise live + // mTLS. + var unsupportedObserver = new RecordingObserver(); + var adapter = new AccountIssuerAuthoritySourceGrpcService(context.owner()); + withPeer( + () -> { + adapter.readCurrentIssuerAuthoritySource( + request(UUID.randomUUID(), "unsupported-issuer", Optional.empty()), + unsupportedObserver); + return null; + }); + + assertThat(unsupportedObserver.error.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(unsupportedObserver.error.getDescription()) + .isEqualTo("Malformed Account issuer source request"); + assertThat(unsupportedObserver.observedValue).isFalse(); + assertThat(unsupportedObserver.completed).isFalse(); + + assertThat(context.allIssuerRows()).isEqualTo(before); + assertThat(context.allIssuerRows()).containsEntry("generation_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("source_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("stream_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("event_rows", 0L); + } + + @Test + void serializableSnapshotWaitsForIssuerAdvanceAndExactRetryCannotSilentlyRefresh() + throws Exception { + TestContext context = newTestContext(); + initializeCanonicalIssuer(context); + UUID operation = UUID.randomUUID(); + var original = withPeer(() -> context.owner().read(request(operation))); + + CountDownLatch writerLocked = new CountDownLatch(1); + CountDownLatch writerAppended = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + CountDownLatch readerStarted = new CountDownLatch(1); + var writerPid = new java.util.concurrent.CompletableFuture(); + var readerPid = new java.util.concurrent.CompletableFuture(); + ExecutorService executor = Executors.newFixedThreadPool(2); + String mutationRequestId = "concurrent-issuer-change-" + UUID.randomUUID(); + Future writer = + executor.submit( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + var writerBackendPidRow = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid()"), + "Writer backend PID query returned no row"); + writerPid.complete( + Objects.requireNonNull( + writerBackendPidRow.get(0, Integer.class), + "Writer backend PID query returned NULL")); + var locked = + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ? FOR UPDATE", + ISSUER); + assertThat(locked).isNotNull(); + writerLocked.countDown(); + context + .sources() + .appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", mutationRequestId); + writerAppended.countDown(); + await(releaseWriter, "Issuer writer was not released to commit"); + })); + Future reader = + executor.submit( + () -> { + await(writerAppended, "Issuer writer did not append the source event"); + readerStarted.countDown(); + context.sources().captureNextReadBackendPid(readerPid); + return withPeer( + () -> context.owner().read(request(operation, Optional.of(original.evidence())))); + }); + + try { + assertThat(writerLocked.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(writerAppended.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(readerStarted.await(30, TimeUnit.SECONDS)).isTrue(); + int exactWriterPid = writerPid.get(10, TimeUnit.SECONDS); + int exactReaderPid = readerPid.get(10, TimeUnit.SECONDS); + assertThat(exactReaderPid).isNotEqualTo(exactWriterPid); + awaitBlockedReader(context.dsl(), exactReaderPid, exactWriterPid); + releaseWriter.countDown(); + writer.get(30, TimeUnit.SECONDS); + + try { + reader.get(30, TimeUnit.SECONDS); + throw new AssertionError( + "The exact old source snapshot must conflict after issuer advance"); + } catch (ExecutionException conflicted) { + Status.Code code = Status.fromThrowable(conflicted.getCause()).getCode(); + assertThat(code).isIn(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE); + } + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + withPeer( + () -> + context.owner().read(request(operation, Optional.of(original.evidence()))))); + + var current = withPeer(() -> context.owner().read(request(UUID.randomUUID()))).evidence(); + assertThat(current.issuerAuthGeneration()).isEqualTo("2"); + assertThat(current.sourceVersion()).isEqualTo("2"); + assertThat(current.lastCommittedOutboxSequence()).isEqualTo("1"); + var event = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify(current.sourceEvent().orElseThrow()); + assertThat(event.eventId()).isEqualTo(mutationRequestId); + assertThat(event.requestId()).isEqualTo(mutationRequestId); + assertThat(event.issuerAuthGeneration()).isEqualTo(current.issuerAuthGeneration()); + assertThat(event.sourceVersion()).isEqualTo(current.sourceVersion()); + assertThat(event.outboxSequence()).isEqualTo(current.lastCommittedOutboxSequence()); + assertThat(context.sourceHead()).containsEntry("current_generation", 2L); + assertThat(context.sourceHead()).containsEntry("current_source_version", 2L); + assertThat(context.sourceHead()).containsEntry("last_outbox_sequence", 1L); + } finally { + releaseWriter.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static void initializeCanonicalIssuer(TestContext context) { + context + .transaction() + .executeWithoutResult(status -> context.sources().initializeIssuerIfAbsent(ISSUER)); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactionManager = new DataSourceTransactionManager(dataSource); + var transaction = new TransactionTemplate(transactionManager); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new BackendPidCapturingSourceRepository(dsl, generations, outbox); + var owner = new AccountIssuerSourceSnapshotReadOwner(sources, transactionManager, NAMESPACE); + return new TestContext(dsl, transaction, sources, owner); + } + + private static void awaitBlockedReader(DSLContext dsl, int readerPid, int writerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (System.nanoTime() < deadline) { + var blockedReader = + dsl.fetchOne( + "SELECT pid FROM pg_stat_activity " + + "WHERE pid = ? AND pid <> pg_backend_pid() " + + "AND datname = current_database() AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)) LIMIT 1", + readerPid, + writerPid); + if (blockedReader != null) return; + Thread.sleep(25L); + } + throw new AssertionError( + "The owned issuer source reader did not wait for the exact concurrent writer"); + } + + private static void await(CountDownLatch latch, String failureMessage) { + try { + if (!latch.await(30, TimeUnit.SECONDS)) throw new IllegalStateException(failureMessage); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(failureMessage, interrupted); + } + } + + private static ReadCurrentIssuerAuthoritySourceRequest request(UUID operation) { + return request(operation, ISSUER, Optional.empty()); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, Optional expected) { + return request(operation, ISSUER, expected); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, String issuer, Optional expected) { + if (!ISSUER.equals(issuer)) { + return ReadCurrentIssuerAuthoritySourceRequest.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(NAMESPACE) + .setReconciliationOperationId(operation.toString()) + .setIssuerId(issuer) + .build(); + } + var typed = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, issuer, expected); + return AccountIssuerSourceSnapshotGrpcCodec.toRequest(typed, NAMESPACE, CALLER); + } + + private static T withPeer(java.util.concurrent.Callable call) throws Exception { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(CALLER).orElseThrow(); + return Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).call(call); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static final class RecordingObserver + implements StreamObserver { + private Status error; + private boolean observedValue; + private boolean completed; + + @Override + public void onNext(AccountIssuerAuthoritySourceSnapshot ignored) { + observedValue = true; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + BackendPidCapturingSourceRepository sources, + AccountIssuerSourceSnapshotReadOwner owner) { + private List issuerRowImages() { + return dsl.fetch( + "SELECT 'generation:' || to_jsonb(r)::text || ':' || r.xmin::text " + + "FROM account_authority_generations r " + + "UNION ALL SELECT 'source:' || to_jsonb(r)::text || ':' || r.xmin::text " + + "FROM account_authority_source_records r " + + "UNION ALL SELECT 'stream:' || to_jsonb(r)::text || ':' || r.xmin::text " + + "FROM account_authority_outbox_streams r " + + "UNION ALL SELECT 'event:' || to_jsonb(r)::text || ':' || r.xmin::text " + + "FROM account_authority_outbox_events r ORDER BY 1") + .getValues(0, String.class); + } + + private Map sourceHead() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT g.generation AS authority_generation, " + + "g.source_version AS authority_source_version, " + + "s.current_generation, s.current_source_version, s.last_outbox_sequence, " + + "stream.last_sequence AS stream_last_sequence, " + + "(SELECT count(*) FROM account_authority_outbox_events event " + + "WHERE event.outbox_stream_key = stream.outbox_stream_key) AS retained_events " + + "FROM account_authority_generations g " + + "JOIN account_authority_source_records s " + + "ON s.outbox_stream_key = 'account:auth-authority:v1:issuer/' || g.issuer_id " + + "JOIN account_authority_outbox_streams stream " + + "ON stream.outbox_stream_key = s.outbox_stream_key " + + "WHERE g.scope_kind = 'ISSUER' AND g.issuer_id = ?", + ISSUER), + "Issuer source head query returned no row") + .intoMap(); + } + + private Map allIssuerRows() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT " + + "(SELECT count(*) FROM account_authority_generations WHERE scope_kind = 'ISSUER') AS generation_rows, " + + "(SELECT count(*) FROM account_authority_source_records WHERE scope_kind = 'ISSUER') AS source_rows, " + + "(SELECT count(*) FROM account_authority_outbox_streams WHERE outbox_stream_key LIKE 'account:auth-authority:v1:issuer/%') AS stream_rows, " + + "(SELECT count(*) FROM account_authority_outbox_events WHERE outbox_stream_key LIKE 'account:auth-authority:v1:issuer/%') AS event_rows"), + "Issuer source row-count query returned no row") + .intoMap(); + } + } + + /** Captures only the next owner's real PostgreSQL backend before delegating the actual read. */ + private static final class BackendPidCapturingSourceRepository + extends AccountAuthoritySourceEvidenceRepository { + private final DSLContext dsl; + private final AtomicReference> nextReadPid = + new AtomicReference<>(); + + private BackendPidCapturingSourceRepository( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + super(dsl, generations, outbox); + this.dsl = dsl; + } + + private void captureNextReadBackendPid( + java.util.concurrent.CompletableFuture capturedPid) { + if (!nextReadPid.compareAndSet(null, capturedPid)) { + throw new IllegalStateException("A PostgreSQL owner-read PID capture is already armed"); + } + } + + @Override + public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exactIssuerId) { + var capture = nextReadPid.getAndSet(null); + if (capture != null) { + try { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_SERIALIZABLE) + .equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "The captured Account owner read must use its writable SERIALIZABLE transaction"); + } + var readerBackendPidRow = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid()"), + "Reader backend PID query returned no row"); + int backendPid = + Objects.requireNonNull( + readerBackendPidRow.get(0, Integer.class), + "Reader backend PID query returned NULL"); + capture.complete(backendPid); + } catch (RuntimeException failure) { + capture.completeExceptionally(failure); + throw failure; + } + } + return super.readCurrentCanonicalIssuerSource(exactIssuerId); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLeaveConsumerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLeaveConsumerPostgresIntegrationTest.java new file mode 100644 index 0000000000..5641be85d2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLeaveConsumerPostgresIntegrationTest.java @@ -0,0 +1,466 @@ +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.spy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.TransactionDefinition; + +/** + * Physical consumer SQL regression after a genuine canonical LEAVE and restore. + * Tenant/creator/billing setup and the caller/scope are controlled; no authenticated public caller, + * real Stripe, World hold, protected admission transport, custody or runtime activation is proved. + */ +class AccountLeaveConsumerPostgresIntegrationTest { + private static final String PREFIX = "leave_consumer_"; + private static final String CALLER = "controlled-paid-join-caller"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @AfterEach + void dropOwnedSchemas() { + var jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalStateException("Refusing unowned schema cleanup"); + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void paidCheckpointUsesCompositeFenceAfterLeaveRestore() { + Context c = context(false); + c.commit(c.observed); + var before = c.currentSources(); + var securityBefore = c.securityRows(); + c.leaveAndRestore(); + var after = c.currentSources(); + assertThat(after.issuanceFence().value()).isEqualTo(before.issuanceFence().value() + 1L); + assertThat(after.account().generation()).isEqualTo(before.account().generation()); + assertThat(c.securityRows()).isEqualTo(securityBefore); + assertThat( + c.hosting + .dsl() + .fetchSingle( + "SELECT current_issuance_fence FROM account_authority_source_records WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + c.scope.accountId()) + .get(0, Long.class)) + .isEqualTo(1L); + + long previousSequence = + c.in(status -> c.outbox.readCheckpoint(c.stream()).orElseThrow().outboxSequence()); + long version = + c.hosting + .dsl() + .fetchSingle( + "SELECT row_version FROM subscription WHERE subscription_id = ?", + c.hosting.creation().subscriptionId()) + .get(0, Long.class); + c.hosting.clock().advance(Duration.ofSeconds(2)); + assertThat( + c.hosting + .service() + .reconcile( + UUID.randomUUID(), + c.hosting.creation().requestId(), + version, + c.hosting.providerId(), + null) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + var freshFence = + c.in(status -> c.hosting.lifecycleRepository().prepareCurrentRead(c.scope.tenantId())); + var freshObserved = c.hosting.observer().observe(freshFence.binding()); + var snapshot = + c.in( + status -> + c.snapshots.requalifyPaidAcquisition( + c.scope.accountId(), + c.scope.tenantId(), + c.hosting.lifecycleRepository().readCurrent(freshFence, freshObserved))); + assertThat(snapshot.issuanceFence()).isEqualTo("2"); + var retained = + c.in(status -> c.outbox.findEvent(c.stream(), previousSequence + 1L).orElseThrow()); + var event = + MembershipAuthorityEventV1Codec.verify( + new String(retained.payload(), StandardCharsets.UTF_8)); + assertThat(event.eventType()).isEqualTo("MEMBERSHIP_AUTHORITY_CHECKPOINT"); + assertThat(event.issuanceFence()).isEqualTo("2"); + assertThat(event.membershipVersion()).isEqualTo(snapshot.membershipVersion()); + assertThat(event.membershipAuthorityGeneration()) + .isEqualTo(snapshot.membershipAuthorityGeneration()); + assertThat(c.securityRows()).isEqualTo(securityBefore); + var replay = + c.in( + status -> + c.snapshots.requalifyPaidAcquisition( + c.scope.accountId(), + c.scope.tenantId(), + c.hosting.lifecycleRepository().readCurrent(freshFence, freshObserved))); + assertThat(replay).isEqualTo(snapshot); + Long replaySequence = + c.in(status -> c.outbox.readCheckpoint(c.stream()).orElseThrow().outboxSequence()); + assertThat(replaySequence).isEqualTo(previousSequence + 1L); + } + + @Test + void delegationGuardAcceptsCurrentCompositeFenceAndRejectsStaleFenceAfterLeaveRestore() { + Context c = context(false); + c.commit(c.observed); + var before = c.currentSources(); + var securityBefore = c.securityRows(); + c.leaveAndRestore(); + var after = c.currentSources(); + assertThat(after.issuanceFence().value()).isEqualTo(before.issuanceFence().value() + 1L); + assertThat(after.account().generation()).isEqualTo(before.account().generation()); + assertThat(c.securityRows()).isEqualTo(securityBefore); + assertThat( + c.hosting + .dsl() + .fetchSingle( + "SELECT current_issuance_fence FROM account_authority_source_records WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + c.scope.accountId()) + .get(0, Long.class)) + .isEqualTo(1L); + + // Actual persisted pending intent invokes the current gameplay authority SQL trigger. + var issuance = + new AccountGameplayDelegationIssuanceRepository( + c.hosting.dsl(), c.sources, c.hosting.clock()); + var intent = c.intent(after); + c.hosting.transaction().executeWithoutResult(status -> issuance.beginPending(intent)); + assertThat( + c.hosting + .dsl() + .fetchSingle( + "SELECT issuance_fence FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + intent.requestId()) + .get(0, Long.class)) + .isEqualTo(2L); + assertThatThrownBy( + () -> + c.hosting + .transaction() + .executeWithoutResult(status -> issuance.beginPending(c.intent(before)))) + .isInstanceOf(AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); + + var pendingBefore = + c.hosting + .dsl() + .fetchSingle( + "SELECT row_to_json(p)::text AS image, xmin::text AS row_xmin FROM account_gameplay_delegation_issuance_operations p WHERE request_id = ?", + intent.requestId()) + .intoMap(); + assertThatThrownBy( + () -> + c.hosting + .transaction() + .executeWithoutResult( + status -> + c.hosting + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations SET issuance_fence = 1, issuance_fence_source_version = 1 WHERE request_id = ?", + intent.requestId()))) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("Account gameplay delegation authority snapshot is stale or missing"); + assertThat( + c.hosting + .dsl() + .fetchSingle( + "SELECT row_to_json(p)::text AS image, xmin::text AS row_xmin FROM account_gameplay_delegation_issuance_operations p WHERE request_id = ?", + intent.requestId()) + .intoMap()) + .isEqualTo(pendingBefore); + } + + private Context context(boolean wrongPolicy) { + String schema = PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var source = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Context(CanonicalHostingSubscriptionTestFixture.create(source), wrongPolicy); + } + + private static final class Context { + private final CanonicalHostingSubscriptionTestFixture.Fixture hosting; + private final AccountJoinOperationRepository operations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountCanonicalFirstJoinTerminalCoordinator coordinator; + private final CanonicalJoinScopeV2 scope; + private final String requestId = UUID.randomUUID().toString(); + private final ReadFence fence; + private final StripeHostingSubscriptionObserver.Result observed; + private final AccountAuthoritySourceEvidenceRepository sources; + private final AccountCanonicalRuntimeMembershipSnapshotRepository snapshots; + private final net.firedevops.firemud.accountservice.service + .AccountCanonicalLeaveMembershipCoordinator + leave; + + private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean wrongPolicy) { + this.hosting = hosting; + var committed = hosting.completeFirstInvoice(); + assertThat(committed.outcome()) + .isEqualTo( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var dsl = hosting.dsl(); + var accounts = new AccountRepository(dsl); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + pairs = new AccountMembershipPairAuthorityRepository(dsl); + var members = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(dsl, outbox, billing, fresh, generations); + demos = + spy( + new AccountDemoTenantEntitlementRepository( + dsl, fresh, generations, billing, tenantEvents)); + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), "prod"), + fresh); + operations = new AccountJoinOperationRepository(dsl, scopes); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + members, + roles, + generations, + outbox, + sources, + tenantEvents, + demos); + coordinator = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + members, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + producer); + leave = + new net.firedevops.firemud.accountservice.service + .AccountCanonicalLeaveMembershipCoordinator( + accounts, + operations, + new AccountLeaveOperationRepository(dsl), + members, + sources, + producer, + new AccountAuditOutboxRepository(dsl)); + snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, generations, sources, tenantEvents, fresh, members, pairs, roles, outbox); + Account input = new Account(); + input.setUsername("paid-player-" + UUID.randomUUID()); + input.setEmail("paid-player-" + UUID.randomUUID() + "@example.test"); + input.setPasswordHash("controlled-hash"); + // Player role belongs to the canonical tenant membership, not global Account authority. + Account player = Objects.requireNonNull(in(status -> accounts.save(input))); + var now = hosting.clock().instant(); + scope = + new CanonicalJoinScopeV2( + "controlled-paid-scope-" + UUID.randomUUID(), + player.getAccountUuid(), + hosting.tenantId(), + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + now.toString(), + now.plusSeconds(120).toString()); + hosting + .transaction() + .executeWithoutResult( + status -> { + var source = fresh.read(hosting.tenantId()).orElseThrow(); + sources.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + player.getAccountUuid(), hosting.tenantId())); + scopes.insertCanonical( + player.getId(), + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, CALLER); + }); + fence = + Objects.requireNonNull( + in(status -> hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); + observed = hosting.observer().observe(fence.binding()); + hosting + .transaction() + .executeWithoutResult( + status -> { + var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + CALLER, + receipt.allowPublicJoin(), + receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); + }); + } + + private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( + StripeHostingSubscriptionObserver.Result result) { + return Objects.requireNonNull( + in( + status -> + coordinator.commitPaidCanonicalFirstJoin( + scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); + } + + private AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot currentSources() { + return in( + status -> + sources.readCurrentIssuerAccountSources( + "firemud-account-service", scope.accountId())); + } + + private List> securityRows() { + return hosting + .dsl() + .fetch( + "SELECT row_to_json(s)::text AS row_image, xmin::text AS row_xmin FROM account_authority_source_records s WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + scope.accountId()) + .intoMaps(); + } + + private void leaveAndRestore() { + var binding = + new net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding( + UUID.randomUUID().toString(), scope.accountId(), scope.tenantId(), CALLER); + var result = in(status -> leave.leave(binding)); + assertThat(result.terminal().outcome()).isEqualTo("LEFT"); + String next = UUID.randomUUID().toString(); + hosting + .transaction() + .executeWithoutResult( + status -> { + operations.lockAccount( + hosting + .dsl() + .fetchSingle( + "SELECT id FROM accounts WHERE account_uuid = ?", scope.accountId()) + .get(0, Long.class)); + operations.insertCanonicalIntent(next, scope, CALLER); + var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); + operations.bindCanonicalPolicyEvidence( + next, scope, CALLER, receipt.allowPublicJoin(), receipt.entitlementVersion()); + }); + var restored = + in( + status -> + coordinator.commitCanonicalJoin( + scope, next, CALLER, hosting.lifecycleRepository(), fence, observed)); + assertThat(restored.membershipVersion()).isEqualTo(4L); + } + + private AccountGameplayDelegationIssuanceRepository.PendingIntent intent( + AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot source) { + long now = hosting.clock().instant().getEpochSecond(); + return new AccountGameplayDelegationIssuanceRepository.PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + new net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord + .AccountAuthoritySnapshot( + scope.accountId(), + source.issuer().generation(), + source.issuer().sourceVersion(), + source.account().generation(), + source.account().sourceVersion(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion(), + java.util.Optional.empty()), + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private T in(org.springframework.transaction.support.TransactionCallback action) { + return Objects.requireNonNull(hosting.transaction().execute(action)); + } + + private String stream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java new file mode 100644 index 0000000000..b2826c75e2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java @@ -0,0 +1,321 @@ +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.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.RestrictionState; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository.BirthSourceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical PostgreSQL proof for V81's historical Account restriction birth evidence. */ +class AccountPlatformRestrictionBirthPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void independentAccountAdvancePreservesBothHistoricalNonrestrictedResults() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + var birth = Objects.requireNonNull(readBirth(context, account.getAccountUuid())); + assertThat(birth.accountSourceNumericId()).isEqualTo(account.getId()); + assertThat(birth.birthAuthority()).isEqualTo(birth.currentAuthority()); + assertThat(birth.accountSecurityLock().restrictionState()) + .isEqualTo(RestrictionState.NONRESTRICTED); + assertThat(birth.platformAccessBan().restrictionState()) + .isEqualTo(RestrictionState.NONRESTRICTED); + assertThat(context.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + + context + .transaction() + .executeWithoutResult( + status -> { + account.setPasswordHash("changed-birth-test-hash"); + new AccountRepository(context.dsl()).save(account); + }); + var later = Objects.requireNonNull(readBirth(context, account.getAccountUuid())); + assertThat(later.accountId()).isEqualTo(birth.accountId()); + assertThat(later.accountSourceNumericId()).isEqualTo(birth.accountSourceNumericId()); + assertThat(later.accountInsertTransactionId()).isEqualTo(birth.accountInsertTransactionId()); + assertThat(later.birthAuthority()).isEqualTo(birth.birthAuthority()); + assertThat(later.accountSecurityLock()).isEqualTo(birth.accountSecurityLock()); + assertThat(later.platformAccessBan()).isEqualTo(birth.platformAccessBan()); + assertThat(later.currentAuthority().generation()).isEqualTo(2L); + assertThat(later.currentAuthority().sourceVersion()).isEqualTo(2L); + assertThat(later.currentAuthority().issuanceFence().value()).isEqualTo(2L); + assertThat(later.currentAuthority().issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(context.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + } + + @Test + void rollbackLeavesNoAccountAuthorityOrBirthEvidence() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult( + status -> { + new AccountRepository(context.dsl()).save(account); + assertThat( + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid())) + .isNotNull(); + status.setRollbackOnly(); + }); + + assertNoAccountOrBirthEvidence(context); + assertThatThrownBy(() -> readBirth(context, account.getAccountUuid())) + .isInstanceOf(BirthSourceUnavailableException.class); + } + + @Test + void postgresRefusesCommitWhenOneRequiredBirthOutboxRowIsMissing() { + Context context = context(null); + interceptBirthOutboxInsert(context, "RETURN NULL;"); + Account account = account(); + + assertPostgresRejection( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + // Keep the transaction open after Java rejects the zero-row outbox insert. + assertThatThrownBy(() -> new AccountRepository(context.dsl()).save(account)) + .isInstanceOf(BirthSourceUnavailableException.class); + assertThat(context.dsl().fetchCount(DSL.table("accounts"))).isEqualTo(1); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_platform_restriction_births"))) + .isEqualTo(2); + assertThat( + context + .dsl() + .fetchCount( + DSL.table("account_platform_restriction_projections"))) + .isEqualTo(2); + assertThat( + context + .dsl() + .fetchCount( + DSL.table("account_platform_restriction_birth_outbox"))) + .isEqualTo(1); + }), + "23514", + "account_restriction_birth_complete"); + + assertNoAccountOrBirthEvidence(context); + } + + @Test + void substitutesForExactBirthResultOrDigestRollBackTheSave() { + Context context = context(null); + for (String substitution : + new String[] { + "NEW.result_id := gen_random_uuid();", "NEW.payload_digest := repeat('0', 64);" + }) { + interceptBirthOutboxInsert(context, substitution); + assertPostgresRejection( + () -> + context + .transaction() + .executeWithoutResult( + status -> new AccountRepository(context.dsl()).save(account())), + "23503", + "account_restriction_birth_outbox_exact_result"); + assertNoAccountOrBirthEvidence(context); + } + } + + @Test + void committedBirthResultAndOutboxCannotBeRewritten() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + var before = Objects.requireNonNull(readBirth(context, account.getAccountUuid())); + + for (String mutation : + new String[] { + "UPDATE account_platform_restriction_births SET payload_digest = repeat('0', 64)", + "UPDATE account_platform_restriction_birth_outbox SET result_id = gen_random_uuid()" + }) { + assertPostgresRejection( + () -> + context + .dsl() + .execute( + mutation + " WHERE account_uuid = ? AND category = 'account_security_lock'", + account.getAccountUuid()), + "23514", + "account_restriction_birth_immutable"); + } + assertThat(readBirth(context, account.getAccountUuid())).isEqualTo(before); + } + + @Test + void v80RetainedDatabaseAccountStaysUnenrolledAfterMigrationAndReadback() { + Context context = context("80"); + Account retained = account(); + UUID retainedUuid = + Objects.requireNonNull( + context + .dsl() + .resultQuery( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, 'player') RETURNING account_uuid", + retained.getUsername(), + retained.getEmail(), + retained.getPasswordHash()) + .fetchOne(0, UUID.class)); + migrate(context, null); + + assertThatThrownBy(() -> readBirth(context, retainedUuid)) + .isInstanceOf(BirthSourceUnavailableException.class); + assertThat(new AccountRepository(context.dsl()).findByEmail(retained.getEmail())) + .hasValueSatisfying( + account -> assertThat(account.getAccountUuid()).isEqualTo(retainedUuid)); + assertNoBirthEvidence(context); + } + + private static AccountPlatformRestrictionBirthSource readBirth(Context context, UUID accountId) { + return context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(accountId)); + } + + private static void assertNoAccountOrBirthEvidence(Context context) { + for (String table : + new String[] { + "accounts", + "account_global_role_sources", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events" + }) { + assertThat(context.dsl().fetchCount(DSL.table(table))).as(table).isZero(); + } + assertNoBirthEvidence(context); + } + + private static void assertNoBirthEvidence(Context context) { + for (String table : + new String[] { + "account_platform_restriction_births", + "account_platform_restriction_projections", + "account_platform_restriction_birth_outbox" + }) { + assertThat(context.dsl().fetchCount(DSL.table(table))).as(table).isZero(); + } + } + + private static void assertPostgresRejection( + ThrowingCallable write, String sqlState, String constraint) { + assertThatThrownBy(write) + .rootCause() + .isInstanceOfSatisfying( + PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo(sqlState); + assertThat(Objects.requireNonNull(failure.getServerErrorMessage()).getConstraint()) + .isEqualTo(constraint); + }); + } + + private static void interceptBirthOutboxInsert(Context context, String beforeReturn) { + context + .dsl() + .execute( + "CREATE OR REPLACE FUNCTION intercept_birth_outbox_insert() " + + "RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " + + "IF NEW.category = 'platform_access_ban' THEN " + + beforeReturn + + " END IF; RETURN NEW; END; $$"); + context + .dsl() + .execute( + "CREATE OR REPLACE TRIGGER intercept_birth_outbox_insert BEFORE INSERT " + + "ON account_platform_restriction_birth_outbox " + + "FOR EACH ROW EXECUTE FUNCTION intercept_birth_outbox_insert()"); + } + + private static Account account() { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername(suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("birth-test-hash"); + return account; + } + + private static Context context(String target) { + String schema = "restriction_birth_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Context context = + new Context( + schema, + dataSource, + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + migrate(context, target); + return context; + } + + private static void migrate(Context context, String target) { + var configuration = + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", context.schema())); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private record Context( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index a8a0ef234f..2d53d4ef05 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -637,7 +637,7 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() } @Test - void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { + void privateRealmGrantStorageRetainsMonotonicCurrentnessWhileLifecycleMutationsAreUnavailable() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); long accountId = Objects.requireNonNull( @@ -715,8 +715,49 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { .orElseThrow(); UUID originalGeneration = original.getGrantAuthorityGeneration(); assertThat(grant.getGrantAuthorityGeneration()).isEqualTo(originalGeneration); + String beforeDeniedMutation = + transactionAwareDsl + .fetchSingle( + "SELECT row_to_json(g)::text FROM account_realm_access_grant g WHERE id = ?", + original.getId()) + .get(0, String.class); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> + accountService.revokeRealmAccess(accountId, 7654323L, "world", "private"))) + .isInstanceOf( + net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class) + .hasMessage("Lifecycle-qualified realm-grant mutations are unavailable"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + accountService.grantRealmAccess( + new RealmAccessGrantRequest( + accountId, + 7654323L, + "world", + "private", + "test", + "regrant", + "req-regrant-1")))) + .isInstanceOf( + net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class) + .hasMessage("Lifecycle-qualified realm-grant mutations are unavailable"); + assertThat( + transactionAwareDsl + .fetchSingle( + "SELECT row_to_json(g)::text FROM account_realm_access_grant g WHERE id = ?", + original.getId()) + .get(0, String.class)) + .isEqualTo(beforeDeniedMutation); + + // Direct fixture storage proves retained currentness, not lifecycle mutation authority. transaction.executeWithoutResult( - status -> accountService.revokeRealmAccess(accountId, 7654323L, "world", "private")); + status -> + grants.revokeByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + accountId, 7654323L, "world", "private")); AccountRealmAccessGrant revoked = grants .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -729,18 +770,8 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { assertThat(revoked.getGrantAuthorityGeneration()).isNotEqualTo(originalGeneration); UUID revokedGeneration = revoked.getGrantAuthorityGeneration(); - var regrantResult = - transaction.execute( - status -> - accountService.grantRealmAccess( - new RealmAccessGrantRequest( - accountId, - 7654323L, - "world", - "private", - "test", - "regrant", - "req-regrant-1"))); + revoked.setGranted(true); + var regrantResult = transaction.execute(status -> grants.save(revoked)); AccountRealmAccessGrant regranted = grants .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -750,8 +781,8 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { assertThat(regranted.getGrantVersion()).isEqualTo(3L); assertThat(regranted.getGrantAuthorityGeneration()).isNotEqualTo(revokedGeneration); assertThat(regrantResult).isNotNull(); - assertThat(regrantResult.granted()).isTrue(); - assertThat(regrantResult.grantVersion()).isEqualTo(regranted.getGrantVersion()); + assertThat(regrantResult.isGranted()).isTrue(); + assertThat(regrantResult.getGrantVersion()).isEqualTo(regranted.getGrantVersion()); assertThat(regranted.getGrantAuthorityGeneration()).isNotEqualTo(originalGeneration); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index 529cca5037..0486d3e45f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -228,6 +228,66 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { assertThat(finalState.sourceVersion()).isEqualTo(3L); assertThat(finalState.issuanceFence().value()).isEqualTo(3L); + // Retrying an older completed logout must preserve the later owner's exact source state. + UUID laterLogoutRequestId = UUID.randomUUID(); + String laterTokenHash = sha256Hex("later presented logout token"); + assertThat( + logoutProducer.commit( + laterLogoutRequestId, + 1, + AccountLogoutRequestDigest.accountLogoutAll( + seed.account().getAccountUuid(), TOKEN_PROFILE, laterTokenHash), + TOKEN_PROFILE, + laterTokenHash, + persistedAccount, + finalState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + ScopeState laterState = readState(transaction, generations, seed.account().getAccountUuid()); + assertThat(laterState.generation()).isEqualTo(4L); + assertThat(laterState.sourceVersion()).isEqualTo(4L); + assertThat(laterState.issuanceFence().value()).isEqualTo(4L); + var laterEvidence = + transaction.execute( + status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), laterState)); + assertThat(laterEvidence).isNotNull(); + assertThat(laterEvidence.checkpoint().sequence()).isEqualTo(3L); + var retainedRows = + dsl.fetch( + "SELECT row_to_json(r)::text FROM account_logout_all_operation_receipts r ORDER BY request_id"); + var retainedEvents = + dsl.fetch( + "SELECT row_to_json(e)::text FROM account_authority_outbox_events e ORDER BY outbox_stream_key, outbox_sequence"); + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + logoutRequestDigest, + TOKEN_PROFILE, + syntheticPresentedTokenHash, + persistedAccount, + expectedLogoutState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(readState(transaction, generations, seed.account().getAccountUuid())) + .isEqualTo(laterState); + var replayedEvidence = + transaction.execute( + status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), laterState)); + var replayedReceipt = + transaction.execute( + status -> logoutOperations.findByRequestId(logoutRequestId).orElseThrow()); + assertThat(replayedEvidence).isEqualTo(laterEvidence); + assertThat(replayedReceipt).isEqualTo(logoutReceipt); + assertThat( + dsl.fetch( + "SELECT row_to_json(r)::text FROM account_logout_all_operation_receipts r ORDER BY request_id")) + .isEqualTo(retainedRows); + assertThat( + dsl.fetch( + "SELECT row_to_json(e)::text FROM account_authority_outbox_events e ORDER BY outbox_stream_key, outbox_sequence")) + .isEqualTo(retainedEvents); + assertDatabaseWriteRejected( () -> dsl.execute( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java index 64fbbd953a..25235beded 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -5,9 +5,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.SQLException; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -19,6 +21,9 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.*; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; @@ -38,6 +43,143 @@ class AccountTenantAuthoritySourceSelectionPostgresIntegrationTest { private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void mixedOriginalOwnersKeepTenantMutationAndExactRetryFenced() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context c = context(); + var f = c.fixture(); + var prior = c.provisionDemo(null, true); + var original = c.select().checkpoint(); + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-tenant", + 2, + "test-tenant", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test/base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + // Controlled source-storage capture only: this is not authenticated creator authorization. + var holder = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.TENANT, + f.tenantId().toString(), + Long.toString(original.tenantAuthorityGeneration()), + Long.toString(original.tenantAuthoritySourceVersion()), + original.outboxStreamKey(), + Long.toString(original.outboxSequence()), + original.payload()))); + var fences = new DraftAuthorizationFenceRepository(f.dsl()); + f.transaction() + .executeWithoutResult( + status -> { + fences.reserve(holder); + fences.claimCommitOrder(holder); + }); + // Owner terminal evidence is stipulated, not an authenticated publisher. + for (Owner owner : List.of(Owner.WORLD, Owner.GAME_DESIGN)) { + Outcome outcome = + owner == Owner.WORLD + ? worldOutcome + : worldOutcome == Outcome.COMMITTED + ? Outcome.DEFINITIVELY_ABORTED + : Outcome.COMMITTED; + var readback = + new OwnerReadback( + owner, + outcome, + holder.operationId(), + holder.commitId(), + holder.fenceId(), + holder.inputDigest(), + holder.canonicalBytes(), + new byte[] {(byte) owner.ordinal(), (byte) outcome.ordinal()}); + f.transaction() + .executeWithoutResult(status -> fences.recordOwnerReadback(holder, readback)); + } + var retained = tenantSnapshot(f); + UUID requestId = UUID.randomUUID(); + for (int attempt = 0; attempt < 2; attempt++) { + RuntimeException failure = + assertThrows(RuntimeException.class, () -> c.provisionDemo(prior, false, requestId)); + Throwable cause = failure; + while (cause != null && !(cause instanceof SQLException)) cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("55P03"); + assertThat(cause) + .hasMessageContaining( + "Required creator source is held until every original owner settles"); + assertThat(tenantSnapshot(f)).isEqualTo(retained); + } + assertThat( + f.dsl() + .fetchSingle( + "SELECT account_draft_authorization_is_settled(?)", holder.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat(c.select().matches(original)).isTrue(); + assertThat(f.transport().reads()).isZero(); + } + } + + private static Map>> tenantSnapshot( + CanonicalHostingSubscriptionTestFixture.Fixture f) { + Map>> rows = new java.util.LinkedHashMap<>(); + for (String table : + List.of( + "account_authority_generations", + "account_tenant_authority_source_records", + "account_authority_outbox_events", + "account_authority_outbox_streams", + "account_tenant_entitlement_outbox_events", + "account_tenant_entitlement_outbox_streams", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks")) { + rows.put( + table, + f.dsl() + .fetch( + "SELECT to_jsonb(t)::text AS evidence, xmin::text AS row_version FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()); + } + return rows; + } + @Test void retainedPendingSubscriptionWithoutCommittedTenantSourceIsUnavailable() { Context c = context(); @@ -298,6 +440,11 @@ private SourceSelection select() { private DemoTenantEntitlementSnapshot provisionDemo( DemoTenantEntitlementSnapshot prior, boolean publicJoin) { + return provisionDemo(prior, publicJoin, UUID.randomUUID()); + } + + private DemoTenantEntitlementSnapshot provisionDemo( + DemoTenantEntitlementSnapshot prior, boolean publicJoin, UUID requestId) { return Objects.requireNonNull( fixture .transaction() @@ -309,7 +456,7 @@ private DemoTenantEntitlementSnapshot provisionDemo( .orElseThrow(); return demos.provision( new DemoTenantEntitlementRequest( - UUID.randomUUID(), + requestId, fixture.tenantId(), source.creationRequestId(), source.requestDigest(), 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..5cc616d8f2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantRoleOperationRepositoryPostgresIntegrationTest.java @@ -0,0 +1,410 @@ +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 net.firedevops.firemud.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @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(); + } + + @Test + void transferJournalRequiresBothExactMembersAndDoesNotPersistAnIncompleteClaim() { + TestContext context = newTestContext(); + UUID actor = insertAccount(context.setupDsl()); + UUID target = insertAccount(context.setupDsl()); + Request request = + request( + UUID.randomUUID(), + actor, + UUID.randomUUID(), + target, + Action.TRANSFER_TENANT_ADMIN, + 4, + 7); + + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> context.repository().claim(request))) + .hasStackTraceContaining("Incomplete Account tenant-role operation cannot commit"); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().findForUpdate(request.requestId()))) + .isEmpty(); + + MemberResult actorMember = member(request, actor, 5, 2, 2, List.of("player"), true); + MemberResult targetMember = + member(request, target, 8, 1, 1, List.of("player", "tenantAdmin"), false); + AuditEvidence audit = audit(UUID.randomUUID(), "{\"transfer\":true}"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + assertThat(context.repository().claim(request).claimed()).isTrue(); + return context.repository().complete(request, audit, List.of(targetMember)); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("member result count"); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().findForUpdate(request.requestId()))) + .isEmpty(); + + OperationEvidence committed = + inTransaction( + context.transaction(), + () -> { + assertThat(context.repository().claim(request).claimed()).isTrue(); + return context + .repository() + .complete(request, audit, List.of(targetMember, actorMember)); + }); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.members()).hasSize(2); + for (MemberResult expected : List.of(actorMember, targetMember)) { + MemberResult actual = + committed.members().stream() + .filter(value -> value.accountUuid().equals(expected.accountUuid())) + .findFirst() + .orElseThrow(); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + assertThat(actual.eventPayload()).containsExactly(expected.eventPayload()); + } + OperationEvidence replay = + inTransaction( + context.transaction(), + () -> { + Claim claim = context.repository().claim(request); + assertThat(claim.claimed()).isFalse(); + return claim.replay().orElseThrow(); + }); + assertExactOperation(committed, replay); + } + + 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/integration/net/firedevops/firemud/accountservice/repository/ConnectTokenDurableReceiptPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ConnectTokenDurableReceiptPostgresIntegrationTest.java new file mode 100644 index 0000000000..ae28548017 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ConnectTokenDurableReceiptPostgresIntegrationTest.java @@ -0,0 +1,595 @@ +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.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier.Lookup; +import net.firedevops.firemud.accountservice.repository.ConnectTokenReceiptClassifier.State; +import net.firedevops.firemud.test.TestContainerImages; +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.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class ConnectTokenDurableReceiptPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void committedReceiptAndCiphertextAreImmutableAndCannotBeReminted() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "original", 60); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='COMMITTED', token_jti=?," + + "token_hash=?, replay_admission_fence=1, issuance_evidence=? WHERE operation_id=?", + UUID.randomUUID(), + digest('b'), + new byte[] {1, 2}, + id); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET request_digest=? WHERE operation_id=?", + digest('c'), + id)) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET token_jti=? WHERE operation_id=?", + UUID.randomUUID(), + id)) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_response_envelope SET encrypted_response=? WHERE operation_id=?", + new byte[] {9}, + id)) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .hasMessageContaining("held"); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_issuance_operation WHERE operation_id=?", id)) + .hasMessageContaining("safe-watermark"); + } + + @Test + void terminalOutcomeWithoutEnvelopeRollsBackAndAbortedEvidenceRemainsHeld() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "missing", 60); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED' WHERE operation_id=?", + id)) + .hasMessageContaining("durably recorded"); + assertThat( + db.fetchValue( + "SELECT status FROM connect_token_issuance_operation WHERE operation_id=?", id)) + .isEqualTo("PENDING"); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='ABORTED',failure_code='RECONCILIATION_REQUIRED' WHERE operation_id=?", + id); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .hasMessageContaining("held"); + } + + @Test + void expiredFailureEnvelopeCanBeRemovedOnlyAfterReconciliationAndNeverRecreated() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "failure", 1); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED' WHERE operation_id=?", + id); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .hasMessageContaining("held"); + db.execute("SELECT pg_sleep(1.1)"); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .hasMessageContaining("held"); + db.execute( + "UPDATE connect_token_issuance_operation SET reconciliation_blocked=FALSE,reconciliation_evidence=? WHERE operation_id=?", + new byte[] {3}, + id); + assertThat(db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .isEqualTo(1); + assertThat( + db.fetchValue( + "SELECT request_digest FROM connect_token_issuance_operation WHERE operation_id=?", + id)) + .isEqualTo(digest('a')); + assertThatThrownBy(() -> envelope(db, id)).hasMessageContaining("cannot be replaced"); + assertThatThrownBy( + () -> + db.execute( + "UPDATE connect_token_issuance_operation SET status='PENDING',terminal_at=NULL,failure_code=NULL WHERE operation_id=?", + id)) + .hasMessageContaining("immutable"); + } + + @Test + void concurrentClaimsSerializeOnExactIdentityAndRetainOneDigest() throws Exception { + DSLContext db = database(); + UUID account = account(db); + UUID tenant = UUID.randomUUID(); + CountDownLatch claimed = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture first = + CompletableFuture.runAsync( + () -> + db.transaction( + configuration -> { + insert( + DSL.using(configuration), + UUID.randomUUID(), + account, + tenant, + "same", + digest('a'), + 60); + claimed.countDown(); + try { + if (!release.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("test release timeout"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + })); + assertThat(claimed.await(10, TimeUnit.SECONDS)).isTrue(); + CompletableFuture second = + CompletableFuture.supplyAsync( + () -> insert(db, UUID.randomUUID(), account, tenant, "same", digest('b'), 60)); + try { + boolean blocked = false; + for (int i = 0; i < 100 && !blocked; i++) { + blocked = + Boolean.TRUE.equals( + Objects.requireNonNull( + db.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE wait_event_type='Lock' " + + "AND query LIKE 'INSERT INTO connect_token_issuance_operation%')")) + .get(0, Boolean.class)); + if (!blocked) Thread.sleep(20); + } + assertThat(blocked).as("the second claim actually waits on the first transaction").isTrue(); + release.countDown(); + first.get(15, TimeUnit.SECONDS); + assertThat(second.get(15, TimeUnit.SECONDS)).isZero(); + assertThat(db.fetchValue("SELECT count(*) FROM connect_token_issuance_operation")) + .isEqualTo(1L); + assertThat(db.fetchValue("SELECT request_digest FROM connect_token_issuance_operation")) + .isEqualTo(digest('a')); + } finally { + release.countDown(); + } + } + + @Test + void successfulEnvelopeExpiryPreservesReceiptAndRejectsRemint() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "success", 1); + db.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + envelope(tx, id); + tx.execute( + "UPDATE connect_token_issuance_operation SET status='COMMITTED',token_jti=?," + + "token_hash=?,replay_admission_fence=1,issuance_evidence=?,reconciliation_blocked=FALSE," + + "reconciliation_evidence=? WHERE operation_id=?", + UUID.randomUUID(), + digest('b'), + new byte[] {1}, + new byte[] {2}, + id); + }); + assertThatThrownBy( + () -> + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .hasMessageContaining("held"); + db.execute("SELECT pg_sleep(1.1)"); + assertThat(db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id)) + .isEqualTo(1); + assertThat( + db.fetchValue( + "SELECT status FROM connect_token_issuance_operation WHERE operation_id=?", id)) + .isEqualTo("COMMITTED"); + assertThatThrownBy(() -> envelope(db, id)).hasMessageContaining("cannot be replaced"); + } + + @Test + void missingResponseAtTransactionCommitRollsBackClaimAndOutcomeTogether() { + DSLContext db = database(); + UUID account = account(db); + UUID id = UUID.randomUUID(); + assertThatThrownBy( + () -> + db.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + insert(tx, id, account, UUID.randomUUID(), "rollback", digest('a'), 60); + tx.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED' WHERE operation_id=?", + id); + })) + .rootCause() + .hasMessageContaining("durably recorded"); + assertThat( + db.fetchValue( + "SELECT count(*) FROM connect_token_issuance_operation WHERE operation_id=?", id)) + .isEqualTo(0L); + } + + @Test + void classifierRequiresExplicitValidDigestAndOwnerTransaction() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "classification", 60); + Lookup lookup = lookup(db, id, digest('a')); + assertThatThrownBy(() -> new ConnectTokenReceiptClassifier(db).classify(lookup)) + .hasMessageContaining("existing Account transaction"); + assertThatThrownBy( + () -> new Lookup(lookup.accountId(), lookup.tenantId(), "scope", "request", 1, "bad")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Lookup( + lookup.accountId(), lookup.tenantId(), "scope", "request", 2, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Lookup(new UUID(0, 0), lookup.tenantId(), "scope", "request", 1, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void classifierPreservesPendingAndUnreconciledEvidenceAndPrioritizesDigestConflict() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "classification", 60); + Lookup lookup = lookup(db, id, digest('a')); + assertThat(classify(db, lookup)).isEqualTo(State.PENDING); + assertThat(classify(db, lookup(db, id, digest('b')))).isEqualTo(State.IDEMPOTENCY_CONFLICT); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED' WHERE operation_id=?", + id); + assertThat(classify(db, lookup)).isEqualTo(State.RECONCILIATION_REQUIRED); + assertThat(classify(db, lookup(db, id, digest('b')))).isEqualTo(State.IDEMPOTENCY_CONFLICT); + db.execute( + "UPDATE connect_token_issuance_operation SET reconciliation_blocked=FALSE,reconciliation_evidence=? WHERE operation_id=?", + new byte[] {1}, + id); + assertThat(classify(db, lookup)).isEqualTo(State.FAILURE_ENVELOPE_RETAINED); + assertThat( + db.fetchValue( + "SELECT failure_code FROM connect_token_issuance_operation WHERE operation_id=?", + id)) + .isEqualTo("JOIN_REQUIRED"); + } + + @Test + void classifierDoesNotConfuseRetainedFailureWithRemovedEnvelopeOrRemint() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "expired", 1); + Lookup lookup = lookup(db, id, digest('a')); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED'," + + "reconciliation_blocked=FALSE,reconciliation_evidence=? WHERE operation_id=?", + new byte[] {1}, + id); + db.execute("SELECT pg_sleep(1.1)"); + assertThat(classify(db, lookup)).isEqualTo(State.FAILURE_ENVELOPE_RETAINED); + db.execute("DELETE FROM connect_token_response_envelope WHERE operation_id=?", id); + assertThat(classify(db, lookup)).isEqualTo(State.RESPONSE_RECOVERY_EXPIRED); + assertThat(classify(db, lookup(db, id, digest('b')))).isEqualTo(State.IDEMPOTENCY_CONFLICT); + assertThat(db.fetchValue("SELECT count(*) FROM connect_token_response_envelope")).isEqualTo(0L); + assertThat(db.fetchValue("SELECT count(*) FROM connect_token_issuance_operation")) + .isEqualTo(1L); + } + + @Test + void classifierNeverAuthorizesSuccessfulReplayOrResumesAbortedAttempt() { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "success", 60); + envelope(db, id); + db.execute( + "UPDATE connect_token_issuance_operation SET status='COMMITTED',token_jti=?,token_hash=?," + + "replay_admission_fence=1,issuance_evidence=?,reconciliation_blocked=FALSE,reconciliation_evidence=?" + + " WHERE operation_id=?", + UUID.randomUUID(), + digest('b'), + new byte[] {1}, + new byte[] {2}, + id); + assertThat(classify(db, lookup(db, id, digest('a')))) + .isEqualTo(State.SUCCESS_REVALIDATION_REQUIRED); + UUID aborted = claim(db, UUID.randomUUID(), "aborted", 60); + db.execute( + "UPDATE connect_token_issuance_operation SET status='ABORTED',failure_code='UNKNOWN_COMMIT' WHERE operation_id=?", + aborted); + assertThat(classify(db, lookup(db, aborted, digest('a')))).isEqualTo(State.ABORTED); + } + + @Test + void missingOrRolledBackReceiptIsUncertainAndCreatesNothing() { + DSLContext db = database(); + UUID account = account(db); + UUID tenant = UUID.randomUUID(); + Lookup lookup = new Lookup(account, tenant, "scope", "missing", 1, digest('a')); + assertThat(classify(db, lookup)).isEqualTo(State.MISSING_UNCERTAIN); + assertThatThrownBy( + () -> + db.transaction( + configuration -> { + insert( + DSL.using(configuration), + UUID.randomUUID(), + account, + tenant, + "missing", + digest('a'), + 60); + throw new IllegalStateException("simulate rolled back owner transaction"); + })) + .hasMessageContaining("rolled back"); + assertThat(classify(db, lookup)).isEqualTo(State.MISSING_UNCERTAIN); + assertThat(db.fetchValue("SELECT count(*) FROM connect_token_issuance_operation")) + .isEqualTo(0L); + } + + @Test + void classifierWaitsForConcurrentTerminalCommitAndReadsItsEnvelope() throws Exception { + DSLContext db = database(); + UUID id = claim(db, UUID.randomUUID(), "concurrent-readback", 60); + Lookup lookup = lookup(db, id, digest('a')); + CountDownLatch updated = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture owner = + CompletableFuture.runAsync( + () -> + db.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + envelope(tx, id); + tx.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED'," + + "reconciliation_blocked=FALSE,reconciliation_evidence=? WHERE operation_id=?", + new byte[] {1}, + id); + updated.countDown(); + try { + if (!release.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("owner release timeout"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + })); + try { + assertThat(updated.await(10, TimeUnit.SECONDS)).isTrue(); + CompletableFuture reader = CompletableFuture.supplyAsync(() -> classify(db, lookup)); + boolean blocked = false; + for (int i = 0; i < 100 && !blocked; i++) { + blocked = + Boolean.TRUE.equals( + Objects.requireNonNull( + db.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE wait_event_type='Lock' " + + "AND query LIKE 'SELECT op.request_digest_version%')")) + .get(0, Boolean.class)); + if (!blocked) Thread.sleep(20); + } + assertThat(blocked).as("classification waits for owner transaction").isTrue(); + release.countDown(); + owner.get(15, TimeUnit.SECONDS); + assertThat(reader.get(15, TimeUnit.SECONDS)).isEqualTo(State.FAILURE_ENVELOPE_RETAINED); + } finally { + release.countDown(); + } + } + + @Test + void encodedExactFailureRetryIsReadOnlyAndDifferentIdentityCannotSeeIt() { + DSLContext db = database(); + UUID account = account(db); + UUID tenant = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + var original = + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint.lookup( + account, tenant, "scope", "stable-request"); + assertThat( + insert(db, operation, account, tenant, "stable-request", original.requestDigest(), 60)) + .isEqualTo(1); + envelope(db, operation); + db.execute( + "UPDATE connect_token_issuance_operation SET status='FAILED',failure_code='JOIN_REQUIRED'," + + "reconciliation_blocked=false,reconciliation_evidence=? WHERE operation_id=?", + new byte[] {1}, + operation); + var before = + db.fetchSingle("SELECT to_jsonb(op)::text FROM connect_token_issuance_operation op") + .get(0, String.class); + var envelopeBefore = + db.fetch( + "SELECT operation_id,encryption_key_id,encryption_version,encode(encrypted_response,'hex') AS response," + + "encode(authenticated_binding,'hex') AS binding FROM connect_token_response_envelope") + .intoMaps(); + // Controlled owner-state fixture only: not an authorized JOIN or membership issuance proof. + db.execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid,tenant_uuid,tenant_provenance_kind,tenant_source_operation_id," + + "tenant_provenance_digest,membership_exists,membership_version," + + "membership_authority_generation,last_event_sequence,last_transition_invalidated) " + + "VALUES (?,?,'FRESH_GAME_DESIGN',?,?,false,1,1,0,false)", + account, + tenant, + UUID.randomUUID(), + digest('a')); + assertThat(classify(db, original)).isEqualTo(State.FAILURE_ENVELOPE_RETAINED); + db.execute( + "UPDATE account_membership_pair_authority SET membership_exists=true,membership_version=2," + + "last_event_sequence=1,last_event_id='controlled-membership-created',last_event_digest=? " + + "WHERE account_uuid=? AND tenant_uuid=?", + digest('b'), + account, + tenant); + assertThat( + db.fetchSingle("SELECT membership_exists FROM account_membership_pair_authority") + .get(0, Boolean.class)) + .isTrue(); + var retry = + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint.lookup( + account, tenant, "scope", "stable-request"); + assertThat(classify(db, retry)).isEqualTo(State.FAILURE_ENVELOPE_RETAINED); + assertThat( + classify( + db, + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint + .lookup(account(db), tenant, "scope", "stable-request"))) + .isEqualTo(State.MISSING_UNCERTAIN); + assertThat( + classify( + db, + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint + .lookup(account, tenant, "scope", "new-request"))) + .isEqualTo(State.MISSING_UNCERTAIN); + assertThat( + classify( + db, + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint + .lookup(account, tenant, "changed-scope", "stable-request"))) + .isEqualTo(State.MISSING_UNCERTAIN); + assertThat(classify(db, new Lookup(account, tenant, "scope", "stable-request", 1, digest('f')))) + .isEqualTo(State.IDEMPOTENCY_CONFLICT); + assertThat( + db.fetchSingle("SELECT to_jsonb(op)::text FROM connect_token_issuance_operation op") + .get(0, String.class)) + .isEqualTo(before); + assertThat( + db.fetch( + "SELECT operation_id,encryption_key_id,encryption_version,encode(encrypted_response,'hex') AS response," + + "encode(authenticated_binding,'hex') AS binding FROM connect_token_response_envelope") + .intoMaps()) + .isEqualTo(envelopeBefore); + assertThat( + db.fetchSingle( + "SELECT count(*) FROM connect_token_issuance_operation WHERE token_jti IS NOT NULL") + .get(0, Long.class)) + .isZero(); + } + + private static State classify(DSLContext db, Lookup lookup) { + return db.transactionResult( + configuration -> + new ConnectTokenReceiptClassifier(DSL.using(configuration)).classify(lookup)); + } + + private static Lookup lookup(DSLContext db, UUID id, String digest) { + var row = + Objects.requireNonNull( + db.fetchOne( + "SELECT account_uuid,tenant_uuid,connect_scope_id,request_id FROM connect_token_issuance_operation WHERE operation_id=?", + id)); + return new Lookup( + row.get(0, UUID.class), + row.get(1, UUID.class), + row.get(2, String.class), + row.get(3, String.class), + 1, + digest); + } + + private static UUID claim(DSLContext db, UUID tenant, String request, int horizonSeconds) { + UUID id = UUID.randomUUID(); + assertThat(insert(db, id, account(db), tenant, request, digest('a'), horizonSeconds)) + .isEqualTo(1); + return id; + } + + private static int insert( + DSLContext db, + UUID id, + UUID account, + UUID tenant, + String request, + String digest, + int horizonSeconds) { + return db.execute( + "INSERT INTO connect_token_issuance_operation " + + "(operation_id,account_uuid,tenant_uuid,connect_scope_id,request_id,request_digest_version,request_digest,status," + + "response_recovery_expires_at,receipt_retain_until) VALUES (?,?,?,'scope',?,1,?,'PENDING'," + + "CURRENT_TIMESTAMP + (? * INTERVAL '1 second'),CURRENT_TIMESTAMP + INTERVAL '1 hour') " + + "ON CONFLICT (account_uuid,tenant_uuid,connect_scope_id,request_id) DO NOTHING", + id, + account, + tenant, + request, + digest, + horizonSeconds); + } + + private static void envelope(DSLContext db, UUID id) { + db.execute( + "INSERT INTO connect_token_response_envelope VALUES (?, 'test-key',1,?,?)", + id, + new byte[] {4, 5}, + new byte[] {6, 7}); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID account(DSLContext db) { + String value = UUID.randomUUID().toString(); + return Objects.requireNonNull( + db.fetchOne( + "INSERT INTO accounts (username,email,password_hash) VALUES (?,?,?) RETURNING account_uuid", + value, + value + "@example.test", + "test-hash")) + .get(0, UUID.class); + } + + private static DSLContext database() { + String schema = "connect_receipt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return DSL.using(source, SQLDialect.POSTGRES); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ProfilePresenceMembershipPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ProfilePresenceMembershipPostgresIntegrationTest.java new file mode 100644 index 0000000000..18accb3cc4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ProfilePresenceMembershipPostgresIntegrationTest.java @@ -0,0 +1,60 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import net.firedevops.firemud.accountservice.repository.ProfileRepository; +import org.jooq.SQLDialect; +import org.jooq.conf.Settings; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +/** Actual repository SQL against PostgreSQL; isolated projection tables, not migration proof. */ +class ProfilePresenceMembershipPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void policyBatchRequiresExactMembershipPairWithoutChangingRetainedProfiles() { + var data = POSTGRES.dataSource(); + var jdbc = new JdbcTemplate(data); + jdbc.execute( + "CREATE TABLE accounts (id bigint PRIMARY KEY, username text, email text, password_hash text, role text, email_verified boolean, login_auth_modes text)"); + jdbc.execute( + "CREATE TABLE profiles (id bigint PRIMARY KEY, account_id bigint, tenant_id bigint, display_name text, bio text, presence_visibility_policy text)"); + jdbc.execute("CREATE TABLE account_tenant_membership (account_id bigint, tenant_id bigint)"); + jdbc.execute( + "INSERT INTO accounts VALUES (1,'one','one@example.test','hash','USER',true,'PASSWORD'), (2,'two','two@example.test','hash','USER',true,'PASSWORD'), (3,'three','three@example.test','hash','USER',true,'PASSWORD')"); + jdbc.execute( + "INSERT INTO profiles VALUES (1,1,10,'one','','PUBLIC'), (2,2,10,'two','','PUBLIC'), (3,3,10,'three','','FRIENDS_ONLY'), (4,1,20,'other','','PUBLIC')"); + jdbc.execute("INSERT INTO account_tenant_membership VALUES (1,10), (2,20)"); + var repository = + new ProfileRepository( + DSL.using(data, SQLDialect.POSTGRES, new Settings().withRenderSchema(false))); + + assertThat(repository.findByTenantIdAndAccountIds(10L, List.of(1L, 2L, 3L))) + .extracting(profile -> profile.getAccount().getId()) + .containsExactly(1L); + assertThat(repository.findByTenantIdAndAccountIds(20L, List.of(1L))).isEmpty(); + assertThat(repository.findByTenantIdAndAccountIds(10L, List.of(2L, 3L))).isEmpty(); + assertThat(repository.findByTenantIdAndAccountIds(10L, List.of())).isEmpty(); + jdbc.update("INSERT INTO account_tenant_membership VALUES (3,10)"); + assertThat(repository.findByTenantIdAndAccountIds(10L, List.of(1L, 2L, 3L))) + .extracting(profile -> profile.getAccount().getId()) + .containsExactly(1L, 3L); + assertThat(jdbc.queryForObject("SELECT count(*) FROM profiles", Integer.class)).isEqualTo(4); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index 5f80a35681..550e39b066 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -5,12 +5,15 @@ import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; @@ -45,8 +48,13 @@ import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -156,6 +164,241 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { .isEqualTo(1L); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + value = SourceKind.class, + names = {"ACCOUNT", "GLOBAL_ROLES"}) + void globalWaitingIntentDeniesFirstJoinAndExactAbortedIntentAllowsTheOriginal(SourceKind kind) { + Fixture fixture = newFixture(); + var change = fixture.retainWaitingSourceChange(kind, fixture.account.getAccountUuid()); + var before = fixture.leaveRows(); + var intentBefore = fixture.rows("account_join_operations"); + + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical first-JOIN Account source intent is unresolved"); + assertThat(fixture.leaveRows()).isEqualTo(before); + assertThat(fixture.rows("account_join_operations")).isEqualTo(intentBefore); + assertThat(fixture.countAll("account_tenant_membership")).isZero(); + assertThat(fixture.countAll("account_tenant_membership_role_snapshots")).isZero(); + assertThat(fixture.countAll("account_audit_outbox")).isZero(); + + fixture.inTransaction( + () -> { + new DraftAuthorizationFenceRepository(fixture.dsl) + .markSourceAborted( + change, + DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + var committed = fixture.commitFirstJoin(); + assertThat(fixture.commitFirstJoin()).isEqualTo(committed); + } + + @Test + void mixedDraftOwnerOutcomesKeepFirstJoinAndOriginalAccountSourceIntentPending() { + Fixture fixture = newFixture(); + var fences = new DraftAuthorizationFenceRepository(fixture.dsl); + var binding = fixture.retainCommitOrderedDraftFence(fences); + var change = + new SourceChange( + UUID.randomUUID(), + binding.sources(), + "controlled pending mutation".getBytes(StandardCharsets.UTF_8)); + assertThat(fixture.inTransaction(() -> fences.requestSourceChange(change))).isFalse(); + + // The Account repository retains exact terminal evidence supplied by the test participants. + var readbacks = + List.of( + draftOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED), + draftOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED)); + fixture.transaction.executeWithoutResult( + status -> readbacks.forEach(readback -> fences.recordOwnerReadback(binding, readback))); + + var authorityBefore = fixture.leaveRows(); + String[] intentTables = { + "account_join_operations", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes", + "account_draft_authorization_owner_readbacks" + }; + var intentsBefore = fixture.rows(intentTables); + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical first-JOIN Account source intent is unresolved"); + + assertThat(fixture.leaveRows()).isEqualTo(authorityBefore); + assertThat(fixture.rows(intentTables)).isEqualTo(intentsBefore); + fixture.transaction.executeWithoutResult( + status -> { + var operation = + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow(); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.terminalProof()).isNull(); + var retainedChange = fences.inspectSourceChange(change); + assertThat(retainedChange.status()).isEqualTo("WAITING"); + assertThat(retainedChange.binding()).containsExactly(change.canonicalBytes()); + assertThat(fences.readSettlement(binding)).isEqualTo(Settlement.PENDING); + assertThat(fences.sourceMutationPermitted(change)).isFalse(); + assertThat(fences.sourceAbortPermitted(change)).isFalse(); + for (var readback : readbacks) { + var retained = fences.readOwnerResult(binding, readback.owner()).orElseThrow(); + assertThat(retained.outcome()).isEqualTo(readback.outcome()); + assertThat(retained.readback()).containsExactly(readback.canonicalBytes()); + } + }); + } + + @Test + void securityWaitingIntentDeniesFirstJoinWithoutAnyJoinOwnerWrites() { + Fixture fixture = newFixture(); + fixture.inTransaction( + () -> { + var current = + fixture.sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, fixture.account.getAccountUuid()); + fixture.commitControlledClosedAccountSecurityChange(current.account(), true); + return null; + }); + var before = fixture.leaveRows(); + var intentBefore = fixture.rows("account_join_operations", "account_security_state_operations"); + assertThat(fixture.countAll("account_security_state_operations")).isEqualTo(1L); + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical first-JOIN Account source intent is unresolved"); + assertThat(fixture.leaveRows()).isEqualTo(before); + assertThat(fixture.rows("account_join_operations", "account_security_state_operations")) + .isEqualTo(intentBefore); + } + + @Test + void unrelatedAccountAndTenantOnlyIntentAreNotGlobalDenialsAndCommittedReplayIsUnchanged() { + Fixture fixture = newFixture(); + Account other = fixture.createAccount(); + fixture.retainWaitingSourceChange(SourceKind.GLOBAL_ROLES, other.getAccountUuid()); + fixture.retainWaitingSourceChange(SourceKind.TENANT, fixture.tenantUuid); + boolean pending = + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + return fixture.operations.hasGlobalPendingIntent(fixture.account.getAccountUuid()); + }); + assertThat(pending).isFalse(); + + // This owner-local first JOIN still applies its existing tenant policy/source guards. + var committed = fixture.commitFirstJoin(); + fixture.retainWaitingSourceChange(SourceKind.GLOBAL_ROLES, fixture.account.getAccountUuid()); + var beforeReplay = fixture.leaveRows(); + assertThat(fixture.commitFirstJoin()).isEqualTo(committed); + assertThat(fixture.leaveRows()).isEqualTo(beforeReplay); + } + + @Test + void concurrentExactTerminalAttemptsShareOneMembershipEventAuditAndReceipt() throws Exception { + Fixture fixture = newFixture(); + var locked = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var firstPid = new java.util.concurrent.atomic.AtomicInteger(); + var waiterPid = new java.util.concurrent.atomic.AtomicInteger(); + var executor = java.util.concurrent.Executors.newFixedThreadPool(2); + try { + // Real owner transactions, not a synthetic COMMITTED-to-PENDING rewrite or a reconciler. + var first = + executor.submit( + () -> + fixture.inReadCommittedTransaction( + () -> { + firstPid.set( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + fixture.operations.lockAccount(fixture.account.getId()); + locked.countDown(); + try { + if (!release.await(20, java.util.concurrent.TimeUnit.SECONDS)) + throw new IllegalStateException( + "First terminal attempt release timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return fixture.commitFirstJoin(); + })); + assertThat(locked.await(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> + fixture.inReadCommittedTransaction( + () -> { + waiterPid.set( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + return fixture.commitFirstJoin(); + })); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + boolean blocked = false; + while (System.nanoTime() < deadline) { + blocked = + Boolean.TRUE.equals( + fixture + .dsl + .fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " + + "AND wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)))", + waiterPid.get(), + firstPid.get()) + .get(0, Boolean.class)); + if (blocked) break; + Thread.sleep(10); + } + assertThat(blocked) + .as("exact retry physically waits on the first owner transaction") + .isTrue(); + assertThat(second.isDone()).isFalse(); + release.countDown(); + var committed = first.get(30, java.util.concurrent.TimeUnit.SECONDS); + assertThat(second.get(30, java.util.concurrent.TimeUnit.SECONDS)).isEqualTo(committed); + var operation = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()); + assertThat(operation.status()).isEqualTo("COMMITTED"); + assertThat(operation.outcome()).isEqualTo("JOINED"); + assertThat(operation.terminalProof()).isEqualTo(committed); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isEqualTo(1L); + assertThat( + fixture.count( + "account_tenant_membership_role_snapshots", + "membership_id", + committed.membershipId())) + .isEqualTo(1L); + assertThat( + fixture.count( + "account_authority_outbox_events", + "outbox_stream_key", + fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.count("account_audit_outbox", "audit_event_id", committed.auditEventId())) + .isEqualTo(1L); + } finally { + release.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + @Test void changedEntitlementPreventsAStalePendingJoinFromCommittingMembership() { Fixture fixture = newFixture(); @@ -267,6 +510,82 @@ void terminalCoordinatorCommitsAuditAndOperationWithTheFirstEventAndReplaysExact .isEqualTo(1L); } + @Test + void unavailableAttemptBlocksFirstJoinUntilExactPolicyRecoversAndCannotRewriteTerminal() { + Fixture fixture = newFixture(); + var diagnosed = + fixture.inTransaction( + () -> + fixture.operations.recordCanonicalPolicyUnavailable( + fixture.requestId, + fixture.scope, + fixture.callerBinding, + "ENTITLEMENT_UNAVAILABLE")); + assertThat(diagnosed.status()).isEqualTo("PENDING"); + assertThat(diagnosed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(diagnosed.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(diagnosed.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(diagnosed.terminalProof()).isNull(); + String[] ownerTables = { + "account_join_operations", + "account_tenant_membership", + "account_tenant_membership_role_snapshots", + "account_membership_pair_authority", + "account_authority_outbox_events", + "account_audit_outbox" + }; + var pending = fixture.rows(ownerTables); + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(CanonicalJoinOperationConflictException.class) + .hasMessageContaining("no available positive public-join policy"); + assertThat(fixture.rows(ownerTables)).isEqualTo(pending); + + fixture.inTransaction( + () -> + fixture.operations.bindCanonicalPolicyEvidence( + fixture.requestId, + fixture.scope, + fixture.callerBinding, + true, + Objects.requireNonNull(diagnosed.entitlementVersion()))); + var proof = fixture.commitFirstJoin(); + var committed = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceByRequestId(fixture.requestId) + .orElseThrow()); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.requestDigest()).isEqualTo(diagnosed.requestDigest()); + assertThat(committed.entitlementVersion()).isEqualTo(diagnosed.entitlementVersion()); + assertThat(committed.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(committed.lastAttemptFailureCode()).isNull(); + assertThat(committed.terminalProof()).isEqualTo(proof); + + var terminal = fixture.rows(ownerTables); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + "UPDATE account_join_operations SET last_attempt_authority_availability = " + + "'UNAVAILABLE', last_attempt_failure_code = 'ENTITLEMENT_UNAVAILABLE' " + + "WHERE request_id = ?", + fixture.requestId))) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Terminal canonical JOIN receipt is immutable"); + }); + assertThat(fixture.commitFirstJoin()).isEqualTo(proof); + assertThat(fixture.rows(ownerTables)).isEqualTo(terminal); + } + @Test void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { Fixture fixture = newFixture(); @@ -583,6 +902,343 @@ void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alrea assertThat(storedRows.get()).isEqualTo(restoredRows); } + @Test + void canonicalLeaveCommitsMembershipFenceWithoutAnySecurityMutationAndReplaysHistoricalReceipt() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var binding = fixture.leaveBinding(); + var securityBefore = fixture.securityRows(); + var result = fixture.commitLeave(binding); + assertThat(result.terminal().outcome()).isEqualTo("LEFT"); + assertThat(result.terminal().beforeVersion()).isEqualTo(2L); + assertThat(result.terminal().version()).isEqualTo(3L); + assertThat(result.terminal().generation()).isEqualTo(2L); + assertThat(result.terminal().fence()).isEqualTo(result.terminal().beforeFence() + 1L); + assertThat(fixture.securityRows()).isEqualTo(securityBefore); + var runtimeReader = + new net.firedevops.firemud.accountservice.repository + .AccountCanonicalRuntimeMembershipSnapshotRepository( + fixture.accounts, + fixture.generations, + fixture.sourceEvidence, + fixture.tenantAuthorityEvents, + fixture.freshTenants, + fixture.memberships, + fixture.pairs, + fixture.roles, + fixture.outbox); + var negative = + fixture.inTransaction( + () -> runtimeReader.readCurrent(binding.accountId(), binding.tenantId())); + assertThat(negative.membershipExists()).isTrue(); + assertThat(negative.membershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(negative.gameplayAdmissionAllowed()).isFalse(); + assertThat(negative.roles()).isEmpty(); + assertThat(negative.issuanceFence()).isEqualTo(Long.toString(result.terminal().fence())); + var allAfter = fixture.leaveRows(); + assertThat(fixture.commitLeave(binding)).isEqualTo(result); + assertThat(fixture.leaveRows()).isEqualTo(allAfter); + assertThatThrownBy( + () -> + fixture.commitLeave( + new net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding( + binding.requestId(), + binding.accountId(), + binding.tenantId(), + "different-caller"))) + .hasMessageContaining("idempotency conflict"); + assertThat(fixture.leaveRows()).isEqualTo(allAfter); + var noOp = fixture.commitLeave(fixture.leaveBinding()); + assertThat(noOp.terminal().outcome()).isEqualTo("ALREADY_LEFT"); + assertThat(noOp.terminal().fence()).isEqualTo(result.terminal().fence()); + assertThat(fixture.securityRows()).isEqualTo(securityBefore); + var restored = fixture.commitExistingJoin(fixture.prepareAnotherJoin()); + assertThat(restored.membershipVersion()).isEqualTo(4L); + assertThat(restored.membershipAuthorityGeneration()).isEqualTo(2L); + var restoredRows = fixture.leaveRows(); + assertThat(fixture.commitLeave(binding)).isEqualTo(result); + assertThat(fixture.leaveRows()).isEqualTo(restoredRows); + } + + @Test + void canonicalLeaveTerminalFailureRollsBackMembershipFenceRolesEventAuditAndIntent() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var binding = fixture.leaveBinding(); + fixture.dsl.execute( + "CREATE FUNCTION fail_leave_terminal() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.status='COMMITTED' THEN RAISE EXCEPTION 'deliberate leave terminal failure'; END IF; RETURN NEW; END $$"); + fixture.dsl.execute( + "CREATE TRIGGER fail_leave_terminal BEFORE UPDATE ON account_leave_operations FOR EACH ROW EXECUTE FUNCTION fail_leave_terminal()"); + var before = fixture.leaveRows(); + assertThatThrownBy(() -> fixture.commitLeave(binding)) + .hasMessageContaining("deliberate leave terminal failure"); + assertThat(fixture.leaveRows()).isEqualTo(before); + fixture.dsl.execute("DROP TRIGGER fail_leave_terminal ON account_leave_operations"); + assertThat(fixture.commitLeave(binding).terminal().outcome()).isEqualTo("LEFT"); + } + + @Test + void canonicalLeaveInvalidatesCapturedSourceWithoutChangingSecurityGeneration() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var captured = + fixture.inTransaction( + () -> + fixture.generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.account( + fixture.account.getAccountUuid()))); + fixture.commitLeave(fixture.leaveBinding()); + var beforeRead = fixture.leaveRows(); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.sourceEvidence.readCurrentAccountSource( + fixture.account.getAccountUuid(), captured))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + var current = fixture.inTransaction(() -> fixture.generations.read(captured.scope())); + assertThat(current.generation()).isEqualTo(captured.generation()); + assertThat(current.sourceVersion()).isEqualTo(captured.sourceVersion()); + assertThat(current.issuanceFence().value()).isEqualTo(captured.issuanceFence().value() + 1L); + assertThat(fixture.leaveRows()).isEqualTo(beforeRead); + } + + @Test + void canonicalLeaveOfAbsentMembershipReturnsNoOpWithoutInitializingAuthority() { + Fixture fixture = newFixture(); + var before = + fixture.rows( + "account_tenant_membership", + "account_membership_pair_authority", + "account_authority_generations", + "account_authority_issuance_fences", + "account_issuance_fence_provenance", + "account_authority_outbox_events", + "account_audit_outbox"); + var binding = fixture.leaveBinding(); + var result = fixture.commitLeave(binding); + assertThat(result.terminal().outcome()).isEqualTo("ALREADY_LEFT"); + assertThat(result.terminal().membershipId()).isNull(); + assertThat(fixture.commitLeave(binding)).isEqualTo(result); + assertThat( + fixture.rows( + "account_tenant_membership", + "account_membership_pair_authority", + "account_authority_generations", + "account_authority_issuance_fences", + "account_issuance_fence_provenance", + "account_authority_outbox_events", + "account_audit_outbox")) + .isEqualTo(before); + } + + @Test + void canonicalLeaveCutoverPreservesExactLegacySecuritySourceAndEventBytes() { + TestContext context = newTestContext("1049"); + Fixture fixture = new Fixture(context); + fixture.commitFirstJoin(); + fixture.commitIndependentSecurityChange(); + var retained = + fixture.rows( + "accounts", + "account_authority_source_records", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_events", + "account_authority_outbox_streams"); + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat( + fixture.rows( + "accounts", + "account_authority_source_records", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_events", + "account_authority_outbox_streams")) + .isEqualTo(retained); + var anchor = + fixture.dsl.fetchSingle( + "SELECT cause_kind, issuance_fence, event_sequence FROM account_issuance_fence_provenance WHERE account_uuid=?", + fixture.account.getAccountUuid()); + assertThat(anchor.get("cause_kind", String.class)).isEqualTo("CUTOVER"); + assertThat(anchor.get("issuance_fence", Long.class)).isEqualTo(2L); + assertThat(anchor.get("event_sequence", Long.class)).isEqualTo(1L); + var security = fixture.securityRows(); + assertThat(fixture.commitLeave(fixture.leaveBinding()).terminal().fence()).isEqualTo(3L); + assertThat(fixture.securityRows()).isEqualTo(security); + } + + @Test + void canonicalLeaveRejectsUnbackedFenceAdvanceAndWrongCausalEventWithFullRollback() { + for (boolean supplyWrongEvent : List.of(false, true)) { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var before = fixture.leaveRows(); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + var scope = + AccountAuthorityGenerationRepository.AuthorityScope.membership( + fixture.account.getAccountUuid(), fixture.tenantUuid); + var old = fixture.generations.read(scope); + var advanced = fixture.generations.advance(old, old.issuanceFence()); + if (supplyWrongEvent) { + var original = + fixture + .outbox + .findEvent(fixture.membershipStream(), 1L) + .orElseThrow(); + fixture.dsl.execute( + "INSERT INTO account_issuance_fence_provenance " + + "(account_uuid,issuance_fence,source_version,prior_fence,cause_kind,tenant_uuid,source_stream_key,event_sequence,event_id,event_digest,prior_generation,generation,prior_authority_source_version,authority_source_version) " + + "VALUES (?,?,?,?, 'MEMBERSHIP',?,?,?,?,?,?,?,?,?)", + fixture.account.getAccountUuid(), + advanced.issuanceFence().value(), + advanced.issuanceFence().sourceVersion(), + old.issuanceFence().value(), + fixture.tenantUuid, + original.outboxStreamKey(), + original.outboxSequence(), + original.eventId(), + original.eventDigest(), + old.generation(), + advanced.generation(), + old.sourceVersion(), + advanced.sourceVersion()); + } + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.leaveRows()).isEqualTo(before); + } + } + + @Test + void canonicalLeaveAndSecurityWriterSerializeAtTheAccountLockInBothOrders() throws Exception { + for (boolean securityFirst : List.of(true, false)) { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var binding = fixture.leaveBinding(); + var locked = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var waiterPid = new java.util.concurrent.atomic.AtomicInteger(); + var executor = java.util.concurrent.Executors.newFixedThreadPool(2); + java.util.function.Consumer change = + security -> { + if (security) { + fixture.commitControlledClosedAccountSecurityChange( + fixture + .sourceEvidence + .readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, fixture.account.getAccountUuid()) + .account()); + } else { + fixture.commitLeave(binding); + } + }; + try { + var first = + executor.submit( + () -> + fixture.inReadCommittedTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + locked.countDown(); + try { + if (!release.await(20, java.util.concurrent.TimeUnit.SECONDS)) + throw new IllegalStateException("First owner release timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + change.accept(securityFirst); + return null; + })); + assertThat(locked.await(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> + fixture.inReadCommittedTransaction( + () -> { + waiterPid.set( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + fixture.operations.lockAccount(fixture.account.getId()); + change.accept(!securityFirst); + return null; + })); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + boolean blocked = false; + while (System.nanoTime() < deadline) { + blocked = + Boolean.TRUE.equals( + fixture + .dsl + .fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock')", + waiterPid.get()) + .get(0, Boolean.class)); + if (blocked) break; + Thread.sleep(10); + } + assertThat(blocked).as("second owner physically waits on Account row lock").isTrue(); + assertThat(second.isDone()).isFalse(); + release.countDown(); + first.get(30, java.util.concurrent.TimeUnit.SECONDS); + second.get(30, java.util.concurrent.TimeUnit.SECONDS); + var current = + fixture.inTransaction( + () -> + fixture.sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, fixture.account.getAccountUuid())); + assertThat(current.account().generation()).isEqualTo(2L); + assertThat(current.account().checkpoint().sequence()).isEqualTo(1L); + assertThat(current.issuanceFence().value()).isEqualTo(3L); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + } + + @Test + void canonicalLeaveAndIndependentSecurityChangeAdvanceOneCompositeFenceInBothOrders() { + for (boolean securityFirst : List.of(true, false)) { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + var binding = fixture.leaveBinding(); + if (securityFirst) fixture.commitIndependentSecurityChange(); + var securityAtLeave = fixture.securityRows(); + var left = fixture.commitLeave(binding); + assertThat(fixture.securityRows()).isEqualTo(securityAtLeave); + if (!securityFirst) fixture.commitIndependentSecurityChange(); + var current = + fixture.inTransaction( + () -> + fixture.sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, fixture.account.getAccountUuid())); + assertThat(current.account().generation()).isEqualTo(2L); + assertThat(current.account().checkpoint().sequence()).isEqualTo(1L); + assertThat(current.issuanceFence().value()).isEqualTo(3L); + var beforeReplay = fixture.leaveRows(); + assertThat(fixture.commitLeave(binding)).isEqualTo(left); + assertThat(fixture.leaveRows()).isEqualTo(beforeReplay); + } + } + @Test void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration() { Fixture fixture = newFixture(); @@ -905,21 +1561,29 @@ private Fixture newFixture() { } private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContext(String target) { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); runOwnedSchemas.add(schema); DriverManagerDataSource dataSource = postgres.dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) configuration.target(target); + configuration.load().migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); return new TestContext( - dsl, new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + dsl, + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + dataSource, + schema); } private static final class Fixture { @@ -1002,6 +1666,83 @@ private Fixture(TestContext context) { seedOwnerRowsAndOperation(); } + private net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding leaveBinding() { + return new net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding( + UUID.randomUUID().toString(), account.getAccountUuid(), tenantUuid, callerBinding); + } + + private net.firedevops.firemud.accountservice.repository.AccountLeaveOperationRepository.Receipt + commitLeave( + net.firedevops.firemud.accountservice.dto.AccountLeaveMembershipBinding binding) { + var owner = + new net.firedevops.firemud.accountservice.service + .AccountCanonicalLeaveMembershipCoordinator( + accounts, + operations, + new net.firedevops.firemud.accountservice.repository.AccountLeaveOperationRepository( + dsl), + memberships, + sourceEvidence, + producer, + auditOutbox); + return inTransaction(() -> owner.leave(binding)); + } + + private T inReadCommittedTransaction(java.util.function.Supplier callback) { + var owner = new TransactionTemplate(transaction.getTransactionManager()); + owner.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + owner.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + return owner.execute(status -> callback.get()); + } + + private void commitIndependentSecurityChange() { + inReadCommittedTransaction( + () -> { + operations.lockAccount(account.getId()); + commitControlledClosedAccountSecurityChange( + sourceEvidence + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, account.getAccountUuid()) + .account()); + return null; + }); + } + + private List>> rows(String... tables) { + return java.util.Arrays.stream(tables) + .map( + table -> + dsl.fetch( + "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()) + .toList(); + } + + private List>> securityRows() { + return rows("accounts", "account_authority_source_records", "account_global_role_sources"); + } + + private List>> leaveRows() { + return rows( + "accounts", + "account_authority_source_records", + "account_global_role_sources", + "account_tenant_membership", + "account_tenant_membership_role_snapshots", + "account_tenant_membership_role_snapshot_roles", + "account_membership_pair_authority", + "account_authority_generations", + "account_authority_issuance_fences", + "account_issuance_fence_provenance", + "account_authority_outbox_events", + "account_authority_outbox_streams", + "account_audit_outbox", + "account_leave_operations"); + } + private Account createAccount() { Account input = new Account(); String suffix = UUID.randomUUID().toString().replace("-", ""); @@ -1551,6 +2292,12 @@ private void seedControlledMembershipSnapshot( */ private void commitControlledClosedAccountSecurityChange( AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource) { + commitControlledClosedAccountSecurityChange(currentSource, false); + } + + private void commitControlledClosedAccountSecurityChange( + AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource, + boolean retainWaiting) { var current = accounts.findByIdForUpdate(account.getId()).orElseThrow(); var roleSource = Objects.requireNonNull( @@ -1638,6 +2385,7 @@ private void commitControlledClosedAccountSecurityChange( var securityOperations = new AccountSecurityStateOperationRepository(dsl); assertThat(fences.requestSourceChange(change)).isTrue(); assertThat(securityOperations.claim(request, capture).claimed()).isTrue(); + if (retainWaiting) return; assertThat(fences.sourceMutationPermitted(change)).isTrue(); var advanced = sourceEvidence.prepareClosedAccountAdvance(account.getAccountUuid(), currentSource); @@ -1673,6 +2421,128 @@ private void commitControlledClosedAccountSecurityChange( assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); } + /** Durable scoped owner snapshots, not an authenticated mutation producer or a guard bypass. */ + private SourceChange retainWaitingSourceChange(SourceKind kind, UUID scopeId) { + return inTransaction( + () -> { + SourceEvidence source; + if (kind == SourceKind.TENANT) { + var event = tenantAuthorityEvents.readCurrentByTenant(scopeId); + source = + new SourceEvidence( + kind, + scopeId.toString(), + Long.toString(event.tenantAuthorityGeneration()), + Long.toString(event.tenantAuthoritySourceVersion()), + event.outboxStreamKey(), + Long.toString(event.outboxSequence()), + event.payload()); + } else { + var state = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.account(scopeId)); + var row = + dsl.fetchSingle( + "SELECT r.global_role_source_version, " + + "to_jsonb(a)::text AS account_evidence, to_jsonb(r)::text AS role_evidence " + + "FROM accounts a JOIN account_global_role_sources r USING (account_uuid) " + + "WHERE a.account_uuid = ?", + scopeId); + source = + new SourceEvidence( + kind, + scopeId.toString(), + kind == SourceKind.ACCOUNT ? Long.toString(state.generation()) : null, + Long.toString( + kind == SourceKind.ACCOUNT + ? state.sourceVersion() + : row.get("global_role_source_version", Long.class)), + null, + null, + row.get( + kind == SourceKind.ACCOUNT ? "account_evidence" : "role_evidence", + String.class) + .getBytes(StandardCharsets.UTF_8)); + } + var change = + new SourceChange( + UUID.randomUUID(), + List.of(source), + "controlled pending mutation".getBytes(StandardCharsets.UTF_8)); + var fences = new DraftAuthorizationFenceRepository(dsl); + assertThat(fences.requestSourceChange(change)).isTrue(); + assertThat(fences.readSourceChange(change).status()).isEqualTo("WAITING"); + return change; + }); + } + + private DraftAuthorizationFenceBinding retainCommitOrderedDraftFence( + DraftAuthorizationFenceRepository fences) { + return inTransaction( + () -> { + operations.lockAccount(account.getId()); + UUID accountId = account.getAccountUuid(); + var current = sourceEvidence.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId); + var source = current.account(); + var accountEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + accountId.toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), + current.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8)); + var draft = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenantUuid, + UUID.randomUUID(), + 1, + tenantEvidence.sourceGameTenantKey(), + tenantEvidence.sourceGameRowId(), + tenantEvidence.sourceGameTenantKey(), + tenantEvidence.provenanceKind()), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only/base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only-world-payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + var binding = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + draft.requestId(), + draft.commitId(), + UUID.randomUUID(), + accountId, + tenantUuid, + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + List.of(accountEvidence)) + .withRequiredOwners(); + fences.reserve(binding); + assertThat(fences.claimCommitOrder(binding).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + return binding; + }); + } + private long membershipId() { return membershipId == null ? -1L : membershipId; } @@ -1701,6 +2571,19 @@ private T inTransaction(java.util.function.Supplier callback) { } } + private static OwnerReadback draftOwnerReadback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + return new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + (owner.name() + ":" + outcome.name()).getBytes(StandardCharsets.UTF_8)); + } + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); @@ -1755,7 +2638,11 @@ private static long positiveRandomLong() { return value == 0L ? 1L : value; } - private record TestContext(DSLContext dsl, TransactionTemplate transaction) {} + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + String schema) {} private record BrowserFacade( net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl service, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java index 9d9eac0ed1..ced1e4d2ca 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java @@ -88,13 +88,10 @@ void boundsActualKeysAfterPressureCounterLossAndFullReset() { service.admit(source("192.0.2." + (i + 1)), "candidate" + i + "@example.test"); assertEnvelope(inspector, policy); } - byte[][] pressureKeys = - inspector - .sync() - .keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*") - .toArray(new byte[0][]); - if (pressureKeys.length > 0) { - inspector.sync().del(pressureKeys); + var pressureKeys = + inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*"); + if (!pressureKeys.isEmpty()) { + inspector.sync().del(pressureKeys.toArray(byte[][]::new)); } for (int i = 0; i < 24; i++) { service.admit(source("198.51.100." + (i + 1)), "new" + i + "@example.test"); @@ -292,6 +289,58 @@ void multipleAccountReplicasUseSingleKeyAtomicFailureUpdates() throws Exception } } + @Test + void candidateFailureBudgetIsSharedAcrossSourcesAndClientReplicas() { + var policy = candidateBudgetPolicy(4_096); + String firstAddress = "198.51.100.41"; + String secondAddress = "::ffff:198.51.100.42"; + String normalizedSecondAddress = "198.51.100.42"; + String candidate = "shared-candidate@example.test"; + String unrelatedCandidate = "other-candidate@example.test"; + RedisClient firstReplica = client(redis, true); + RedisClient secondReplica = client(redis, true); + try (var key = key(); + var inspector = admin.connect(ByteArrayCodec.INSTANCE); + var firstConnection = firstReplica.connect(ByteArrayCodec.INSTANCE); + var secondConnection = secondReplica.connect(ByteArrayCodec.INSTANCE)) { + var firstService = service(policy, key, firstConnection); + var secondService = service(policy, key, secondConnection); + + var firstAttempt = firstService.admit(source(firstAddress), candidate); + assertThat(firstAttempt.outcome()).isEqualTo(Outcome.ADMITTED); + assertThat(firstService.recordFailure(firstAttempt.permit()).outcome()) + .isEqualTo(Outcome.FAILURE_RECORDED); + + var secondAttempt = secondService.admit(source(secondAddress), candidate); + assertThat(secondAttempt.outcome()).isEqualTo(Outcome.ADMITTED); + assertThat(secondService.recordFailure(secondAttempt.permit()).outcome()) + .isEqualTo(Outcome.FAILURE_RECORDED); + + var keys = new AccountCredentialAbuseSubjectKeys(policy.scope(), key); + long window = Instant.now().toEpochMilli() / policy.window().toMillis(); + assertThat(keys.source(firstAddress, window).redisKey()) + .isNotEqualTo(keys.source(secondAddress, window).redisKey()); + assertThat(keys.source(secondAddress, window).redisKey()) + .isEqualTo(keys.source(normalizedSecondAddress, window).redisKey()); + assertThat(firstService.admit(source(firstAddress), candidate).outcome()) + .isEqualTo(Outcome.RETRY_LATER); + assertThat(firstService.admit(source(firstAddress), unrelatedCandidate).outcome()) + .isEqualTo(Outcome.ADMITTED); + + assertEnvelope(inspector, policy); + assertStoredStateOmitsRawInputs( + inspector, + firstAddress, + secondAddress, + normalizedSecondAddress, + candidate, + unrelatedCandidate); + } finally { + firstReplica.shutdown(); + secondReplica.shutdown(); + } + } + @Test void wrongPrincipalAndClusterTopologyRefuseWithoutAStandaloneFallback() { var policy = policy(4_096); @@ -409,13 +458,41 @@ private static AccountCredentialAbuseService service( } private static AccountCredentialAbusePolicy policy(long bucketBytes) { + return policy( + bucketBytes, + List.of( + new AccountCredentialAbusePolicy.Rule(3, 2, 0, Duration.ofSeconds(1)), + new AccountCredentialAbusePolicy.Rule(3, 2, 10, Duration.ofSeconds(5)))); + } + + private static AccountCredentialAbusePolicy candidateBudgetPolicy(long bucketBytes) { + return policy( + bucketBytes, + List.of( + new AccountCredentialAbusePolicy.Rule(3, 0, 0, Duration.ofSeconds(1)), + new AccountCredentialAbusePolicy.Rule(0, 2, 0, Duration.ofSeconds(5)), + new AccountCredentialAbusePolicy.Rule(0, 2, 10, Duration.ofSeconds(10))), + Duration.ofMinutes(5), + Duration.ofMinutes(10)); + } + + private static AccountCredentialAbusePolicy policy( + long bucketBytes, List rules) { + return policy(bucketBytes, rules, Duration.ofSeconds(60), Duration.ofSeconds(120)); + } + + private static AccountCredentialAbusePolicy policy( + long bucketBytes, + List rules, + Duration window, + Duration timeToLive) { Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); return new AccountCredentialAbusePolicy( "login-v1", now.minusSeconds(60), now.plusSeconds(3_600), - Duration.ofSeconds(60), - Duration.ofSeconds(120), + window, + timeToLive, 2, 8, POLICY_BYTES, @@ -426,9 +503,7 @@ private static AccountCredentialAbusePolicy policy(long bucketBytes) { Duration.ofSeconds(5), Duration.ofSeconds(10), Duration.ofSeconds(1), - List.of( - new AccountCredentialAbusePolicy.Rule(3, 2, 0, Duration.ofSeconds(1)), - new AccountCredentialAbusePolicy.Rule(3, 2, 10, Duration.ofSeconds(5)))); + rules); } private static byte[] onlyCandidateKey(StatefulRedisConnection inspector) { @@ -460,6 +535,22 @@ private static void assertEnvelope( assertThat(metric(memory, "used_memory_rss")).isLessThanOrEqualTo(PROCESS_BYTES); } + private static void assertStoredStateOmitsRawInputs( + StatefulRedisConnection inspector, String... rawInputs) { + var keys = inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "*"); + assertThat(keys).isNotEmpty(); + for (byte[] key : keys) { + String keyText = new String(key, StandardCharsets.US_ASCII); + byte[] value = inspector.sync().get(key); + assertThat(value).isNotNull(); + String valueText = new String(value, StandardCharsets.US_ASCII); + for (String rawInput : rawInputs) { + assertThat(keyText).doesNotContain(rawInput); + assertThat(valueText).doesNotContain(rawInput); + } + } + } + private static long metric(String info, String name) { return info.lines() .filter(line -> line.startsWith(name + ":")) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java index 2987eda302..d5847b3c00 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -213,6 +213,18 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce denied.put("secret", "wrong-secret"); assertThat(receiving.request("POST", "/api/account/auth/login", null, denied).statusCode()) .isEqualTo(401); + // The fixture owns a unique policy scope with real 60-second fixed windows. Start a + // new window before issuance so earlier failures cannot supply threshold credit + // and the real 60-second response-recovery window is not consumed by this wait. + long windowMillis = Duration.ofSeconds(60).toMillis(); + long previousWindow = Math.floorDiv(System.currentTimeMillis(), windowMillis); + long windowWaitDeadline = System.nanoTime() + Duration.ofSeconds(65).toNanos(); + while (Math.floorDiv(System.currentTimeMillis(), windowMillis) <= previousWindow) { + assertThat(System.nanoTime()).isLessThan(windowWaitDeadline); + Thread.sleep(25); + } + long failureWindow = Math.floorDiv(System.currentTimeMillis(), windowMillis); + long failurePhaseDeadline = System.nanoTime() + Duration.ofSeconds(50).toNanos(); receiving.resetIngressObservations(); var signedIn = receiving.request( @@ -292,23 +304,26 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce assertThat(wrongOwner.body()) .doesNotContain(tuple.path("invoiceId").asText(), "clientSecret", PASSWORD); - // The fixture uses fixed 60-second windows. If setup crossed a window boundary, the - // first phase's source failures may have expired; keep issuing fresh requests until this - // distinct candidate reaches its bounded threshold in one window. - denied.put("email", account.getEmail()); - HttpResponse throttled = null; - for (int attempt = 0; attempt < 8; attempt++) { + // Admission precedes failure accounting: three failures populate source >= 3 and + // candidate >= 2, and only the following new request is throttled. + for (int failure = 0; failure < 3; failure++) { + assertThat(System.nanoTime()).isLessThan(failurePhaseDeadline); + assertThat(Math.floorDiv(System.currentTimeMillis(), windowMillis)) + .isEqualTo(failureWindow); denied.put("requestId", UUID.randomUUID()); - var response = receiving.request("POST", "/api/account/auth/login", null, denied); - if (response.statusCode() == 429) { - throttled = response; - break; - } - assertThat(response.statusCode()).isEqualTo(401); + assertThat( + receiving.request("POST", "/api/account/auth/login", null, denied).statusCode()) + .isEqualTo(401); + assertThat(Math.floorDiv(System.currentTimeMillis(), windowMillis)) + .isEqualTo(failureWindow); } - assertThat(throttled) - .as("Shared Cache throttles within the bounded retry phase") - .isNotNull(); + assertThat(System.nanoTime()).isLessThan(failurePhaseDeadline); + denied.put("requestId", UUID.randomUUID()); + var throttled = receiving.request("POST", "/api/account/auth/login", null, denied); + assertThat(Math.floorDiv(System.currentTimeMillis(), windowMillis)) + .isEqualTo(failureWindow); + assertThat(System.nanoTime()).isLessThan(failurePhaseDeadline); + assertThat(throttled.statusCode()).isEqualTo(429); assertThat(throttled.headers().firstValue("retry-after")).contains("1"); assertThat(throttled.body()).contains("AUTH_RETRY_LATER"); @@ -663,6 +678,10 @@ private static final class RegisteredChain implements AutoCloseable { grpc = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext(grpcTls) + // The gateway channel pings every 30s without calls; the test idles across a + // rate-limit window, so admit those pings instead of answering too_many_pings. + .permitKeepAliveTime(30, TimeUnit.SECONDS) + .permitKeepAliveWithoutCalls(true) .addService( ServerInterceptors.intercept( account.getBean(AccountControlUiAuthenticationGrpcService.class), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java index 3ee44a5c2c..52450338c2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -3,10 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -17,10 +20,16 @@ import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Objects; @@ -29,6 +38,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; @@ -48,21 +59,23 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real Flyway/PostgreSQL owner storage proof only. Primary authentication, canonical authority, - * signer capture and Redis/TLS/WAITAOF are explicitly test-only doubles. The tenant source is a - * stipulated external Game Design fixture, not genuine owner provenance. No private proof - * constructor is bypassed: Coordination creates its receipt through its normal transport path. - * Opaque envelope fixture bytes prove retention, not AEAD, genuine issuance or physical Redis. + * Real Flyway/PostgreSQL owner storage. Repository cases use controlled primary, authority and + * signer inputs. The retained-key rotation and signing refusal cases use real envelope cryptography + * with temporary test custody. Signing refusal also uses actual Account source, primary + * authentication, mounted signing and JWT validation with controlled upstream inputs. Coordination + * creates receipts through the owner adapter with controlled transport responses. */ @Testcontainers(disabledWithoutDocker = true) class AccountControlUiIssuancePostgresIntegrationTest { @@ -107,6 +120,351 @@ void originalPreparedCandidateCommittedAndLostResponseReadBackExactOwnerBytes() assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); } + @Test + void serviceCommitsPreparedBeforeSigningAndRecoversTheSameOriginalAfterRefusal( + @TempDir Path temporary) throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + temporary, + false); + var lifecycle = new AccountControlUiSignerFixture(f, temporary); + lifecycle.commit(); + Path custody = temporary.resolve("custody"); + writeTestKeyring(custody.resolve("encryption"), "enc1", (byte) 11); + writeTestKeyring(custody.resolve("request-mac"), "mac1", (byte) 29); + Clock clock = Clock.fixed(Instant.now().truncatedTo(ChronoUnit.SECONDS), ZoneOffset.UTC); + var crypto = + new AccountControlUiResponseCryptography(new AccountControlUiKeyring(custody), clock); + var operations = new AccountControlUiIssuanceRepository(f.dsl); + var signer = spy(lifecycle.signer); + var registry = controlledRegistry(f, operations); + var publicSource = + new AccountJwtJwksTrustedSource( + lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + var actors = + new AccountControlUiActorService( + operations, f.authority, signer, registry, publicSource, f.fences, f.manager, clock); + Function issuance = + currentClock -> + new AccountControlUiIssuanceService( + f.primary, + null, + new AccountControlUiIssuanceRepository(f.dsl), + f.authority, + f.fences, + signer, + crypto, + registry, + actors, + f.manager, + currentClock, + 300_000L, + AccountControlUiOwnerSourcesFixture.CALLER); + var first = new AtomicReference(); + var refusal = new IllegalStateException("Controlled first signing refusal"); + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var prepared = Objects.requireNonNull(f.tx(() -> operations.findRequest(f.request))); + var captured = call.getArgument(0, AccountControlUiSignerOwner.Capture.class); + var spec = call.getArgument(1, AccountControlUiSigningSpec.class); + assertThat(prepared.status).isEqualTo("PREPARED"); + assertThat(prepared.tokenHash).isNull(); + assertThat(prepared.pendingRegistry).isNull(); + assertThat(prepared.activeRegistry).isNull(); + assertThat(prepared.operationId).isEqualTo(spec.operationId()); + assertThat(prepared.requestId).isEqualTo(spec.requestId()); + assertThat(prepared.jti).isEqualTo(spec.jti()); + assertThat(prepared.claims) + .containsExactly(AccountControlUiAuthority.canonical(spec.claims())); + assertThat(prepared.signerReceipt).containsExactly(captured.receipt()); + assertThat(prepared.issuedAt).isEqualTo(clock.instant()); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))) + .isZero(); + if (first.compareAndSet(null, prepared)) { + throw refusal; + } + assertOriginal(first.get(), prepared); + return call.callRealMethod(); + }) + .when(signer) + .sign(any(), any(), any()); + + var request = f.request(AccountControlUiOwnerSourcesFixture.OTP); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + try (var peer = + AccountControlUiOwnerSourcesFixture.withPeer(AccountControlUiOwnerSourcesFixture.CALLER)) { + assertThatThrownBy(() -> issuance.apply(clock).issue(request, environment)).isSameAs(refusal); + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + var retained = f.tx(() -> operations.findRequest(f.request)); + assertOriginal(first.get(), retained); + assertThat(retained.status).isEqualTo("PREPARED"); + assertThat(retained.tokenHash).isNull(); + verifyNoInteractions(registry); + + var restarted = issuance.apply(Clock.offset(clock, Duration.ofSeconds(1))); + try (var issued = restarted.issue(request, environment); + var replayed = restarted.issue(request, environment)) { + var committed = f.tx(() -> operations.findRequest(f.request)); + assertOriginal(retained, committed); + assertThat(committed.status).isEqualTo("COMMITTED"); + assertThat(committed.tokenHash) + .isEqualTo(AccountControlUiIssuanceRepository.hash(issued.compactBytes())); + assertThat(replayed.compactBytes()).containsExactly(issued.compactBytes()); + assertThat(replayed.expiresAt()).isEqualTo(retained.expiresAt); + assertThat(replayed.recoveryExpiresAt()).isEqualTo(retained.recoveryExpiry); + } + } + verify(signer, times(2)).sign(any(), any(), any()); + verify(registry).registerPending(anyString(), any(byte[].class), anyLong()); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isEqualTo(1); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + } + + private static AccountControlUiCoordination controlledRegistry( + AccountControlUiOwnerSourcesFixture f, AccountControlUiIssuanceRepository operations) { + var registry = mock(AccountControlUiCoordination.class); + var activated = new AtomicReference(); + when(registry.registerPending(anyString(), any(byte[].class), anyLong())) + .thenAnswer( + call -> { + var candidate = f.tx(() -> operations.findRequest(f.request)); + return new Transport(candidate) + .client.registerPending( + call.getArgument(0), call.getArgument(1), call.getArgument(2)); + }); + when(registry.activate(any())) + .thenAnswer( + call -> { + var original = + call.getArgument(0, AccountControlUiIssuanceRepository.Committed.class); + var receipt = + new Transport(original.stored, original.activeRegistry()) + .client.activate(original); + activated.set(original); + return receipt; + }); + when(registry.readActive(anyString())) + .thenAnswer( + call -> { + var original = activated.get(); + return original != null && original.tokenHash().equals(call.getArgument(0)) + ? original.activeRegistry() + : null; + }); + return registry; + } + + private static void writeTestKeyring(Path directory, String id, byte fill) throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, fill); + Files.writeString( + Files.createDirectories(directory).resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + @Test + void concurrentOwnerRequestSelectionRetainsOneOriginalPreparedCapture() throws Exception { + Context c = context(); + Fixture f = new Fixture(c); + UUID callerContext = UUID.randomUUID(); + Instant issuedAt = Instant.ofEpochSecond(Instant.now().getEpochSecond()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (var workers = Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable attempt = + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) + throw new AssertionError("Owner selection start timed out"); + return c.tx( + () -> { + c.operations.lockReplayRequest(f.request); + var existing = c.operations.findRequest(f.request); + if (existing != null) return existing; + return c.operations.prepare( + f.request, + "spiffe://test-only/control-ui", + callerContext, + "test-mac1", + "c".repeat(64), + f.primary, + f.authority, + f.signer, + issuedAt, + 300_000L); + }); + }; + var first = workers.submit(attempt); + var second = workers.submit(attempt); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult.status).isEqualTo("PREPARED"); + assertOriginal(firstResult, secondResult); + assertThat(secondResult.operationId).isEqualTo(firstResult.operationId); + assertThat(secondResult.jti).isEqualTo(firstResult.jti); + assertThat(secondResult.callerContextId).isEqualTo(callerContext); + assertThat(secondResult.claims).containsExactly(firstResult.claims); + assertThat(secondResult.sources).containsExactly(firstResult.sources); + assertThat(secondResult.bundle).containsExactly(firstResult.bundle); + assertThat(secondResult.signerReceipt).containsExactly(firstResult.signerReceipt); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + } finally { + start.countDown(); + } + } + + @Test + void retainedEncryptedOwnerResponseRecoversAfterRealKeyRotationAndRepositoryRestart( + @org.junit.jupiter.api.io.TempDir java.nio.file.Path custody) throws Exception { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + java.nio.file.Path encryption = + java.nio.file.Files.createDirectories(custody.resolve("encryption")); + byte[] oldKey = new byte[32]; + byte[] newKey = new byte[32]; + java.util.Arrays.fill(oldKey, (byte) 11); + java.util.Arrays.fill(newKey, (byte) 23); + String oldEncoded = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(oldKey); + String newEncoded = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(newKey); + String header = "firemud-account-response-envelope-keyring-v1\n"; + java.nio.file.Files.writeString( + encryption.resolve("keyring"), header + "active enc-old " + oldEncoded + "\n"); + Clock clock = Clock.fixed(prepared.issuedAt, java.time.ZoneOffset.UTC); + var crypto = + new AccountControlUiResponseCryptography(new AccountControlUiKeyring(custody), clock); + byte[] credential = bytes("test-only-control-ui-response-not-a-runtime-token"); + byte[] sealed = crypto.seal(credential, f.ownerBinding, prepared.recoveryExpiry); + var candidate = + c.tx( + () -> + c.operations.bindCandidate( + prepared, "d".repeat(64), sealed, f.ownerBinding, f.signer)); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + c.tx(() -> c.operations.commit(candidate, pending)); + var operationsBefore = + c.dsl + .fetch( + "SELECT row_to_json(t)::text FROM account_control_ui_issuance_operations t ORDER BY 1") + .getValues(0, String.class); + var envelopesBefore = + c.dsl + .fetch( + "SELECT row_to_json(t)::text FROM account_control_ui_response_envelopes t ORDER BY 1") + .getValues(0, String.class); + assertThat(operationsBefore).hasSize(1); + assertThat(envelopesBefore).hasSize(1); + java.nio.file.Files.writeString( + encryption.resolve("keyring"), + header + + "active enc-new " + + newEncoded + + "\nretiring enc-old " + + prepared.recoveryExpiry.plusSeconds(60).toEpochMilli() + + " " + + oldEncoded + + "\n"); + var restarted = new AccountControlUiIssuanceRepository(c.dsl); + var reread = c.tx(() -> restarted.findRequest(prepared.requestId)); + c.tx(() -> restarted.requireCommitted(reread)); + var envelope = Objects.requireNonNull(c.tx(() -> restarted.envelope(reread))); + var rotatedCrypto = + new AccountControlUiResponseCryptography(new AccountControlUiKeyring(custody), clock); + assertThat(envelope.encrypted()).containsExactly(sealed); + assertThat(envelope.binding()).containsExactly(f.ownerBinding); + assertThat(rotatedCrypto.open(envelope.encrypted(), envelope.binding(), reread.recoveryExpiry)) + .containsExactly(credential); + assertThatThrownBy( + () -> + rotatedCrypto.open( + envelope.encrypted(), bytes("different-owner"), reread.recoveryExpiry)) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + java.nio.file.Files.writeString( + encryption.resolve("keyring"), header + "active enc-new " + newEncoded + "\n"); + assertThatThrownBy( + () -> + rotatedCrypto.open(envelope.encrypted(), envelope.binding(), reread.recoveryExpiry)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + assertThat( + c.dsl + .fetch( + "SELECT row_to_json(t)::text FROM account_control_ui_issuance_operations t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(operationsBefore); + assertThat( + c.dsl + .fetch( + "SELECT row_to_json(t)::text FROM account_control_ui_response_envelopes t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(envelopesBefore); + } + + @Test + void lateCommitRollbackPreservesExactCandidateAndOriginalEnvelope() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + var candidate = f.candidate(prepared); + var rowsBefore = + c.dsl.fetch( + "SELECT to_jsonb(o)::text AS wire FROM account_control_ui_issuance_operations o"); + var envelopesBefore = + c.dsl.fetch( + "SELECT to_jsonb(e)::text AS wire FROM account_control_ui_response_envelopes e"); + assertThat(rowsBefore).hasSize(1); + assertThat(envelopesBefore).hasSize(1); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + assertThatThrownBy( + () -> + c.tx( + () -> { + var committed = c.operations.commit(candidate, pending); + assertThat(committed.stored.status).isEqualTo("COMMITTED"); + assertThat(c.operations.findRequest(candidate.requestId).status) + .isEqualTo("COMMITTED"); + throw new IllegalStateException("deliberate rollback after issuance commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("deliberate rollback after issuance commit"); + assertThat( + c.dsl.fetch( + "SELECT to_jsonb(o)::text AS wire FROM account_control_ui_issuance_operations o")) + .isEqualTo(rowsBefore); + assertThat( + c.dsl.fetch( + "SELECT to_jsonb(e)::text AS wire FROM account_control_ui_response_envelopes e")) + .isEqualTo(envelopesBefore); + var retained = c.tx(() -> c.operations.findRequest(candidate.requestId)); + assertThat(retained.status).isEqualTo("CANDIDATE"); + assertOriginal(candidate, retained); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(retained))) + .isInstanceOf(IllegalStateException.class); + var recovered = c.tx(() -> c.operations.commit(retained, pending)); + assertThat(recovered.stored.status).isEqualTo("COMMITTED"); + assertOriginal(candidate, recovered.stored); + var envelope = Objects.requireNonNull(c.tx(() -> c.operations.envelope(recovered.stored))); + assertThat(envelope.encrypted()).containsExactly(f.encryptedResponse); + assertThat(envelope.binding()).containsExactly(f.ownerBinding); + } + @Test void replayDenialsPersistBoundedHistoryWithoutChangingRetainedIssuanceAccountOrOtp() { Context c = contextAt("1043"); @@ -709,6 +1067,10 @@ private static final class Transport { final AccountControlUiCoordination client; Transport(AccountControlUiIssuanceRepository.Stored original) { + this(original, original.pendingRegistry); + } + + Transport(AccountControlUiIssuanceRepository.Stored original, byte[] exactReadback) { var descriptor = AccountControlUiRegistryContract.descriptor(); var catalog = mock(RedisScriptCatalog.class); when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); @@ -727,7 +1089,7 @@ private static final class Transport { anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); doReturn(List.of(1L, 1L)).when(commands).dispatch(any(), any(), any()); when(commands.pexpiretime(any(byte[].class))).thenReturn(original.expiryMillis()); - when(commands.get(any(byte[].class))).thenReturn(original.pendingRegistry); + when(commands.get(any(byte[].class))).thenReturn(exactReadback); client = new AccountControlUiCoordination( () -> connection, new AcknowledgementRequirements(1, 1, 1000), catalog); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 88edc2d1c8..7ed7b9cfc2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -263,6 +263,862 @@ void dropOwnedPostgresSchema() { } } + @Test + void issuerOnlyPublishesRealBaselineAdvanceAndExactRetryWithoutAccountOrSqlMutation() { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + inTransaction(database, () -> sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER)); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + String unrelatedAccountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + UUID.randomUUID(); + assertThat(admin.get(ascii(unrelatedAccountKey))).isNull(); + byte[] unrelatedAccountBytes = ascii("test-only-unrelated-account-sentinel"); + admin.set(ascii(unrelatedAccountKey), unrelatedAccountBytes); + try { + var publisher = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, database.manager(), redisClient(new TrackedProvider(writer))); + var before = issuerOnlySqlRows(dsl); + var first = publisher.refreshCurrent(ACCOUNT_ISSUER); + assertThat(first.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(admin.get(ascii(key))) + .containsExactly(first.json().getBytes(StandardCharsets.UTF_8)); + assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + assertThat(publisher.refreshCurrent(ACCOUNT_ISSUER).outcome()) + .isEqualTo( + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(before); + inTransaction( + database, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", "issuer-only-" + UUID.randomUUID())); + var advancedRows = issuerOnlySqlRows(dsl); + var advanced = publisher.refreshCurrent(ACCOUNT_ISSUER); + assertThat(advanced.json()).isNotEqualTo(first.json()); + var exact = + inTransaction(database, () -> sources.readCurrentCanonicalIssuerSource(ACCOUNT_ISSUER)); + assertThat(advanced.json()) + .isEqualTo( + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.fromSource( + exact) + .toJson()); + assertThat(admin.get(ascii(key))) + .containsExactly(advanced.json().getBytes(StandardCharsets.UTF_8)); + assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + assertThat(publisher.refreshCurrent(ACCOUNT_ISSUER)) + .isEqualTo( + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher.Publication( + advanced.key(), + advanced.json(), + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY)); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(advancedRows); + assertThat(dsl.fetchSingle("SELECT count(*) FROM accounts").get(0, Long.class)).isZero(); + assertThat(admin.get(ascii(unrelatedAccountKey))).containsExactly(unrelatedAccountBytes); + assertThat(admin.pttl(ascii(unrelatedAccountKey))).isEqualTo(-1L); + } finally { + admin.del(ascii(key)); + admin.del(ascii(unrelatedAccountKey)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "MALFORMED", + "TTL", + "AHEAD", + "CONFLICTING_EVENT", + "MISSING_EVENT", + "CHANGED_DIGEST" + }) + void issuerOnlyRefusesRetainedRedisEvidenceWithoutRepair(String corruption) { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + inTransaction(database, () -> sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER)); + inTransaction( + database, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", "issuer-corruption-" + UUID.randomUUID())); + var sqlBefore = issuerOnlySqlRows(dsl); + var canonical = + inTransaction(database, () -> sources.readCurrentCanonicalIssuerSource(ACCOUNT_ISSUER)); + byte[] genuine = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.fromSource( + canonical) + .toJson() + .getBytes(StandardCharsets.UTF_8); + byte[] corrupt = + switch (corruption) { + case "MALFORMED" -> ascii("{not-json"); + case "TTL" -> genuine; + case "AHEAD" -> projectionPair(UUID.randomUUID(), 3L, 1L, "ahead-owner", "unused")[0]; + case "CONFLICTING_EVENT" -> + projectionPair(UUID.randomUUID(), 2L, 1L, "different-event", "unused")[0]; + case "MISSING_EVENT" -> + ascii( + new String(genuine, StandardCharsets.UTF_8) + .replace("\"sourceEvent\":", "\"unrecognizedEvent\":")); + case "CHANGED_DIGEST" -> + ascii( + new String(genuine, StandardCharsets.UTF_8) + .replace( + canonical.source().checkpoint().sourceEventDigest().orElseThrow(), + "sha256:" + "0".repeat(64))); + default -> throw new IllegalArgumentException(corruption); + }; + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + try { + admin.set(ascii(key), corrupt); + if ("TTL".equals(corruption)) admin.pexpire(ascii(key), 120_000L); + Long expiry = admin.pexpiretime(ascii(key)); + var publisher = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, database.manager(), redisClient(new TrackedProvider(writer))); + assertThatThrownBy(() -> publisher.refreshCurrent(ACCOUNT_ISSUER)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(key))).containsExactly(corrupt); + assertThat(admin.pexpiretime(ascii(key))).isEqualTo(expiry); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(sqlBefore); + } finally { + admin.del(ascii(key)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void issuerOnlyCommittedAdvanceBetweenSqlReadsRequiresExplicitLaterRetry() { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + inTransaction(database, () -> sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER)); + var baseline = + inTransaction(database, () -> sources.readCurrentCanonicalIssuerSource(ACCOUNT_ISSUER)); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + try { + var redis = redisClient(new TrackedProvider(writer)); + var changing = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, + new BeforeSecondTransactionManager( + database.manager(), + () -> + inTransaction( + database, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, + "SIGNER_COMPROMISE", + "issuer-race-" + UUID.randomUUID()))), + redis); + assertThatThrownBy(() -> changing.refreshCurrent(ACCOUNT_ISSUER)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issuer source changed during projection; explicit retry required"); + assertThat(admin.get(ascii(key))) + .containsExactly( + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.fromSource( + baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + var afterAdvance = issuerOnlySqlRows(dsl); + var stable = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher(sources, database.manager(), redis); + var retry = stable.refreshCurrent(ACCOUNT_ISSUER); + assertThat(retry.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(admin.get(ascii(key))) + .containsExactly(retry.json().getBytes(StandardCharsets.UTF_8)); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(afterAdvance); + assertThat(dsl.fetchSingle("SELECT count(*) FROM accounts").get(0, Long.class)).isZero(); + } finally { + admin.del(ascii(key)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void issuerOnlyMissingSqlSourceDeniesWithoutEnrollmentOrRedisWrite() { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + var original = issuerOnlySqlRows(dsl); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + var provider = new TrackedProvider(writer); + var publisher = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, database.manager(), redisClient(provider)); + assertThatThrownBy(() -> publisher.refreshCurrent(ACCOUNT_ISSUER)) + .isInstanceOf(IllegalStateException.class); + assertThat(provider.openedConnections()).isZero(); + assertThat(admin.get(ascii(key))).isNull(); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(original); + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issuerOnlyContradictorySqlHistoryDeniesBeforeRedisWithoutMutatingOriginal(boolean missing) { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + inTransaction(database, () -> sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER)); + inTransaction( + database, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", "issuer-negative-clone-" + UUID.randomUUID())); + var original = issuerOnlySqlRows(dsl); + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + var cloningManager = + new PlatformTransactionManager() { + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + var status = database.manager().getTransaction(definition); + try { + dsl.execute( + "CREATE TEMP TABLE account_authority_outbox_events ON COMMIT DROP AS SELECT * FROM " + + schema + + ".account_authority_outbox_events"); + assertThat( + dsl.fetchSingle( + "SELECT 'account_authority_outbox_events'::regclass::oid = " + + "'pg_temp.account_authority_outbox_events'::regclass::oid") + .get(0, Boolean.class)) + .isTrue(); + assertThat( + sources + .readCurrentCanonicalIssuerSource(ACCOUNT_ISSUER) + .source() + .generation()) + .isEqualTo(2L); + if (missing) { + assertThat(dsl.execute("DELETE FROM pg_temp.account_authority_outbox_events")) + .isEqualTo(1); + } else { + assertThat( + dsl.execute( + "UPDATE pg_temp.account_authority_outbox_events SET event_digest=?", + "sha256:" + "0".repeat(64))) + .isEqualTo(1); + } + return status; + } catch (RuntimeException | Error failure) { + database.manager().rollback(status); + throw failure; + } + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + database.manager().commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + database.manager().rollback(status); + } + }; + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + var provider = new TrackedProvider(writer); + var publisher = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, cloningManager, redisClient(provider)); + assertThatThrownBy(() -> publisher.refreshCurrent(ACCOUNT_ISSUER)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + assertThat(provider.openedConnections()).isZero(); + assertThat(admin.get(ascii(key))).isNull(); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(original); + assertThat( + inTransaction( + database, () -> sources.readCurrentCanonicalIssuerSource(ACCOUNT_ISSUER)) + .source() + .generation()) + .isEqualTo(2L); + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void issuerOnlyCannotSubstituteFixtureAdministratorForAccountCoordinationPrincipal() { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var sources = + new AccountAuthoritySourceEvidenceRepository( + dsl, + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl)); + inTransaction(database, () -> sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER)); + var original = issuerOnlySqlRows(dsl); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String key = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.keyForIssuer( + ACCOUNT_ISSUER); + try (var connection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = connection.sync(); + assertThat(admin.get(ascii(key))).isNull(); + var provider = new TrackedProvider(fixtureAdmin); + var publisher = + new net.firedevops.firemud.accountservice.service.session + .AccountIssuerGenerationProjectionPublisher( + sources, database.manager(), redisClient(provider)); + assertThatThrownBy(() -> publisher.refreshCurrent(ACCOUNT_ISSUER)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(provider.openedConnections()).isEqualTo(1); + assertThat(provider.trace(0)).doesNotContain("scriptLoad", "evalsha", "dispatch"); + assertThat(admin.get(ascii(key))).isNull(); + assertThat(issuerOnlySqlRows(dsl)).isEqualTo(original); + } finally { + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static Map>> issuerOnlySqlRows(DSLContext dsl) { + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + var rows = new java.util.TreeMap>>(); + for (String table : + dsl.fetch("SELECT tablename FROM pg_tables WHERE schemaname=? ORDER BY tablename", schema) + .getValues(0, String.class)) { + rows.put( + table, + dsl.fetch( + "SELECT to_jsonb(t)::text AS row,xmin::text AS xmin FROM " + + schema + + "." + + table + + " t ORDER BY 1,2") + .intoMaps()); + } + return rows; + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({"false, true", "true, true", "true, false"}) + void physicalOwnerAdvanceAcrossProjectionRoundTripNeverReturnsStaleSuccess( + boolean publish, boolean seedProjection) { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + try (var adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = adminConnection.sync(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + try { + var redis = redisClient(new TrackedProvider(writer)); + var stable = + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis); + var initialSource = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + byte[][] original = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(initialSource); + if (seedProjection) { + stable.publishCurrent(accountId); + assertProjectionBytes(admin, issuerKey, accountKey, original); + // Redis-only poisoning cannot authorize Account source advancement or an overwrite. + assertThat(initialSource.account().generation()).isEqualTo(1L); + byte[] aheadAccount = projectionPair(accountId, 1L, 2L, "unused", "ahead-cache")[1]; + admin.set(ascii(accountKey), aheadAccount); + assertThatThrownBy(() -> stable.publishCurrent(accountId)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(accountKey))).containsExactly(aheadAccount); + assertThat(admin.get(ascii(issuerKey))).containsExactly(original[0]); + assertThat(admin.pttl(ascii(accountKey))).isEqualTo(-1L); + assertThat( + inTransaction( + database, + () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId))) + .isEqualTo(initialSource); + assertThatThrownBy(() -> stable.observeCurrent(accountId)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + admin.set(ascii(accountKey), original[1]); + } else { + assertThat(publish).isTrue(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + } + var changingManager = + new BeforeSecondTransactionManager( + database.manager(), + () -> + commitPasswordResetAuthorityChange( + database, dsl, authorities, outbox, sources, accountId)); + var changing = + new AccountGameplayDelegationAuthorityProjection(sources, changingManager, redis); + assertThatThrownBy( + () -> { + if (publish) changing.publishCurrent(accountId); + else changing.observeCurrent(accountId); + }) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + var current = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + byte[][] advanced = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + assertThat(advanced[1]).isNotEqualTo(original[1]); + assertProjectionBytes(admin, issuerKey, accountKey, original); + assertThatThrownBy(() -> stable.observeCurrent(accountId)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + stable.publishCurrent(accountId); + assertProjectionBytes(admin, issuerKey, accountKey, advanced); + assertThat(stable.observeCurrent(accountId).accountGeneration()) + .isEqualTo(current.account().generation()); + } finally { + admin.del(ascii(issuerKey)); + admin.del(ascii(accountKey)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void olderCapturedProjectionCannotOverwriteNewerCommittedOwnerPublication() { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + try (var adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = adminConnection.sync(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + try { + var stableRedis = redisClient(new TrackedProvider(writer)); + var stable = + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), stableRedis); + stable.publishCurrent(accountId); + byte[][] baseline = stableRedis.readAuthorityProjections(accountId); + AtomicInteger interleavings = new AtomicInteger(); + TrackedProvider staleProvider = new TrackedProvider(writer); + var staleRedis = + redisClient( + () -> { + assertThat(interleavings.incrementAndGet()).isEqualTo(1); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + commitPasswordResetAuthorityChange( + database, dsl, authorities, outbox, sources, accountId); + stable.publishCurrent(accountId); + return staleProvider.openPinnedConnection(); + }); + var stale = + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), staleRedis); + assertThatThrownBy(() -> stale.publishCurrent(accountId)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(interleavings.get()).isEqualTo(1); + assertThat(staleProvider.openedConnections()).isEqualTo(1); + var current = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + byte[][] advanced = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + assertThat(advanced[1]).isNotEqualTo(baseline[1]); + assertProjectionBytes(admin, issuerKey, accountKey, advanced); + assertThat(stable.observeCurrent(accountId).accountGeneration()) + .isEqualTo(current.account().generation()); + } finally { + admin.del(ascii(issuerKey)); + admin.del(ascii(accountKey)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void resetThenLogoutProjectionPreservesExactCommittedSqlHistory() { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + var accounts = new AccountRepository(dsl, sources); + var resets = new AccountPasswordResetOperationRepository(dsl); + var logouts = new AccountLogoutAllOperationRepository(dsl); + var security = new AccountSecurityStateOperationRepository(dsl); + var logoutProducer = + new net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer( + accounts, + authorities, + sources, + outbox, + logouts, + new net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback( + outbox, resets, logouts, security), + dsl, + database.manager()); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + try (var adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = adminConnection.sync(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + try { + var redis = redisClient(new TrackedProvider(writer)); + var projection = + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis); + commitPasswordResetAuthorityChange(database, dsl, authorities, outbox, sources, accountId); + for (long expectedGeneration : List.of(2L, 3L)) { + if (expectedGeneration == 3L) { + var persisted = + inTransaction(database, () -> accounts.findByAccountUuid(accountId).orElseThrow()); + var expected = + inTransaction( + database, + () -> + authorities.readCompositeSnapshot( + ACCOUNT_ISSUER, accountId, List.of(), List.of())); + String tokenHash = "ab".repeat(32); + String digest = + net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest + .accountLogoutAll(accountId, "control-ui", tokenHash); + assertThat( + logoutProducer.commit( + UUID.randomUUID(), + 1, + digest, + "control-ui", + tokenHash, + persisted, + expected.account())) + .isEqualTo( + net.firedevops.firemud.accountservice.service + .AccountLogoutAllAuthorityEventProducer.LogoutAllResult + .LOGOUT_ALL_COMMITTED); + } + var current = + inTransaction( + database, + () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertThat(current.account().generation()).isEqualTo(expectedGeneration); + assertThat(current.account().checkpoint().sequence()).isEqualTo(expectedGeneration - 1L); + var tables = + List.of( + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_password_reset_operation_receipts", + "account_logout_all_operation_receipts"); + Map> committedRows = new java.util.LinkedHashMap<>(); + for (String table : tables) + committedRows.put( + table, + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)); + projection.publishCurrent(accountId); + byte[][] expectedBytes = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + assertProjectionBytes(admin, issuerKey, accountKey, expectedBytes); + assertThat(projection.observeCurrent(accountId).accountGeneration()) + .isEqualTo(expectedGeneration); + projection.publishCurrent(accountId); + assertProjectionBytes(admin, issuerKey, accountKey, expectedBytes); + for (String table : tables) + assertThat( + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(committedRows.get(table)); + } + } finally { + admin.del(ascii(issuerKey)); + admin.del(ascii(accountKey)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void committedResetSurvivesRedisAuthenticationFailureAndExactRetry() { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + Runnable exactReset = + commitPasswordResetAuthorityChange(database, dsl, authorities, outbox, sources, accountId); + var committed = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertThat(committed.account().generation()).isEqualTo(2L); + assertThat(committed.account().checkpoint().sequence()).isEqualTo(1L); + var tables = + List.of( + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_password_reset_operation_receipts", + "password_reset_token"); + Map> committedRows = new java.util.LinkedHashMap<>(); + for (String table : tables) + committedRows.put( + table, + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)); + assertThat(committedRows.get("account_password_reset_operation_receipts")).hasSize(1); + assertThat(committedRows.get("account_authority_outbox_events")).hasSize(1); + RedisClient writer = redisClient(writerUri); + RedisClient denied = + redisClient( + writerUri.getHost(), + writerUri.getPort(), + ACCOUNT_IDENTITY, + "deliberately-invalid-test-credential"); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + try (var adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE)) { + var admin = adminConnection.sync(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + try { + AtomicInteger deniedAttempts = new AtomicInteger(); + java.util.concurrent.atomic.AtomicBoolean authenticationRefused = + new java.util.concurrent.atomic.AtomicBoolean(); + var deniedRedis = + redisClient( + () -> { + deniedAttempts.incrementAndGet(); + try { + var unexpectedConnection = denied.connect(ByteArrayCodec.INSTANCE); + unexpectedConnection.close(); + throw new AssertionError( + "Invalid fixture credentials unexpectedly authenticated"); + } catch (RuntimeException failure) { + assertThat(failure) + .hasRootCauseInstanceOf( + io.lettuce.core.RedisCommandExecutionException.class) + .hasStackTraceContaining("WRONGPASS"); + authenticationRefused.set(true); + throw failure; + } + }); + var unavailable = + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), deniedRedis); + assertThatThrownBy(() -> unavailable.publishCurrent(accountId)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(deniedAttempts.get()).isEqualTo(1); + assertThat(authenticationRefused.get()).isTrue(); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + for (String table : tables) + assertThat( + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(committedRows.get(table)); + exactReset.run(); + var projection = + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), redisClient(new TrackedProvider(writer))); + projection.publishCurrent(accountId); + assertCurrentOwnerProjection(projection, admin, accountId, committed); + for (String table : tables) + assertThat( + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(committedRows.get(table)); + } finally { + admin.del(ascii(issuerKey)); + admin.del(ascii(accountKey)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + denied.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void unknownAccountProjectionFailsBeforeRedisAndLeavesOwnerRowsUnchanged() { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + createFreshAccount(database, sources); + UUID unknownAccount = UUID.randomUUID(); + assertThat(dsl.fetchCount(DSL.table("accounts"), DSL.field("account_uuid").eq(unknownAccount))) + .isZero(); + var tables = + List.of( + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_streams", + "account_authority_outbox_events"); + Map> before = new java.util.LinkedHashMap<>(); + for (String table : tables) { + before.put( + table, + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)); + } + RedisClient writer = redisClient(writerUri); + try { + TrackedProvider provider = new TrackedProvider(writer); + var projection = + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), redisClient(provider)); + assertThatThrownBy(() -> projection.publishCurrent(unknownAccount)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority snapshot requires its exact Account row"); + assertThatThrownBy(() -> projection.observeCurrent(unknownAccount)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority snapshot requires its exact Account row"); + assertThat(provider.openedConnections()).isZero(); + for (String table : tables) { + assertThat( + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(before.get(table)); + } + } finally { + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void accountCoordinationPrincipalRejectsRawEvalBeforeAnyScriptExecution() { + RedisClient writer = redisClient(writerUri); + try (var connection = writer.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(ACCOUNT_IDENTITY); + assertThatThrownBy( + () -> + commands.eval( + "return 1", io.lettuce.core.ScriptOutputType.INTEGER, new byte[0][])) + .isInstanceOf(io.lettuce.core.RedisCommandExecutionException.class) + .hasMessageContaining("NOPERM"); + assertThat(commands.ping()).isEqualTo("PONG"); + } finally { + writer.shutdown(); + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenantBound) @@ -438,7 +1294,7 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(issuerRegressionConnection)) - .containsExactly("aclWhoami", "scriptLoad", "evalsha", "close"); + .containsExactly("aclWhoami", "get", "scriptLoad", "evalsha", "close"); assertThat(admin.get(ascii(issuerKey))).containsExactly(initialProjection[0]); assertThat(admin.get(ascii(accountKey))).containsExactly(accountBeforeIssuerRegression); assertThat(admin.get(ascii(accountKey))).containsExactly(initialProjection[1]); @@ -453,7 +1309,8 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(equalIssuerConflictConnection)) - .doesNotContain("dispatch", "get"); + .contains("get") + .doesNotContain("dispatch"); assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); byte[][] equalAccountConflict = @@ -470,6 +1327,114 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant .doesNotContain("dispatch"); assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + // The real current issuer owner refuses malformed retained evidence, even when a + // newer canonical candidate would pass the old Lua outer-shape/generation checks. + byte[][] newerProjection = projectionPair(accountId, 8L, 8L, "issuer-next", "account-next"); + var malformedIssuer = + (tools.jackson.databind.node.ObjectNode) JSON.readTree(initialProjection[0]); + // Issuer projection canonical JSON is the owner's fixed insertion order, not RFC8785. + assertThat(JSON.writeValueAsBytes(malformedIssuer)).containsExactly(initialProjection[0]); + malformedIssuer.put("sourceEvent", "not-a-canonical-issuer-event"); + var originalIssuer = JSON.readTree(initialProjection[0]); + for (String field : + List.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence", + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest")) { + assertThat(malformedIssuer.get(field)).isEqualTo(originalIssuer.get(field)); + } + byte[] malformedIssuerBytes = JSON.writeValueAsBytes(malformedIssuer); + admin.set(ascii(issuerKey), malformedIssuerBytes); + int malformedIssuerConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, newerProjection[0], newerProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(malformedIssuerConnection)) + .containsExactly("aclWhoami", "get", "close"); + assertThat(admin.get(ascii(issuerKey))).containsExactly(malformedIssuerBytes); + assertThat(admin.get(ascii(accountKey))).containsExactly(initialProjection[1]); + assertThat(admin.pttl(ascii(issuerKey))).isEqualTo(-1L); + admin.set(ascii(issuerKey), initialProjection[0]); + + admin.pexpire(ascii(issuerKey), 60_000L); + Long originalIssuerExpiry = admin.pexpiretime(ascii(issuerKey)); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, newerProjection[0], newerProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + assertThat(admin.pexpiretime(ascii(issuerKey))).isEqualTo(originalIssuerExpiry); + admin.set(ascii(issuerKey), initialProjection[0]); + + // Mutate through an independent fixture-admin connection after the Java read, exactly + // before the actual Lua CAS. ABSENT, PRESENT and VERIFY must all refuse without overwrite. + byte[][] concurrentProjection = + projectionPair(accountId, 9L, 9L, "issuer-concurrent", "account-concurrent"); + for (String mode : List.of("ABSENT", "PRESENT", "VERIFY")) { + if (mode.equals("ABSENT")) admin.del(ascii(issuerKey)); + else admin.set(ascii(issuerKey), initialProjection[0]); + byte[][] candidate = mode.equals("VERIFY") ? initialProjection : newerProjection; + int raceConnection = writerProvider.openedConnections(); + writerProvider.beforeNextEval(() -> admin.set(ascii(issuerKey), concurrentProjection[0])); + assertThatThrownBy( + () -> redis.publishAuthorityProjections(accountId, candidate[0], candidate[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(raceConnection)) + .containsExactly("aclWhoami", "get", "scriptLoad", "evalsha", "close"); + assertThat(admin.get(ascii(issuerKey))).containsExactly(concurrentProjection[0]); + assertThat(admin.get(ascii(accountKey))).containsExactly(initialProjection[1]); + assertThat(admin.pttl(ascii(issuerKey))).isEqualTo(-1L); + } + admin.set(ascii(issuerKey), initialProjection[0]); + assertThat( + redis.publishAuthorityProjections(accountId, newerProjection[0], newerProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishAuthorityProjections(accountId, newerProjection[0], newerProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertProjectionBytes(admin, issuerKey, accountKey, newerProjection); + // Restore only these test-owned keys for the existing independent corruption vectors. + admin.set(ascii(issuerKey), initialProjection[0]); + admin.set(ascii(accountKey), initialProjection[1]); + + // A corrupt or expiring stored projection is not permission to replace it. + byte[] malformedAccountProjection = ascii("{not-a-canonical-projection}"); + admin.set(ascii(accountKey), malformedAccountProjection); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(accountKey))).containsExactly(malformedAccountProjection); + assertThat(admin.get(ascii(issuerKey))).containsExactly(initialProjection[0]); + admin.set(ascii(accountKey), initialProjection[1]); + admin.pexpire(ascii(accountKey), 60_000L); + Long originalAccountProjectionExpiry = admin.pexpiretime(ascii(accountKey)); + assertThat(admin.pttl(ascii(accountKey))).isPositive(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + assertThat(admin.pexpiretime(ascii(accountKey))).isEqualTo(originalAccountProjectionExpiry); + assertThat(admin.pttl(ascii(accountKey))).isPositive(); + admin.set(ascii(accountKey), initialProjection[1]); + assertThat(admin.pttl(ascii(accountKey))).isEqualTo(-1L); + byte[][] signedBigintBoundary = projectionPair( accountId, Long.MAX_VALUE, Long.MAX_VALUE, "issuer-bigint-max", "account-bigint-max"); @@ -503,7 +1468,7 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(boundaryRegressionConnection)) - .doesNotContain("dispatch", "get"); + .containsExactly("aclWhoami", "get", "scriptLoad", "evalsha", "close"); assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); TrackedProvider wrongRoleProvider = new TrackedProvider(fixtureAdmin); @@ -3073,7 +4038,7 @@ private static UUID createFreshAccount( }); } - private static void commitPasswordResetAuthorityChange( + private static Runnable commitPasswordResetAuthorityChange( TestContext context, DSLContext dsl, AccountAuthorityGenerationRepository authorities, @@ -3136,14 +4101,19 @@ private static void commitPasswordResetAuthorityChange( null, null, context.manager()); - inTransaction( - context, - () -> { - accountService.completePasswordReset( - new CompletePasswordResetRequest( - rawToken, "active-transition-password-" + UUID.randomUUID())); - return null; - }); + var request = + new CompletePasswordResetRequest( + rawToken, "active-transition-password-" + UUID.randomUUID()); + Runnable exactReset = + () -> + inTransaction( + context, + () -> { + accountService.completePasswordReset(request); + return null; + }); + exactReset.run(); + return exactReset; } private String writeResponseKeyring() throws Exception { @@ -3591,6 +4561,13 @@ public void rollback(org.springframework.transaction.TransactionStatus status) { private static final class TrackedProvider implements AccountCoordinationPinnedConnectionProvider { private final RedisClient client; + private Runnable beforeNextEval; + + private void beforeNextEval(Runnable action) { + if (beforeNextEval != null) throw new IllegalStateException("Unconsumed test CAS hook"); + beforeNextEval = Objects.requireNonNull(action); + } + private final List> traces = new ArrayList<>(); private final List> dispatchedCommands = new ArrayList<>(); @@ -3627,7 +4604,7 @@ private List dispatchedCommands(int index) { } @SuppressWarnings("unchecked") - private static StatefulRedisConnection observe( + private StatefulRedisConnection observe( StatefulRedisConnection delegate, List trace, List dispatches) { @@ -3660,6 +4637,11 @@ private static StatefulRedisConnection observe( .contains(name)) { trace.add(name); } + if (name.equals("evalsha") && beforeNextEval != null) { + Runnable action = beforeNextEval; + beforeNextEval = null; + action.run(); + } return invoke(commands, commandMethod, commandArguments); }); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java index 9d7c868ff2..423f08d7b2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; import java.nio.file.Path; import java.util.Objects; import java.util.UUID; @@ -14,8 +16,11 @@ import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; import net.firedevops.firemud.accountservice.service.auth.AccountCredentialAbuseCacheFixture; import net.firedevops.firemud.accountservice.service.auth.AccountCredentialAbuseService; +import net.firedevops.firemud.accountservice.service.auth.AccountCredentialAbuseSubjectKeys; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.testcontainers.containers.GenericContainer; @@ -43,6 +48,11 @@ class AccountGlobalControlUiIssuancePostgresIntegrationTest { @Container static GenericContainer credentialCache = AccountCredentialAbuseCacheFixture.container(); + @BeforeAll + static void awaitMappedOwnerJdbc() { + net.firedevops.firemud.test.PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @TempDir Path temporary; @Test @@ -191,6 +201,156 @@ void accountSourceObservationCannotUseHistoricalNonrestrictedBirthAsCurrentAutho fixture.assertNoIssuance(); } + @Test + void consumedOtpCannotAuthenticateASecondNewPrimaryAttempt() throws Exception { + var fixture = fixture(); + var account = fixture.createGlobalAccount(PASSWORD); + fixture.installGlobalOtp(account, OTP); + assertThat( + fixture + .tx( + () -> + fixture.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), OTP)) + .accountId()) + .isEqualTo(account.getAccountUuid()); + assertThat(fixture.challenges.findByAccountId(account.getId())).isEmpty(); + var before = retainedOwners(fixture); + + // A new primary attempt, not recovery of an original issuance request. + assertInvalidCredentials( + () -> + fixture.tx( + () -> + fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP))); + + assertThat(fixture.challenges.findByAccountId(account.getId())).isEmpty(); + assertThat(retainedOwners(fixture)).isEqualTo(before); + assertNoMembership(fixture, account); + fixture.assertNoIssuance(); + } + + @Test + void invalidPasswordAndOtpCommitOnlyChallengeFailuresAndRealSharedAbuseAccounting() + throws Exception { + var admin = + RedisClient.create( + RedisURI.Builder.redis(credentialCache.getHost(), credentialCache.getMappedPort(6379)) + .withTimeout(java.time.Duration.ofSeconds(2)) + .build()); + try (var inspector = admin.connect(); + var abuse = new AccountCredentialAbuseCacheFixture(credentialCache)) { + var fixture = fixture(abuse.service()); + var account = fixture.createGlobalAccount(PASSWORD); + fixture.installGlobalOtp(account, OTP); + var ownersBefore = retainedOwners(fixture); + var challengeBefore = challengeContent(fixture, account); + var oldKeys = + new java.util.HashSet<>( + inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "subject:*")); + try (var ignored = + AccountControlUiOwnerSourcesFixture.withPeer( + AccountControlUiOwnerSourcesFixture.CALLER)) { + int failures = 0; + for (String secret : java.util.List.of("incorrect-password", "incorrect-otp")) { + var request = + new AccountControlUiIssuanceService.AccountSignInRequest( + UUID.randomUUID(), + account.getEmail(), + secret, + UUID.randomUUID(), + new SourceContext("192.0.2.41")); + assertInvalidCredentials(() -> fixture.service.issueAccount(request)); + failures++; + assertThat( + fixture + .challenges + .findByAccountId(account.getId()) + .orElseThrow() + .getInvalidAttemptCount()) + .isEqualTo(failures); + assertThat(challengeContent(fixture, account)).isEqualTo(challengeBefore); + assertThat(retainedOwners(fixture)).isEqualTo(ownersBefore); + assertNoMembership(fixture, account); + fixture.assertNoIssuance(); + + var keys = inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "subject:*"); + keys.removeAll(oldKeys); + // The fixture uses a unique policy scope; only this new attempt creates these buckets. + // Sum across retained windows so a wall-clock window boundary cannot lose accounting. + for (String subject : java.util.List.of("source", "candidate")) { + var subjectKeys = + keys.stream().filter(key -> key.contains(":" + subject + ":")).toList(); + assertThat(subjectKeys).isNotEmpty(); + long actualFailures = 0; + for (String key : subjectKeys) { + String[] fields = inspector.sync().get(key).split("\\|", -1); + assertThat(fields).hasSize(4); + assertThat(fields[0]).isEqualTo("v1"); + assertThat(fields[3]).isEqualTo("0000000000000000"); + actualFailures += Long.parseLong(fields[2]); + assertThat(inspector.sync().pttl(key)).isPositive(); + } + assertThat(actualFailures).isEqualTo(failures); + } + } + } + } finally { + admin.shutdown(); + } + } + + private static void assertInvalidCredentials(Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo("AUTH_INVALID_CREDENTIALS")); + } + + private static java.util.Map challengeContent( + AccountControlUiOwnerSourcesFixture fixture, Account account) { + var row = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT * FROM account_email_login_challenge WHERE account_id = ?", + account.getId())) + .intoMap(); + // These two fields are the intended, committed failed-attempt change. + row.remove("invalid_attempt_count"); + row.remove("updated_at"); + return row; + } + + private static java.util.Map>> + retainedOwners(AccountControlUiOwnerSourcesFixture fixture) { + var result = + new java.util.LinkedHashMap>>(); + for (String table : + java.util.List.of( + "accounts", + "account_global_role_sources", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_events", + "account_platform_restriction_current_projections", + "account_tenant_membership", + "account_control_ui_issuance_operations", + "account_control_ui_response_envelopes")) { + result.put( + table, + fixture + .dsl + .fetch( + "SELECT to_jsonb(t)::text AS content, xmin::text AS row_version FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()); + } + return result; + } + private AccountControlUiOwnerSourcesFixture fixture() throws Exception { return new AccountControlUiOwnerSourcesFixture( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java index c20b71171a..c87ed9075c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; +import net.firedevops.firemud.accountservice.service.auth.AccountCredentialAbuseCacheFixture; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.TestContainerImages; import org.apache.catalina.startup.Tomcat; @@ -112,6 +113,10 @@ class AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest { "first-invoice-primary", "6379"); + // Dedicated run-owned Cache/Rate-Limit instance, never the Coordination Redis endpoint. + @Container + static final GenericContainer credentialCache = AccountCredentialAbuseCacheFixture.container(); + @TempDir Path temporary; @Test @@ -338,14 +343,16 @@ void billingReauthenticationDoesNotHoldIssuerSourceAcrossOtpVerificationAndRolls @Test void actualHttpsOwnerConsentScaAndExactSignedCompletionGrantAuthorityOnlyAfterReadback() throws Exception { - try (var owners = - new AccountControlUiOriginalOrderFixture( - postgres.getJdbcUrl(), - postgres.getUsername(), - postgres.getPassword(), - redis.getHost(), - redis.getMappedPort(6379), - temporary)) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var owners = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + abuse.service())) { var issued = owners.issueCertifiedAccount(PASSWORD); var hosting = CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( @@ -757,14 +764,16 @@ void actualHttpsOwnerConsentScaAndExactSignedCompletionGrantAuthorityOnlyAfterRe @Test void delayedOriginalConfirmationLosesToExplicitPreRowRenewalWithoutConsumingItsProof() throws Exception { - try (var owners = - new AccountControlUiOriginalOrderFixture( - postgres.getJdbcUrl(), - postgres.getUsername(), - postgres.getPassword(), - redis.getHost(), - redis.getMappedPort(6379), - temporary)) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var owners = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + abuse.service())) { var issued = owners.issueCertifiedAccount(PASSWORD); var hosting = CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java index 5a122c2d0b..ba7d90a1a5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.auth.AccountCredentialAbuseCacheFixture; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture.IssuedAccount; import net.firedevops.firemud.accountservice.service.session.AccountHostingSubscriptionTerminalResolutionService.Input; @@ -89,12 +90,17 @@ class AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegration "terminal-resolution-primary", "6379"); + // Dedicated run-owned Cache/Rate-Limit instance, never the Coordination Redis endpoint. + @Container + static final GenericContainer credentialCache = AccountCredentialAbuseCacheFixture.container(); + @TempDir Path temporary; @Test void actualAccountAndFreshOtpCommitOneAtomicCancellationAndAuthenticatedReplay() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var issued = failed.issued(); var hosting = failed.hosting(); @@ -149,7 +155,8 @@ void actualAccountAndFreshOtpCommitOneAtomicCancellationAndAuthenticatedReplay() @Test void wrongPrimaryCredentialRetainsFinancialFenceAndUnconsumedOtp() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var issued = failed.issued(); var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); @@ -172,7 +179,8 @@ void wrongPrimaryCredentialRetainsFinancialFenceAndUnconsumedOtp() throws Except @Test void lateBillingSqlFailureRollsBackCancellationAndOtpThenSameOtpSucceeds() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var issued = failed.issued(); var hosting = failed.hosting(); @@ -212,7 +220,8 @@ void lateBillingSqlFailureRollsBackCancellationAndOtpThenSameOtpSucceeds() throw @Test void missingFailedOperationCopyRejectsBeforeCurrentCasAndRollsBackAuditJournalAndOtp() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var issued = failed.issued(); var hosting = failed.hosting(); @@ -257,7 +266,8 @@ void missingFailedOperationCopyRejectsBeforeCurrentCasAndRollsBackAuditJournalAn @Test void genericAccountAuthorityAdvanceDuringSdkReadMakesSourceUnavailableAndKeepsOtp() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var issued = failed.issued(); var hosting = failed.hosting(); @@ -308,7 +318,8 @@ void genericAccountAuthorityAdvanceDuringSdkReadMakesSourceUnavailableAndKeepsOt @Test void otherCertifiedAccountsFreshOtpCannotAuthorizeBillingOwnerAndConsumptionRollsBack() throws Exception { - try (var accountOwners = accountOwners()) { + try (var abuse = new AccountCredentialAbuseCacheFixture(credentialCache); + var accountOwners = accountOwners(abuse)) { var failed = failedHosting(accountOwners); var other = accountOwners.issueCertifiedAccount("test-only-other-account-password"); assertThat(other.actors().authenticateAccount(other.compact()).accountId()) @@ -325,14 +336,16 @@ void otherCertifiedAccountsFreshOtpCannotAuthorizeBillingOwnerAndConsumptionRoll } } - private AccountControlUiOriginalOrderFixture accountOwners() throws Exception { + private AccountControlUiOriginalOrderFixture accountOwners( + AccountCredentialAbuseCacheFixture abuse) throws Exception { return new AccountControlUiOriginalOrderFixture( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), redis.getHost(), redis.getMappedPort(6379), - temporary); + temporary, + abuse.service()); } private static FailedHosting failedHosting(AccountControlUiOriginalOrderFixture accountOwners) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java index dab77470c5..ec1b49ea70 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java @@ -6,8 +6,15 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.protobuf.Message; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Attributes; import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; import java.math.BigInteger; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -39,7 +46,15 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.IntConsumer; import java.util.function.Supplier; +import javax.net.ssl.SSLSession; import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountjwtmaterializer.CanonicalMaterializerDriver; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; @@ -56,6 +71,8 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; import net.firedevops.firemud.accountservice.repository.AccountJwtValidatorInventoryRepository; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -132,6 +149,86 @@ void dropRunOwnedSchemas() { schemas.clear(); } + @Test + void actualMaterializerPersistsOriginalGenerationAndRecoversWithoutLegacyReadinessRpc() + throws Exception { + Harness harness = harness(); + CanonicalMaterializerDriver materializer = + new CanonicalMaterializerDriver( + harness.binding.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harness.binding.bindingDigest(), + harness.binding.configRevision(), + SECRET_UID, + harness::invokeMaterializerOwner); + assertThat(materializer.observe()).isEqualTo("SECRET_OBSERVATION_RECORDED"); + assertThat(materializer.patches()).isZero(); + assertThat(harness.count("account_jwt_signer_secret_observations")).isEqualTo(1); + materializer.loseNextPatchReply(); + // The real materializer can retain generation even if later readiness remains unavailable. + assertThatThrownBy(materializer::reconcile) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account-authorized JWT materialization could not be reconciled"); + assertThat(harness.lastMaterializerOwnerError.get()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(materializer.patches()).isEqualTo(1); + assertThat(harness.count("account_jwt_signer_generation_results")).isEqualTo(1); + byte[] originalPending = materializer.pendingBundle(); + try { + Files.write(harness.privateMount.resolve("pending.key"), originalPending); + harness.result = + harness.tx( + () -> + harness.desired.readCurrentGenerationResult( + harness.binding.accountBinding(), harness.trust)); + harness.readinessFixture = + new AccountJwtPreparedPublicationPostgresFixture( + harness.binding.accountBinding(), + harness.trust, + harness.result, + API_DIGEST, + API_REVISION); + harness.prepublication.prepublishCurrentGeneration(); + harness.mountAndObserve(); + // Each invocation constructs a new Materializer and client adapter; only durable owner + // state and the independently retained controlled Secret survive. + assertThatThrownBy(materializer::reconcile).isInstanceOf(IllegalStateException.class); + assertThat(harness.lastMaterializerOwnerError.get()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(materializer.patches()).isEqualTo(1); + assertThat(materializer.pendingBundle()).isEqualTo(originalPending); + assertThat(harness.count("account_jwt_signer_generation_results")).isEqualTo(1); + assertThat(harness.count("account_jwt_signer_secret_observations")).isEqualTo(1); + assertThat(harness.count("account_jwt_signer_promotion_operations")).isZero(); + harness.readinessFixture.completeReadiness( + harness.readiness, + harness.transaction, + harness.dsl, + harness.privateMount, + harness.publicMount); + // Secret CAS precedes asynchronous mount delivery; the owner remains fail-closed. + assertThatThrownBy(materializer::reconcile) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat(harness.lastMaterializerOwnerError.get()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(materializer.patches()).isEqualTo(2); + byte[] current = materializer.currentBundle(); + try { + Files.write(harness.privateMount.resolve("current.key"), current); + } finally { + java.util.Arrays.fill(current, (byte) 0); + } + assertThat(materializer.reconcile()).isEqualTo("PRIVATE_PROMOTION_RECEIPT_RECORDED"); + assertThat(materializer.patches()).isEqualTo(2); + assertThat(harness.materializerResponses).noneMatch(value -> value.contains("PRIVATE KEY")); + JsonMapper mapper = JsonMapper.builder().build(); + String privateKey = mapper.readTree(originalPending).path("privateKeyPkcs8").asText(); + assertThat(privateKey).isNotEmpty(); + assertThat(harness.materializerResponses).noneMatch(value -> value.contains(privateKey)); + } finally { + java.util.Arrays.fill(originalPending, (byte) 0); + } + } + @Test void initialPrepublicationCutsRemainUnavailableUntilExactFailedReceiptReconciliation() throws Exception { @@ -681,6 +778,10 @@ private static final class Harness { private final AccountJwtSignerBootstrapCoordinator coordinator; private final AccountPublicJwksReadService publicRead; private final ControlledTransport transport; + private final AccountJwtSignerMaterializerTrustBinding materializerProvider; + private final DefaultListableBeanFactory ownerBeans; + private final List materializerResponses = new java.util.ArrayList<>(); + private final AtomicReference lastMaterializerOwnerError = new AtomicReference<>(); private final AccountJwtJwksConfigMapClient configMap; private final Path privateMount; private final Path publicMount; @@ -707,7 +808,8 @@ private Harness(DataSource dataSource, String schema, Path directory) throws Exc transaction = new TransactionTemplate(manager); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); String peer = "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; - List pins = List.of("d".repeat(64)); + List pins = + List.of(sha256("controlled-materializer-spki".getBytes(StandardCharsets.UTF_8))); String digest = AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( "trust-r1", @@ -732,6 +834,7 @@ private Harness(DataSource dataSource, String schema, Path directory) throws Exc trust = new TrustFence(CLUSTER_UID, NAMESPACE_UID, digest, "trust-r1"); var materializer = mock(AccountJwtSignerMaterializerTrustBinding.class); when(materializer.current()).thenReturn(Optional.of(binding)); + materializerProvider = materializer; ParsedBinding parsed = new ParsedBinding( API_REVISION, @@ -792,6 +895,7 @@ private Harness(DataSource dataSource, String schema, Path directory) throws Exc }); var beans = new DefaultListableBeanFactory(); beans.registerSingleton("controlledInventory", inventory); + ownerBeans = beans; coordinator = new AccountJwtSignerBootstrapCoordinator( materializer, @@ -807,9 +911,91 @@ private Harness(DataSource dataSource, String schema, Path directory) throws Exc new AccountPublicJwksReadService( source, new AccountPublicJwksReadWorkloadGuard(materializer, api, binding.namespace())); + ownerBeans.registerSingleton("bootstrapCoordinator", coordinator); coordinator.enrollOnce(); } + @SuppressWarnings({"unchecked", "rawtypes"}) + private Message invokeMaterializerOwner(String method, Message request) { + var service = + new AccountJwtSignerMaterializationService( + new AccountJwtSignerDesiredStateRepository(dsl), + readiness, + materializerProvider, + manager, + ownerBeans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class), + ownerBeans.getBeanProvider(AccountJwtValidatorInventorySource.class)); + AtomicReference value = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + AtomicBoolean complete = new AtomicBoolean(); + StreamObserver observer = + new StreamObserver() { + public void onNext(Message response) { + assertThat(value.compareAndSet(null, response)).isTrue(); + materializerResponses.add(response.toString()); + } + + public void onError(Throwable failure) { + error.set(failure); + } + + public void onCompleted() { + complete.set(true); + } + }; + ServerCall call = mock(ServerCall.class); + SSLSession session = mock(SSLSession.class); + var certificate = mock(java.security.cert.X509Certificate.class); + var key = mock(java.security.PublicKey.class); + when(key.getEncoded()) + .thenReturn("controlled-materializer-spki".getBytes(StandardCharsets.UTF_8)); + when(certificate.getPublicKey()).thenReturn(key); + try { + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, binding.expectedPeerUri()))); + when(session.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + } catch (Exception failure) { + throw new AssertionError(failure); + } + when(call.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + new AccountJwtSignerMaterializerTlsInterceptor(materializerProvider) + .interceptCall( + call, + new Metadata(), + (intercepted, headers) -> { + switch (method) { + case "enroll" -> + service.enrollBootstrap((EnrollBootstrapRequest) request, observer); + case "generation" -> + service.getCurrentGenerationRequest( + (GetCurrentGenerationRequestRequest) request, observer); + case "observe" -> + service.recordSecretObservation( + (RecordSecretObservationRequest) request, observer); + case "record" -> + service.recordGenerationResult( + (RecordGenerationResultRequest) request, observer); + case "promote" -> + service.recordPrivatePromotionResult( + (RecordPrivatePromotionResultRequest) request, observer); + case "promotion" -> + service.getCurrentPromotionRequest( + (GetCurrentPromotionRequestRequest) request, observer); + default -> throw new AssertionError("Unexpected materializer operation"); + } + return new ServerCall.Listener<>() {}; + }); + if (error.get() != null) { + lastMaterializerOwnerError.set(Status.fromThrowable(error.get()).getCode()); + throw Status.fromThrowable(error.get()).asRuntimeException(); + } + assertThat(complete.get()).isTrue(); + return java.util.Objects.requireNonNull(value.get()); + } + private void generate() throws Exception { request = tx(() -> desired.ensureCurrentGenerationRequest(binding.accountBinding(), trust)); String prior = result == null ? "12" : "14"; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index cf08297130..4eaf36bb80 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -887,6 +887,96 @@ void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndD } } + @Test + void settledOriginalDraftDoesNotReleaseIndependentPublicationSourceOrder() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var draft = proof.original(); + // Original owner evidence is stipulated here, not authenticated World transport. + f.tx( + () -> { + f.fences.reserve(draft); + f.fences.claimCommitOrder(draft); + for (var owner : draft.requiredOwners()) { + f.fences.recordOwnerReadback( + draft, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + draft.operationId(), + draft.commitId(), + draft.fenceId(), + draft.inputDigest(), + draft.canonicalBytes(), + new byte[] {1})); + } + return null; + }); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_draft_authorization_is_settled(?)", draft.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var publication = + service.authorize(issued.compact(), proof.selection(), issued.environment()); + assertThat(publication.operationId()).isNotEqualTo(draft.operationId()); + assertThat(publication.fenceId()).isNotEqualTo(draft.fenceId()); + var retained = + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS evidence, xmin::text AS row_version " + + "FROM account_selected_publication_authorizations t ORDER BY to_jsonb(t)::text") + .intoMaps(); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), publication.sources(), new byte[] {7}); + for (int attempt = 0; attempt < 2; attempt++) { + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.inspectSourceChange(change).status())).isEqualTo("WAITING"); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + assertThat( + service + .authorize(issued.compact(), proof.selection(), issued.environment()) + .canonicalBytes()) + .containsExactly(publication.canonicalBytes()); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text AS evidence, xmin::text AS row_version " + + "FROM account_selected_publication_authorizations t ORDER BY to_jsonb(t)::text") + .intoMaps()) + .isEqualTo(retained); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + } + } + } + @Test void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() throws Exception { try (var fixture = fixture()) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java index 1fa9e678d0..4676b67b5f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -755,6 +755,34 @@ void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { } finally { missing.dsl().execute("ALTER TABLE account_security_state_operations ENABLE TRIGGER USER"); } + // Storage rejection does not replace owner readback verification of a missing receipt. + assertThatThrownBy( + () -> + tx( + missing, + () -> + sourceReadback(missing) + .requireCurrentLatest( + new AccountRepository(missing.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + missing.generations().read(seed.source().scope())))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx( + missing, + () -> { + sourceReadback(missing) + .requireRetainedEvent( + new AccountRepository(missing.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + event, + missing.generations().read(seed.source().scope())); + return null; + })) + .isInstanceOf(IllegalStateException.class); assertPostgresCheckViolation( () -> missing diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java index d8c9ba3a53..78dcae9f90 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java @@ -58,8 +58,10 @@ import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -329,6 +331,124 @@ void verifiedTerminalSettlesEachSharedSourceHolderAndUnblocksOnlyAfterBoth() thr assertThat(c.tx(() -> repository.readPending(null, 10))).isEmpty(); } + @Test + void creationTerminalCannotReleaseSharedSourceBeforeEveryOriginalDraftOwnerSettles() + throws Exception { + Context c = context(); + Fixture fixture = fixture(c); + List sources = controlledSources(c, fixture); + seedSerializationRows(c, sources); + var repository = repository(c); + var creation = + c.tx(() -> repository.acquireLocked(fixture.intent(), fixture.admitted(), sources)); + var draftRepository = new DraftAuthorizationFenceRepository(c.dsl); + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-creation", + 2, + "test-creation", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test/base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + // Controlled shared source bytes and owner results, not creator or remote publisher authority. + var draft = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + fixture.intent().initiatingAccountId(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + sources.stream() + .filter(x -> x.kind() == SourceKind.ISSUER) + .findFirst() + .orElseThrow())); + c.tx(() -> draftRepository.reserve(draft)); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), + sources, + "shared creation and draft source change".getBytes(StandardCharsets.UTF_8)); + assertThat(c.tx(() -> draftRepository.requestSourceChange(change))).isFalse(); + String originalXmin = xmin(c, creation.creationOperationId()); + var notCreated = terminalEvidence(creation.outcomeBinding(), Outcome.NOT_CREATED); + var verified = readTerminal(notCreated, creation.outcomeBinding()); + c.tx(() -> repository.settleLocked(creation, verified)); + assertThat(c.tx(() -> draftRepository.sourceMutationPermitted(change))).isFalse(); + assertWriterGateDenied(c, "ISSUER:firemud-account-service"); + var required = draft.requiredOwners(); + assertThat(required).hasSizeGreaterThan(1); + int settled = 0; + for (var owner : required) { + var readback = + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, + draft.operationId(), + draft.commitId(), + draft.fenceId(), + draft.inputDigest(), + draft.canonicalBytes(), + new byte[] {12}); + c.tx( + () -> { + draftRepository.recordOwnerReadback(draft, readback); + return null; + }); + settled++; + if (settled < required.size()) { + assertThat(c.tx(() -> draftRepository.sourceMutationPermitted(change))).isFalse(); + assertWriterGateDenied(c, "ISSUER:firemud-account-service"); + } + } + assertThat(c.tx(() -> draftRepository.sourceMutationPermitted(change))).isTrue(); + assertWriterGateAllowed(c, "ISSUER:firemud-account-service"); + c.tx( + () -> { + draftRepository.markSourceCommitted(change); + return null; + }); + assertThat(c.tx(() -> draftRepository.inspectSourceChange(change).status())) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + c.tx( + () -> + repository + .readOriginal(creation.creationOperationId()) + .orElseThrow() + .canonicalBytes())) + .containsExactly(creation.canonicalBytes()); + assertThat(xmin(c, creation.creationOperationId())).isEqualTo(originalXmin); + assertThat(c.tx(() -> repository.settleLocked(creation, verified).canonicalBytes())) + .containsExactly(notCreated.canonicalBytes()); + } + @Test void failedOrMismatchedTerminalReadsCannotSettleAnOriginalHolder() throws Exception { Context c = context(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClientsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClientsTest.java new file mode 100644 index 0000000000..d3ebf403f7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateDelegationClientsTest.java @@ -0,0 +1,345 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetSnapshot; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled composition/byte-binding proof only, not genuine source/owner or mTLS qualification. + */ +class AccountCharacterCreateDelegationClientsTest { + private static final String NAMESPACE = "creation-outbound-proof"; + private static final Instant NOW = Instant.parse("2026-10-24T00:00:00Z"); + private final AccountCharacterCreateIntent intent = + AccountCharacterCreateTestActions.intent( + NAMESPACE, UUID.randomUUID(), UUID.randomUUID(), NOW.plusSeconds(300)); + private final AccountCharacterCreateRepository.Protection protection = + new AccountCharacterCreateRepository.Protection( + intent, UUID.randomUUID(), 7L, NOW, new byte[] {1, 2}, new byte[] {3, 4}); + private final ReadOriginalCharacterCreateProtectionResponse account = + AccountCharacterCreateDelegationBindings.account(NAMESPACE, intent, protection); + private final AccountCharacterCreateGameSessionClient gameSession = + mock(AccountCharacterCreateGameSessionClient.class); + private final AccountCharacterCreateWorldClient world = + mock(AccountCharacterCreateWorldClient.class); + private final AccountCharacterCreateEntityClient entity = + mock(AccountCharacterCreateEntityClient.class); + private final AccountCharacterCreateOwnerClients resolver = + AccountCharacterCreateOwnerClients.unavailable(); + + @Test + void resolverStaysUnavailableDespiteConcreteDelegationComposition() { + var clients = clients(); + assertThatThrownBy( + () -> + clients.resolvePublicProduction( + NAMESPACE, + mock(AccountCharacterCreatePrincipal.class), + intent.connectScopeId())) + .hasMessageContaining("UNAVAILABLE"); + assertThatThrownBy(() -> clients.requireExactOriginalSource(intent)) + .hasMessageContaining("UNAVAILABLE"); + verifyNoInteractions(gameSession, world, entity); + } + + @Test + void forwardsActualBootstrapCapabilityAndOpaqueScopeWithoutCallingDelegationOwners() { + var source = mock(AccountCharacterCreateOwnerClients.class); + var principal = mock(AccountCharacterCreatePrincipal.class); + var resolved = + new AccountCharacterCreateOwnerClients.ResolvedSource( + intent.actionBytes(), intent.originalSourceReadback()); + when(source.resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId())) + .thenReturn(resolved); + var clients = + new AccountCharacterCreateDelegationClients(NAMESPACE, source, gameSession, world, entity); + + assertThat(clients.resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId())) + .isSameAs(resolved); + + verify(source).resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId()); + verifyNoInteractions(gameSession, world, entity); + } + + @Test + void compositionPassesExactCommittedAccountCarrierAndOwnerReadbacks() { + var target = target(); + var lifecycle = lifecycle(); + var terminal = terminal(target, lifecycle); + when(gameSession.acquireAndReadOriginal(account)).thenReturn(target); + when(world.acquireAndReadOriginal(account)).thenReturn(lifecycle); + when(entity.commitAndReadOriginal(account, target, lifecycle)).thenReturn(terminal); + + assertThat(clients().submitProtected(intent, protection)).isEqualTo(terminal); + + var order = org.mockito.Mockito.inOrder(gameSession, world, entity); + order.verify(gameSession).acquireAndReadOriginal(account); + order.verify(world).acquireAndReadOriginal(account); + order.verify(entity).commitAndReadOriginal(account, target, lifecycle); + } + + @Test + void partialAcquisitionTimeoutRetriesExactAccountSelectorWithoutInvokingEntity() { + var target = target(); + var lifecycle = lifecycle(); + var terminal = terminal(target, lifecycle); + when(gameSession.acquireAndReadOriginal(account)).thenReturn(target); + when(world.acquireAndReadOriginal(account)) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()) + .thenReturn(lifecycle); + when(entity.commitAndReadOriginal(account, target, lifecycle)).thenReturn(terminal); + + assertThatThrownBy(() -> clients().submitProtected(intent, protection)) + .hasMessageContaining("DEADLINE_EXCEEDED"); + verifyNoInteractions(entity); + assertThat(clients().submitProtected(intent, protection)).isEqualTo(terminal); + var observed = ArgumentCaptor.forClass(ReadOriginalCharacterCreateProtectionResponse.class); + verify(gameSession, times(2)).acquireAndReadOriginal(observed.capture()); + assertThat(observed.getAllValues()).containsExactly(account, account); + verify(world, times(2)).acquireAndReadOriginal(account); + } + + @Test + void mismatchedOriginalHoldAndAmbientSqlCannotReachOwners() { + var changed = + new AccountCharacterCreateIntent( + UUID.randomUUID(), + intent.createCharacterRequestId(), + intent.connectScopeId(), + intent.accountId(), + intent.actionBytes(), + intent.mutationDigest(), + intent.originalSourceReadback()); + assertThatThrownBy(() -> clients().submitProtected(changed, protection)) + .hasMessageContaining("original CHARACTER_CREATE"); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> clients().submitProtected(intent, protection)) + .hasMessageContaining("no ambient Account transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(gameSession, world, entity); + } + + @Test + void terminalMustRetainEveryOriginalOwnerByteAndReference() { + var target = target(); + var lifecycle = lifecycle(); + var terminal = terminal(target, lifecycle); + var request = AccountCharacterCreateDelegationBindings.request(account, target, lifecycle); + AccountCharacterCreateDelegationBindings.terminal( + request, account, target, lifecycle, terminal); + for (var changed : + java.util.List.of( + terminal.toBuilder() + .setAccountOriginal( + account.getOriginal().toBuilder() + .setOriginalSourceReadback(ByteString.copyFromUtf8("changed"))) + .build(), + terminal.toBuilder() + .setOriginalAccountProtection( + account.toBuilder().setAccountProtectionFence(8L).build().toByteString()) + .build(), + terminal.toBuilder() + .setOriginalGameSessionProtection( + target.toBuilder() + .setAcquiredAt(NOW.plusNanos(1).toString()) + .build() + .toByteString()) + .build(), + terminal.toBuilder() + .setOriginalWorldProtection( + lifecycle.toBuilder() + .setOriginalLifecycleEvidence(ByteString.copyFromUtf8("changed")) + .build() + .toByteString()) + .build(), + terminal.toBuilder() + .setOriginalRequest( + request.toBuilder() + .setOriginal( + request.getOriginal().toBuilder() + .setOperationId(UUID.randomUUID().toString()))) + .build(), + terminal.toBuilder().setUnknownFields(unknown()).build())) { + assertThatThrownBy( + () -> + AccountCharacterCreateDelegationBindings.terminal( + request, account, target, lifecycle, changed)) + .hasMessageContaining("original CHARACTER_CREATE"); + } + } + + @Test + void unspecifiedPendingLikeOutcomeOrMalformedAbortNeverBecomesTerminal() { + var target = target(); + var lifecycle = lifecycle(); + var terminal = terminal(target, lifecycle); + var request = AccountCharacterCreateDelegationBindings.request(account, target, lifecycle); + assertThatThrownBy( + () -> + AccountCharacterCreateDelegationBindings.terminal( + request, + account, + target, + lifecycle, + terminal.toBuilder() + .setOutcome( + EntityCharacterCreateOutcome + .ENTITY_CHARACTER_CREATE_OUTCOME_UNSPECIFIED) + .build())) + .hasMessageContaining("original CHARACTER_CREATE"); + assertThatThrownBy( + () -> + AccountCharacterCreateDelegationBindings.terminal( + request, + account, + target, + lifecycle, + terminal.toBuilder() + .clearCharacterId() + .setOutcome( + EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED) + .build())) + .hasMessageContaining("original CHARACTER_CREATE"); + // A genuine definitive abort may be returned by Entity after an independently fenced race; + // recognizing its exact terminal here does not release any hold or invoke Abort RPC. + AccountCharacterCreateDelegationBindings.terminal( + request, + account, + target, + lifecycle, + terminal.toBuilder() + .clearCharacterId() + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED) + .setAbortRequestId(UUID.randomUUID().toString()) + .build()); + } + + @Test + void targetSnapshotCannotSubstituteAccountSourceLifecycleOrPointerVersion() { + var target = target(); + AccountCharacterCreateDelegationBindings.gameSession(account, target); + assertThatThrownBy( + () -> + AccountCharacterCreateDelegationBindings.gameSession( + account, + target.toBuilder() + .setAccountProtection( + account.toBuilder() + .setOriginalMembershipSnapshot(ByteString.copyFromUtf8("changed"))) + .build())) + .hasMessageContaining("original CHARACTER_CREATE"); + try { + var snapshot = CharacterCreateTargetSnapshot.parseFrom(target.getOriginalTargetEvidence()); + assertThatThrownBy( + () -> + AccountCharacterCreateDelegationBindings.gameSession( + account, + target.toBuilder() + .setOriginalTargetEvidence( + snapshot.toBuilder() + .setPointerVersion(snapshot.getPointerVersion() + 1) + .build() + .toByteString()) + .build())) + .hasMessageContaining("original CHARACTER_CREATE"); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw new AssertionError(malformed); + } + assertThatThrownBy(() -> AccountCharacterCreateDelegationBindings.world(account, lifecycle())) + .isInstanceOf(RuntimeException.class); + } + + private AccountCharacterCreateDelegationClients clients() { + return new AccountCharacterCreateDelegationClients( + NAMESPACE, resolver, gameSession, world, entity); + } + + private CharacterCreateTargetProtection target() { + var action = intent.action(); + var snapshot = + CharacterCreateTargetSnapshot.newBuilder() + .setSchemaVersion(1) + .setOriginalAction(account.getOriginal().getOriginalAction()) + .setTargetNamespace(NAMESPACE) + .setOperationId(intent.operationId().toString()) + .setMutationDigest(intent.mutationDigest()) + .setCanonicalTenantId(action.scope().tenantId()) + .setRealmId(action.target().realmId()) + .setCanonicalGameInstanceId(action.target().gameInstanceId()) + .setCanonicalVersionId(action.target().versionId()) + .setPlayableStateNamespaceId(action.scope().playableStateNamespaceId()) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) + .setCatalogReceiptDigest("sha256:" + "a".repeat(64)) + .setInitialAdmissionRequestId("owner-native-request") + .setInitialAdmissionOwnerProofDigest("sha256:" + "b".repeat(64)) + .setAdmissionPointerSnapshotDigest("c".repeat(64)) + .build(); + return CharacterCreateTargetProtection.newBuilder() + .setAccountProtection(account) + .setGameSessionProtectionId(UUID.randomUUID().toString()) + .setGameSessionProtectionFence(11L) + .setAcquiredAt(NOW.toString()) + .setOriginalTargetEvidence(snapshot.toByteString()) + .build(); + } + + private WorldCharacterCreateLifecycleProtection lifecycle() { + return WorldCharacterCreateLifecycleProtection.newBuilder() + .setAccountProtection(account) + .setWorldProtectionId(UUID.randomUUID().toString()) + .setWorldProtectionFence(13L) + .setAcquiredAt(NOW.toString()) + .setOriginalLifecycleEvidence( + ByteString.copyFromUtf8("controlled-invalid-lifecycle-not-authority")) + .build(); + } + + private EntityCharacterCreateTerminal terminal( + CharacterCreateTargetProtection target, WorldCharacterCreateLifecycleProtection lifecycle) { + return EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest( + AccountCharacterCreateDelegationBindings.request(account, target, lifecycle)) + .setAccountOriginal(account.getOriginal()) + .setOriginalAccountProtection(account.toByteString()) + .setOriginalGameSessionProtection(target.toByteString()) + .setOriginalWorldProtection(lifecycle.toByteString()) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(UUID.randomUUID().toString()) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1L) + .setCompletedAt(NOW.toString()) + .build(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGrpcClientsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGrpcClientsTest.java new file mode 100644 index 0000000000..683f2cb009 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateGrpcClientsTest.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.v1.AcquireCharacterCreateTargetProtectionRequest; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetSnapshot; +import net.firedevops.firemud.gamesession.v1.ReadOriginalCharacterCreateTargetProtectionRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled stub proof; readable placeholder paths here do not qualify any TLS connection. */ +class AccountCharacterCreateGrpcClientsTest { + private static final String NAMESPACE = "creation-client-proof"; + @TempDir Path directory; + private final GrpcChannelFactory channels = mock(GrpcChannelFactory.class); + + @Test + void allClientsRequireFileBackedMutualTlsBeforeChannelConstruction() throws Exception { + var plaintext = tls(); + plaintext.setPlaintext(true); + for (var invalid : java.util.Arrays.asList(plaintext, null, new CommonGrpcClientProperties())) { + assertThatThrownBy( + () -> + new AccountCharacterCreateGameSessionClient( + new ServiceEndpointsProperties(), invalid, channels, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountCharacterCreateWorldClient( + new ServiceEndpointsProperties(), invalid, channels, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountCharacterCreateEntityClient( + new ServiceEndpointsProperties(), invalid, channels, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channels); + } + + @Test + void targetAcquisitionReadsExactCommittedOriginalWithFiniteBoundedCalls() throws Exception { + var stub = + mock( + CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub.class, + RETURNS_SELF); + var account = account(); + var target = target(account); + when(stub.acquireCharacterCreateTargetProtection(any())).thenReturn(target); + when(stub.readOriginalCharacterCreateTargetProtection(any())).thenReturn(target); + var client = targetClient(stub); + + assertThat(client.acquireAndReadOriginal(account)).isEqualTo(target); + assertThat(client.acquireAndReadOriginal(account)).isEqualTo(target); + + var acquisitions = ArgumentCaptor.forClass(AcquireCharacterCreateTargetProtectionRequest.class); + verify(stub, times(2)).acquireCharacterCreateTargetProtection(acquisitions.capture()); + assertThat(acquisitions.getAllValues()) + .allSatisfy( + request -> + assertThat(request.getAccountProtection()) + .isEqualTo(AccountCharacterCreateDelegationBindings.selector(account))); + var reads = ArgumentCaptor.forClass(ReadOriginalCharacterCreateTargetProtectionRequest.class); + verify(stub, times(2)).readOriginalCharacterCreateTargetProtection(reads.capture()); + assertThat(reads.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getAccountProtection()) + .isEqualTo(AccountCharacterCreateDelegationBindings.selector(account)); + assertThat(request.getGameSessionProtectionId()) + .isEqualTo(target.getGameSessionProtectionId()); + assertThat(request.getGameSessionProtectionFence()) + .isEqualTo(target.getGameSessionProtectionFence()); + }); + verify(stub, times(4)).withDeadlineAfter(5, TimeUnit.SECONDS); + verify(stub, times(4)) + .withMaxInboundMessageSize(AccountCharacterCreateDelegationBindings.MAX_PROTECTION_BYTES); + } + + @Test + void changedOwnerReadbackNeverBecomesAcceptedAcquisition() throws Exception { + var stub = + mock( + CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub.class, + RETURNS_SELF); + var account = account(); + var target = target(account); + when(stub.acquireCharacterCreateTargetProtection(any())).thenReturn(target); + when(stub.readOriginalCharacterCreateTargetProtection(any())) + .thenReturn(target.toBuilder().setAcquiredAt("2026-10-24T00:00:00.000000001Z").build()); + + assertThatThrownBy(() -> targetClient(stub).acquireAndReadOriginal(account)) + .hasMessageContaining("original CHARACTER_CREATE"); + } + + @Test + void ambientSqlIsRejectedBeforeAnyOwnerRpcOrInitialization() throws Exception { + var target = + new AccountCharacterCreateGameSessionClient( + new ServiceEndpointsProperties(), tls(), channels, NAMESPACE); + var world = + new AccountCharacterCreateWorldClient( + new ServiceEndpointsProperties(), tls(), channels, NAMESPACE); + var entity = + new AccountCharacterCreateEntityClient( + new ServiceEndpointsProperties(), tls(), channels, NAMESPACE); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> target.acquireAndReadOriginal(account())) + .hasMessageContaining("no ambient Account transaction"); + assertThatThrownBy(() -> world.acquireAndReadOriginal(account())) + .hasMessageContaining("no ambient Account transaction"); + assertThatThrownBy(() -> entity.commitAndReadOriginal(account(), null, null)) + .hasMessageContaining("no ambient Account transaction"); + assertThatThrownBy(() -> entity.readOriginalTerminal(account(), null, null)) + .hasMessageContaining("no ambient Account transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(channels); + } + + private AccountCharacterCreateGameSessionClient targetClient( + CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub stub) + throws Exception { + var client = + new AccountCharacterCreateGameSessionClient( + new ServiceEndpointsProperties(), tls(), channels, NAMESPACE); + Field current = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + current.setAccessible(true); + current.set(client, stub); + Field initialized = + AbstractReloadingBlockingGrpcClient.class.getDeclaredField("explicitlyInitialized"); + initialized.setAccessible(true); + initialized.set(client, true); + return client; + } + + private CommonGrpcClientProperties tls() throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "controlled-placeholder").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "controlled-placeholder").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "controlled-placeholder").toString()); + return tls; + } + + private static ReadOriginalCharacterCreateProtectionResponse account() { + var intent = + AccountCharacterCreateTestActions.intent( + NAMESPACE, UUID.randomUUID(), UUID.randomUUID(), Instant.parse("2099-01-01T00:00:00Z")); + return AccountCharacterCreateDelegationBindings.account( + NAMESPACE, + intent, + new AccountCharacterCreateRepository.Protection( + intent, + UUID.randomUUID(), + 7L, + Instant.parse("2026-10-24T00:00:00Z"), + new byte[] {1}, + new byte[] {2})); + } + + private static CharacterCreateTargetProtection target( + ReadOriginalCharacterCreateProtectionResponse account) { + var action = + net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.decode( + account.getOriginal().getOriginalAction().toByteArray()); + var snapshot = + CharacterCreateTargetSnapshot.newBuilder() + .setSchemaVersion(1) + .setOriginalAction(account.getOriginal().getOriginalAction()) + .setTargetNamespace(NAMESPACE) + .setOperationId(account.getOriginal().getOperationId()) + .setMutationDigest(account.getOriginal().getMutationDigest()) + .setCanonicalTenantId(action.scope().tenantId()) + .setRealmId(action.target().realmId()) + .setCanonicalGameInstanceId(action.target().gameInstanceId()) + .setCanonicalVersionId(action.target().versionId()) + .setPlayableStateNamespaceId(action.scope().playableStateNamespaceId()) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) + .setCatalogReceiptDigest("sha256:" + "a".repeat(64)) + .setInitialAdmissionRequestId("native-owner-request") + .setInitialAdmissionOwnerProofDigest("sha256:" + "b".repeat(64)) + .setAdmissionPointerSnapshotDigest("c".repeat(64)) + .build(); + return CharacterCreateTargetProtection.newBuilder() + .setAccountProtection(account) + .setGameSessionProtectionId(UUID.randomUUID().toString()) + .setGameSessionProtectionFence(17L) + .setAcquiredAt("2026-10-24T00:00:00Z") + .setOriginalTargetEvidence(ByteString.copyFrom(snapshot.toByteArray())) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntentTest.java new file mode 100644 index 0000000000..a12db9bc65 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateIntentTest.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountCharacterCreateIntentTest { + private final AccountCharacterCreateIntent original = + AccountCharacterCreateTestActions.intent( + "character-create-proof", + UUID.randomUUID(), + UUID.randomUUID(), + Instant.parse("2099-01-01T00:00:00Z")); + + @Test + void retainsExactOpaqueScopeWithoutParsingTrimmingOrChangingCase() { + String scope = " Issued.Scope_Mixed-case-é-e\u0301-\uD83D\uDE80 "; + var retained = withScope(scope); + assertThat(retained.connectScopeId()).isEqualTo(scope); + assertThat(retained.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(retained.sameBinding(withScope(scope))).isTrue(); + assertThat(retained.sameBinding(withScope(scope.strip()))).isFalse(); + assertThat(retained.sameBinding(withScope(scope.replace("Mixed", "mixed")))).isFalse(); + assertThat(withScope("s".repeat(2048)).connectScopeId()).hasSize(2048); + } + + @Test + void rejectsAbsentBlankOversizedAndUnrepresentableScopes() { + assertThatThrownBy(() -> withScope(null)).isInstanceOf(IllegalArgumentException.class); + for (String scope : + List.of("", " \t\n", "s".repeat(2049), "a" + (char) 0 + "b", "\uD800", "\uDC00")) { + assertThatThrownBy(() -> withScope(scope)).isInstanceOf(IllegalArgumentException.class); + } + } + + private AccountCharacterCreateIntent withScope(String scope) { + return new AccountCharacterCreateIntent( + original.operationId(), + original.createCharacterRequestId(), + scope, + original.accountId(), + original.actionBytes(), + original.mutationDigest(), + original.originalSourceReadback()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOutboundMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOutboundMtlsTest.java new file mode 100644 index 0000000000..94cb2c7e18 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateOutboundMtlsTest.java @@ -0,0 +1,741 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.BindableService; +import io.grpc.Grpc; +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 io.grpc.stub.MetadataUtils; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki.Identity; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki.TestCertificateAuthority; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; +import net.firedevops.firemud.gamesession.v1.AcquireCharacterCreateTargetProtectionRequest; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetProtection; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetSnapshot; +import net.firedevops.firemud.gamesession.v1.ReadOriginalCharacterCreateTargetProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCharacterCreateLifecycleProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.CharacterCreateLifecycleServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalCharacterCreateLifecycleProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** + * Native production-client transport proof over controlled loopback PKI and stipulated payloads. + * ACTIVE, Account snapshots and Entity COMMITTED here are fixture content, not genuine source, + * lifecycle, player-bootstrap, database ownership, route activation or production-PKI proof. + */ +@Timeout(120) +class AccountCharacterCreateOutboundMtlsTest { + private static final String NAMESPACE = "test"; + private static final Instant NOW = Instant.parse("2026-10-24T00:00:00Z"); + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + @TempDir static Path directory; + private static TestCertificateAuthority authority; + private static Identity accountIdentity; + private static Identity wrongClientService; + private static Identity wrongClientNamespace; + private static Identity gameSessionIdentity; + private static Identity worldIdentity; + private static Identity entityIdentity; + private static Identity wrongServerService; + private static Identity wrongServerNamespace; + private static Payloads payloads; + + @BeforeAll + static void createControlledPkiAndPayloads() throws Exception { + authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, + "creation-ca.p12", + "creation-ca.crt", + "creation-ca", + "CN=Controlled creation transport CA", + "controlled-test-password"); + accountIdentity = issue("account", NAMESPACE, "account-service", false); + wrongClientService = issue("social-client", NAMESPACE, "social-groups-service", false); + wrongClientNamespace = issue("other-account", "other-test", "account-service", false); + gameSessionIdentity = issue("game-session", NAMESPACE, "game-session-service", true); + worldIdentity = issue("world", NAMESPACE, "world-management-service", true); + entityIdentity = issue("entity", NAMESPACE, "entity-management-service", true); + wrongServerService = issue("social-server", NAMESPACE, "social-groups-service", true); + wrongServerNamespace = issue("other-server", "other-test", "game-session-service", true); + payloads = Payloads.create(); + } + + @Test + void actualAccountChannelsPreserveAcquisitionOriginalReadsAndEntityTerminalOnRetry() + throws Exception { + try (var owners = owners(); + var clients = clients(owners, accountIdentity, new GrpcChannelFactory())) { + var composition = + new AccountCharacterCreateDelegationClients( + NAMESPACE, + AccountCharacterCreateOwnerClients.unavailable(), + clients.gameSession, + clients.world, + clients.entity); + var first = composition.submitProtected(payloads.intent, payloads.protection); + var retry = composition.submitProtected(payloads.intent, payloads.protection); + assertThat(first.toByteArray()).containsExactly(payloads.terminal.toByteArray()); + assertThat(retry.toByteArray()).containsExactly(first.toByteArray()); + assertThat( + clients.entity.readOriginalTerminal( + payloads.account, payloads.target, payloads.world)) + .isEqualTo(first); + var verified = clients.entity.readVerifiedOriginalTerminal(payloads.account); + assertThat(verified.account()).isEqualTo(payloads.account); + assertThat(verified.terminal()).isEqualTo(first); + assertThat(owners.calls) + .containsExactly( + "gs.acquire", + "gs.read", + "world.acquire", + "world.read", + "entity.commit", + "entity.read", + "gs.acquire", + "gs.read", + "world.acquire", + "world.read", + "entity.commit", + "entity.read", + "entity.read", + "entity.read"); + assertThat(first.getOriginalAccountProtection()).isEqualTo(payloads.account.toByteString()); + assertThat(first.getOriginalGameSessionProtection()) + .isEqualTo(payloads.target.toByteString()); + assertThat(first.getOriginalWorldProtection()).isEqualTo(payloads.world.toByteString()); + } + } + + @Test + void certificateServiceNamespaceAndBearerCannotSubstituteForExactAccountPeer() throws Exception { + try (var owners = owners()) { + for (Identity identity : List.of(wrongClientService, wrongClientNamespace)) { + try (var clients = clients(owners, identity, new GrpcChannelFactory())) { + denied( + Status.Code.PERMISSION_DENIED, + () -> clients.gameSession.acquireAndReadOriginal(payloads.account)); + denied( + Status.Code.PERMISSION_DENIED, + () -> clients.world.acquireAndReadOriginal(payloads.account)); + denied( + Status.Code.PERMISSION_DENIED, + () -> + clients.entity.commitAndReadOriginal( + payloads.account, payloads.target, payloads.world)); + } + } + // Even a real Account certificate cannot make bearer metadata part of this certificate-only + // purpose boundary; a wrong certificate plus an asserted Account bearer is denied too. + for (Identity identity : List.of(accountIdentity, wrongClientService)) { + try (var clients = clients(owners, identity, bearerFactory())) { + denied( + Status.Code.PERMISSION_DENIED, + () -> clients.gameSession.acquireAndReadOriginal(payloads.account)); + denied( + Status.Code.PERMISSION_DENIED, + () -> clients.world.acquireAndReadOriginal(payloads.account)); + denied( + Status.Code.PERMISSION_DENIED, + () -> + clients.entity.commitAndReadOriginal( + payloads.account, payloads.target, payloads.world)); + } + } + assertThat(owners.calls).isEmpty(); + } + } + + @Test + void everyClientRejectsWrongServiceAndNamespaceServerCertificates() throws Exception { + for (Identity identity : List.of(wrongServerService, wrongServerNamespace)) { + try (var owners = new NativeOwners(identity, identity, identity); + var clients = clients(owners, accountIdentity, new GrpcChannelFactory())) { + denied( + Status.Code.UNAUTHENTICATED, + () -> clients.gameSession.acquireAndReadOriginal(payloads.account)); + assertThat(owners.calls).isEmpty(); + denied( + Status.Code.UNAUTHENTICATED, + () -> clients.world.acquireAndReadOriginal(payloads.account)); + assertThat(owners.calls).isEmpty(); + denied( + Status.Code.UNAUTHENTICATED, + () -> + clients.entity.commitAndReadOriginal( + payloads.account, payloads.target, payloads.world)); + assertThat(owners.calls).isEmpty(); + } + } + } + + @Test + void changedIndependentOriginalProtectionAndTerminalReadbacksAreRejectedOverTls() + throws Exception { + try (var owners = owners(); + var clients = clients(owners, accountIdentity, new GrpcChannelFactory())) { + owners.targetRead.set( + payloads.target.toBuilder().setAcquiredAt(NOW.plusNanos(1).toString()).build()); + assertThatThrownBy(() -> clients.gameSession.acquireAndReadOriginal(payloads.account)) + .hasMessageContaining("Exact original CHARACTER_CREATE"); + owners.worldRead.set( + payloads.world.toBuilder().setAcquiredAt(NOW.plusNanos(1).toString()).build()); + assertThatThrownBy(() -> clients.world.acquireAndReadOriginal(payloads.account)) + .hasMessageContaining("Exact original CHARACTER_CREATE"); + owners.terminalRead.set( + payloads.terminal.toBuilder().setCompletedAt(NOW.plusNanos(1).toString()).build()); + assertThatThrownBy( + () -> + clients.entity.commitAndReadOriginal( + payloads.account, payloads.target, payloads.world)) + .hasMessageContaining("Exact original CHARACTER_CREATE"); + owners.terminalRead.set( + payloads.terminal.toBuilder() + .setOriginalAccountProtection( + payloads.account.toBuilder() + .setOriginalMembershipSnapshot( + ByteString.copyFromUtf8("different-owner-source")) + .build() + .toByteString()) + .build()); + assertThatThrownBy( + () -> + clients.entity.readOriginalTerminal( + payloads.account, payloads.target, payloads.world)) + .hasMessageContaining("Exact original CHARACTER_CREATE"); + } + } + + @Test + void nativeTargetReplyEnforcesThePurposeSpecificSixteenMiBReceiveBound() throws Exception { + try (var owners = owners(); + var clients = clients(owners, accountIdentity, new GrpcChannelFactory())) { + owners.targetAcquire.set( + payloads.target.toBuilder() + .setOriginalTargetEvidence( + ByteString.copyFrom( + new byte[AccountCharacterCreateDelegationBindings.MAX_PROTECTION_BYTES])) + .build()); + denied( + Status.Code.RESOURCE_EXHAUSTED, + () -> clients.gameSession.acquireAndReadOriginal(payloads.account)); + assertThat(owners.calls).containsExactly("gs.acquire"); + } + } + + private static NativeOwners owners() throws Exception { + return new NativeOwners(gameSessionIdentity, worldIdentity, entityIdentity); + } + + private static Identity issue(String alias, String namespace, String service, boolean server) + throws Exception { + return AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + "spiffe://firemud/ns/" + namespace + "/sa/" + service, + server, + false, + true) + .identity(); + } + + private static Clients clients( + NativeOwners owners, Identity identity, GrpcChannelFactory channels) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + owners.servers.get(0).getPort()); + endpoints.setWorldManagementService("localhost:" + owners.servers.get(1).getPort()); + endpoints.setEntityManagementService("localhost:" + owners.servers.get(2).getPort()); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + pem(identity.alias() + "-client.pem", "CERTIFICATE", identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + pem(identity.alias() + "-key.pem", "PRIVATE KEY", identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(authority.certificateFile().toString()); + var clients = + new Clients( + new AccountCharacterCreateGameSessionClient(endpoints, tls, channels, NAMESPACE), + new AccountCharacterCreateWorldClient(endpoints, tls, channels, NAMESPACE), + new AccountCharacterCreateEntityClient(endpoints, tls, channels, NAMESPACE)); + try { + clients.gameSession.init(); + clients.world.init(); + clients.entity.init(); + return clients; + } catch (Exception failure) { + clients.close(); + throw failure; + } + } + + private static Path pem(String name, String label, byte[] bytes) throws Exception { + return Files.writeString( + directory.resolve(name), + "-----BEGIN " + + label + + "-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes) + + "\n-----END " + + label + + "-----\n", + StandardCharsets.US_ASCII); + } + + private static GrpcChannelFactory bearerFactory() { + return new GrpcChannelFactory() { + @Override + public io.grpc.ManagedChannel buildChannel( + String target, int port, CommonGrpcClientProperties tls, boolean keepAlive) + throws javax.net.ssl.SSLException { + var headers = new Metadata(); + headers.put(AUTHORIZATION, "Bearer test-fixture-token"); + return NettyChannelBuilder.forTarget(target) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(Path.of(tls.getCaCert()).toFile()) + .keyManager( + Path.of(tls.getCertChain()).toFile(), Path.of(tls.getPrivateKey()).toFile()) + .build()) + .intercept(MetadataUtils.newAttachHeadersInterceptor(headers)) + .build(); + } + }; + } + + private static void denied( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record Clients( + AccountCharacterCreateGameSessionClient gameSession, + AccountCharacterCreateWorldClient world, + AccountCharacterCreateEntityClient entity) + implements AutoCloseable { + @Override + public void close() throws Exception { + try { + gameSession.close(); + } finally { + try { + world.close(); + } finally { + entity.close(); + } + } + } + } + + private static final class AccountCertificateOnly implements ServerInterceptor { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .orElse(null); + if (peer == null + || !NAMESPACE.equals(peer.namespace()) + || !"account-service".equals(peer.service()) + || headers.get(AUTHORIZATION) != null) { + call.close( + Status.PERMISSION_DENIED.withDescription( + "Exact certificate-only Account peer required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + } + + private static final class NativeOwners implements AutoCloseable { + private final List servers = new ArrayList<>(); + private final List calls = new CopyOnWriteArrayList<>(); + private final AtomicReference targetAcquire = + new AtomicReference<>(payloads.target); + private final AtomicReference targetRead = + new AtomicReference<>(payloads.target); + private final AtomicReference worldRead = + new AtomicReference<>(payloads.world); + private final AtomicReference terminalRead = + new AtomicReference<>(payloads.terminal); + + private NativeOwners(Identity gs, Identity world, Identity entity) throws Exception { + try { + start( + gs, + new CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceImplBase() { + @Override + public void acquireCharacterCreateTargetProtection( + AcquireCharacterCreateTargetProtectionRequest request, + StreamObserver observer) { + respond( + "gs.acquire", + observer, + () -> { + assertThat(request.getAccountProtection()) + .isEqualTo( + AccountCharacterCreateDelegationBindings.selector(payloads.account)); + return targetAcquire.get(); + }); + } + + @Override + public void readOriginalCharacterCreateTargetProtection( + ReadOriginalCharacterCreateTargetProtectionRequest request, + StreamObserver observer) { + respond( + "gs.read", + observer, + () -> { + assertThat(request.getAccountProtection()) + .isEqualTo( + AccountCharacterCreateDelegationBindings.selector(payloads.account)); + assertThat(request.getGameSessionProtectionId()) + .isEqualTo(payloads.target.getGameSessionProtectionId()); + assertThat(request.getGameSessionProtectionFence()) + .isEqualTo(payloads.target.getGameSessionProtectionFence()); + return targetRead.get(); + }); + } + }); + start( + world, + new CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceImplBase() { + @Override + public void acquireCharacterCreateLifecycleProtection( + AcquireCharacterCreateLifecycleProtectionRequest request, + StreamObserver observer) { + respond( + "world.acquire", + observer, + () -> { + assertThat(request.getAccountProtection()) + .isEqualTo( + AccountCharacterCreateDelegationBindings.selector(payloads.account)); + return payloads.world; + }); + } + + @Override + public void readOriginalCharacterCreateLifecycleProtection( + ReadOriginalCharacterCreateLifecycleProtectionRequest request, + StreamObserver observer) { + respond( + "world.read", + observer, + () -> { + assertThat(request.getAccountProtection()) + .isEqualTo( + AccountCharacterCreateDelegationBindings.selector(payloads.account)); + assertThat(request.getWorldProtectionId()) + .isEqualTo(payloads.world.getWorldProtectionId()); + assertThat(request.getWorldProtectionFence()) + .isEqualTo(payloads.world.getWorldProtectionFence()); + return worldRead.get(); + }); + } + }); + start( + entity, + new EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceImplBase() { + @Override + public void commitProtectedCharacterCreate( + CommitProtectedCharacterCreateRequest request, + StreamObserver observer) { + respond( + "entity.commit", + observer, + () -> { + assertThat(request).isEqualTo(payloads.terminal.getOriginalRequest()); + return payloads.terminal; + }); + } + + @Override + public void readEntityCharacterCreateTerminal( + ReadEntityCharacterCreateTerminalRequest request, + StreamObserver observer) { + respond( + "entity.read", + observer, + () -> { + assertThat(request.getOriginal()) + .isEqualTo(payloads.terminal.getOriginalRequest().getOriginal()); + return terminalRead.get(); + }); + } + }); + } catch (Exception failure) { + close(); + throw failure; + } + } + + private void start(Identity identity, BindableService service) throws Exception { + servers.add( + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(authority.certificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, new GrpcPeerIdentityInterceptor(), new AccountCertificateOnly())) + .build() + .start()); + } + + private void respond( + String method, StreamObserver observer, java.util.function.Supplier value) { + calls.add(method); + try { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + observer.onNext(value.get()); + observer.onCompleted(); + } catch (Throwable failure) { + observer.onError( + Status.INTERNAL + .withDescription("Controlled fixture binding failure") + .withCause(failure) + .asRuntimeException()); + } + } + + @Override + public void close() throws Exception { + for (Server server : servers) server.shutdownNow(); + for (Server server : servers) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private record Payloads( + AccountCharacterCreateIntent intent, + AccountCharacterCreateRepository.Protection protection, + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateTargetProtection target, + WorldCharacterCreateLifecycleProtection world, + EntityCharacterCreateTerminal terminal) { + private static Payloads create() throws Exception { + var lifecycle = AuthoringFixtures.lifecycleEvidence("ACTIVE", 31L); + var basis = + AccountCharacterCreateTestActions.intent( + NAMESPACE, + UUID.randomUUID(), + lifecycle.request().canonicalTenantId(), + Instant.parse("2099-01-01T00:00:00Z")) + .action(); + var prior = basis.mutation().authoredSource(); + var launch = lifecycle.launchBinding(); + var scope = lifecycle.request(); + String policy = + prior + .policy() + .canonicalPolicyJson() + .replace(basis.target().worldSlug(), scope.worldSlug()); + String policyDigest = + "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(policy.getBytes(StandardCharsets.UTF_8))); + var authored = + new CharacterCreateOperatorAction.AuthoredSource( + prior.schema(), + prior.bindingId(), + prior.bindingDigest(), + scope.canonicalTenantId().toString(), + scope.canonicalVersionId().toString(), + launch.descriptor().authoredWorldSourceOperationId().toString(), + launch.descriptor().authoredWorldSourceEvidenceDigest(), + scope.worldSlug(), + launch.releaseAttestation().publishWorkflowId(), + launch.releaseAttestation().commitId(), + prior.selectedCommitDigest(), + new CharacterCreateOperatorAction.Policy( + prior.policy().commitId(), + prior.policy().revisionId(), + prior.policy().logicalRevisionId(), + policy, + policyDigest), + prior.core(), + prior.descriptor(), + prior.disposition(), + prior.safeFeedback()); + var c = basis.mutation().catalog(); + var p = basis.mutation().pointer(); + var catalog = + new CharacterCreateOperatorAction.Catalog( + c.tenantId(), + c.tenantSlug(), + scope.worldSlug(), + c.worldDisplayName(), + c.realmId(), + c.realmSlug(), + c.realmDisplayName(), + true, + true, + "SHARED", + scope.playableStateNamespaceId().toString(), + "PLAYER_CREATED", + c.catalogRevision()); + var pointer = + new CharacterCreateOperatorAction.Pointer( + p.tenantId(), + p.realmId(), + scope.worldSlug(), + p.realmSlug(), + "OPEN", + scope.canonicalGameInstanceId().toString(), + p.pointerVersion(), + p.catalogRevision(), + p.updatedAt()); + var action = + new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + NAMESPACE, + scope.canonicalTenantId().toString(), + scope.playableStateNamespaceId().toString(), + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + basis.target().accountId(), + basis.target().realmId(), + scope.worldSlug(), + basis.target().realmSlug(), + scope.canonicalGameInstanceId().toString(), + scope.canonicalVersionId().toString()), + basis.expectedVersion(), + new CharacterCreateOperatorAction.Mutation( + "CHARACTER_CREATE", "PLAYER_CREATED", catalog, pointer, authored, "{}"), + basis.auditReason()); + byte[] actionBytes = CharacterCreateOperatorActionCodec.encode(action); + var intent = + new AccountCharacterCreateIntent( + scope.readRequestId(), + UUID.randomUUID(), + "Issued.Transport.Scope_Mixed-case", + UUID.fromString(action.target().accountId()), + actionBytes, + CharacterCreateOperatorActionCodec.mutationDigest(action), + "stipulated-transport-source-readback".getBytes(StandardCharsets.UTF_8)); + var protection = + new AccountCharacterCreateRepository.Protection( + intent, UUID.randomUUID(), 7L, NOW, new byte[] {1}, new byte[] {2}); + var account = AccountCharacterCreateDelegationBindings.account(NAMESPACE, intent, protection); + var snapshot = + CharacterCreateTargetSnapshot.newBuilder() + .setSchemaVersion(1) + .setOriginalAction(ByteString.copyFrom(actionBytes)) + .setTargetNamespace(NAMESPACE) + .setOperationId(intent.operationId().toString()) + .setMutationDigest(intent.mutationDigest()) + .setCanonicalTenantId(action.scope().tenantId()) + .setRealmId(action.target().realmId()) + .setCanonicalGameInstanceId(action.target().gameInstanceId()) + .setCanonicalVersionId(action.target().versionId()) + .setPlayableStateNamespaceId(action.scope().playableStateNamespaceId()) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(31L) + .setCatalogReceiptDigest("sha256:" + "a".repeat(64)) + .setInitialAdmissionRequestId("stipulated-native-owner-request") + .setInitialAdmissionOwnerProofDigest("sha256:" + "b".repeat(64)) + .setAdmissionPointerSnapshotDigest("c".repeat(64)) + .build(); + var target = + CharacterCreateTargetProtection.newBuilder() + .setAccountProtection(account) + .setGameSessionProtectionId(UUID.randomUUID().toString()) + .setGameSessionProtectionFence(11L) + .setAcquiredAt(NOW.toString()) + .setOriginalTargetEvidence(snapshot.toByteString()) + .build(); + var world = + WorldCharacterCreateLifecycleProtection.newBuilder() + .setAccountProtection(account) + .setWorldProtectionId(UUID.randomUUID().toString()) + .setWorldProtectionFence(13L) + .setAcquiredAt(NOW.toString()) + .setOriginalLifecycleEvidence(ByteString.copyFrom(lifecycle.canonicalBytes())) + .build(); + var terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest( + AccountCharacterCreateDelegationBindings.request(account, target, world)) + .setAccountOriginal(account.getOriginal()) + .setOriginalAccountProtection(account.toByteString()) + .setOriginalGameSessionProtection(target.toByteString()) + .setOriginalWorldProtection(world.toByteString()) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(UUID.randomUUID().toString()) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1L) + .setCompletedAt(NOW.toString()) + .build(); + return new Payloads(intent, protection, account, target, world, terminal); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipalTest.java new file mode 100644 index 0000000000..09e3d9f9ba --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePrincipalTest.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.*; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled adapter proof; genuine signature/session verification belongs to the existing owner. + */ +class AccountCharacterCreatePrincipalTest { + private final AccountPlayerBootstrapCallerVerifier verifier = + mock(AccountPlayerBootstrapCallerVerifier.class); + private static final String token = "sensitive-bootstrap-token"; + private final UUID account = UUID.randomUUID(); + + @AfterEach + void resetTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void revalidatesExactCredentialOnEveryUseAndNeverPrintsIt() { + var caller = mock(AccountPlayerBootstrapCallerVerifier.VerifiedCaller.class); + when(caller.accountUuid()).thenReturn(account); + when(verifier.requireCaller(token)).thenReturn(caller); + var principal = AccountCharacterCreatePrincipal.authenticate(verifier, token); + assertThat(principal.authenticateCurrentAccount()).isEqualTo(account); + assertThat(principal.authenticateCurrentAccount()).isEqualTo(account); + verify(verifier, times(3)).requireCaller(token); + assertThat(principal.toString()).doesNotContain(token); + } + + @Test + void revokedCredentialCannotReusePreviouslyAuthenticatedIdentity() { + var caller = mock(AccountPlayerBootstrapCallerVerifier.VerifiedCaller.class); + when(caller.accountUuid()).thenReturn(account); + when(verifier.requireCaller(token)).thenReturn(caller); + var principal = AccountCharacterCreatePrincipal.authenticate(verifier, token); + var revoked = new IllegalStateException("revoked"); + when(verifier.requireCaller(token)).thenThrow(revoked); + assertThatThrownBy(principal::authenticateCurrentAccount).isSameAs(revoked); + } + + @Test + void differentOwnerCannotReplaceOriginalIdentity() { + var caller = mock(AccountPlayerBootstrapCallerVerifier.VerifiedCaller.class); + when(caller.accountUuid()).thenReturn(account, UUID.randomUUID()); + when(verifier.requireCaller(token)).thenReturn(caller); + var principal = AccountCharacterCreatePrincipal.authenticate(verifier, token); + assertThatThrownBy(principal::authenticateCurrentAccount) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Bootstrap Account identity changed"); + } + + @Test + void ambientTransactionNeverCallsCredentialOwner() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> AccountCharacterCreatePrincipal.authenticate(verifier, token)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(verifier); + } + + @Test + void ambientSynchronizationNeverCallsCredentialOwner() { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> AccountCharacterCreatePrincipal.authenticate(verifier, token)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(verifier); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClientMtlsTest.java new file mode 100644 index 0000000000..f7359055e5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreatePublicSourceClientMtlsTest.java @@ -0,0 +1,1134 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Server; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +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 io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicCatalog; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicPointer; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Production client init/channel and closed owner-codec proof over controlled loopback PKI. Valid + * owner-shaped results are stipulated fixtures with a matching closed authored projection. This + * proves transport and complete byte/target binding, not genuine production publication, bootstrap + * issuance, issued scope, membership, protection, allocation or admission. + */ +@Timeout(120) +class AccountCharacterCreatePublicSourceClientMtlsTest { + private static final UUID FIXTURE_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + private static final String NAMESPACE = "test"; + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + private static Fixture fixture; + + @BeforeAll + static void setUp() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Account public source test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/test/sa/account-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/social-groups-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/game-session-service", true)); + fixture = fixture(); + } + + @Test + void resolvesFriendlySelectorsToExactOwnerCanonicalTargetWithoutCallerIdentities() + throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + var result = client.resolve("synthetic-world", "realm", FIXTURE_ID); + assertThat(owner.targetReceived).containsExactly(targetRequest()); + assertThat(result.response().toByteArray()).containsExactly(targetResponse().toByteArray()); + assertThat(result.response().getCanonicalGameInstanceId()) + .isEqualTo(fixture.world().request().canonicalGameInstanceId().toString()); + assertThat(result.response().getCatalog().getPlayableStateNamespaceId()) + .isEqualTo(fixture.world().request().playableStateNamespaceId().toString()); + assertThat(result.response().getPointer().getUpdatedAt()) + .isEqualTo("2026-10-24T00:00:00.123456789Z"); + assertThat(owner.received).isEmpty(); + } + } + + @Test + void targetResolutionRejectsWrongServerBeforeAnyRpc() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + try (var owner = owner(identity); + var client = client(owner)) { + client.init(); + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(owner.targetReceived).isEmpty(); + assertThat(owner.received).isEmpty(); + } + } + } + + @Test + void targetResolutionRejectsMalformedSelectorsUninitializedClientAndAmbientSqlBeforeRpc() + throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOf(IllegalStateException.class); + client.init(); + for (String slug : List.of("", "World", " world", "world_1", "x".repeat(16 * 1024))) { + assertThatThrownBy(() -> client.resolve(slug, "realm", FIXTURE_ID)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> client.resolve("synthetic-world", slug, FIXTURE_ID)) + .isInstanceOf(RuntimeException.class); + } + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", new UUID(0, 0))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", null)) + .isInstanceOf(RuntimeException.class); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(owner.targetReceived).isEmpty(); + } + } + + @Test + void targetResolutionRejectsChangedEchoPrivatePolicyAndInconsistentOwnerMetadata() + throws Exception { + var good = targetResponse(); + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + for (var changed : + List.of( + good.toBuilder() + .setRequest( + targetRequest().toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build(), + good.toBuilder() + .setRequest(targetRequest().toBuilder().setTargetNamespace("other")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setPublicProduction(false)) + .build(), + good.toBuilder().setCatalog(good.getCatalog().toBuilder().setVisible(false)).build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setCharacterCreationPolicy("PRESEEDED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setStateScope("ISOLATED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setWorldSlug("other-world")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setRealmSlug("other-realm")) + .build(), + good.toBuilder() + .setCatalog( + good.getCatalog().toBuilder().setRealmId(UUID.randomUUID().toString())) + .build(), + good.toBuilder() + .setCatalog( + good.getCatalog().toBuilder().setTenantId(UUID.randomUUID().toString())) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().clearPlayableStateNamespaceId()) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().clearWorldDisplayName()) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setCatalogRevision(0)) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setCatalogRevision(99)) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setPointerVersion(0)) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setAdmissionState("CLOSED")) + .build(), + good.toBuilder().setPointer(good.getPointer().toBuilder().clearUpdatedAt()).build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder().setCanonicalGameInstanceId(UUID.randomUUID().toString()).build(), + good.toBuilder().setCanonicalVersionId("42").build(), + good.toBuilder().setActiveLifecycleEpoch(0).build(), + good.toBuilder().setUnknownFields(unknown()).build(), + good.toBuilder().clearCatalog().build(), + good.toBuilder().clearPointer().build())) { + owner.targetResponse.set(changed); + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOf(RuntimeException.class); + } + owner.targetResponse.set(good); + assertThat(client.resolve("synthetic-world", "realm", FIXTURE_ID).response()).isEqualTo(good); + } + } + + @Test + void targetResolutionPreservesOwnerAmbiguityErrorAndEnforces64KiBTransportBound() + throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + owner.targetError.set( + io.grpc.Status.FAILED_PRECONDITION.withDescription("Ambiguous public target")); + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Ambiguous public target"); + }); + owner.targetError.set(null); + owner.targetResponse.set( + targetResponse().toBuilder() + .setCatalog( + targetResponse().getCatalog().toBuilder() + .setWorldDisplayName( + "x" + .repeat( + AccountCharacterCreatePublicSourceClient.MAX_TARGET_WIRE_BYTES))) + .build()); + assertThatThrownBy(() -> client.resolve("synthetic-world", "realm", FIXTURE_ID)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.RESOURCE_EXHAUSTED)); + assertThat(owner.targetReceived).containsExactly(targetRequest(), targetRequest()); + } + } + + private static ResolveCharacterCreatePublicTargetRequest targetRequest() { + return ResolveCharacterCreatePublicTargetRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(FIXTURE_ID.toString()) + .setTargetNamespace(NAMESPACE) + .setWorldSlug("synthetic-world") + .setRealmSlug("realm") + .build(); + } + + private static ResolveCharacterCreatePublicTargetResponse targetResponse() { + return ResolveCharacterCreatePublicTargetResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(targetRequest()) + .setCatalog(fixture.response().getCatalog()) + .setPointer(fixture.response().getPointer()) + .setCanonicalGameInstanceId(fixture.request().getCanonicalGameInstanceId()) + .setCanonicalVersionId(fixture.response().getCanonicalVersionId()) + .setActiveLifecycleEpoch(fixture.response().getActiveLifecycleEpoch()) + .build(); + } + + @Test + void actualInitializedClientPreservesExactRequestAndCompleteTypedOwnerSources() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + var result = client.read(fixture.request()); + assertThat(owner.received).containsExactly(fixture.request()); + assertThat(result.response().toByteArray()).containsExactly(fixture.response().toByteArray()); + assertThat(result.authored().canonicalBytes()) + .containsExactly(fixture.authored().canonicalBytes()); + assertThat(result.authored().projections()).hasSize(1); + assertThat(result.world().canonicalBytes()).containsExactly(fixture.world().canonicalBytes()); + assertThat(result.response().getOriginalControlPlaneRequestId()) + .isEqualTo("world-lifecycle-control-request"); + assertThat(result.response().getPointer().getUpdatedAt()) + .isEqualTo("2026-10-24T00:00:00.123456789Z"); + } + } + + @Test + void wrongServerServiceAndNamespaceAreRejectedBeforeAnyReceivedRpc() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + try (var owner = owner(identity); + var client = client(owner)) { + client.init(); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(owner.received).isEmpty(); + } + } + } + + @Test + void absentInitializationAndAmbientSqlRefuseBeforeAnyReceivedRpc() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + client.init(); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(owner.received).isEmpty(); + } + } + + @Test + void malformedAndChangedRequestSelectorsRefuseBeforeAnyReceivedRpc() throws Exception { + var request = fixture.request(); + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setPlayableStateScope("ISOLATED").build(), + request.toBuilder().setCanonicalGameInstanceId("invalid").build(), + request.toBuilder().setWorldSlug("x".repeat(16 * 1024)).build(), + request.toBuilder().setUnknownFields(unknown()).build(), + request.toBuilder().setConnectScopeExpiresAt(request.getEvaluatedAt()).build())) { + assertThatThrownBy(() -> client.read(changed)).isInstanceOf(RuntimeException.class); + } + assertThat(owner.received).isEmpty(); + } + } + + @Test + void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws Exception { + var good = fixture.response(); + var world = fixture.world(); + var inactive = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "TERMINATING", + world.lifecycleEpoch(), + world.rowVersion(), + world.captureId(), + world.graphSha256(), + world.preparationInputDigest(), + world.operationalRegionAssignments()); + var otherLaunch = fixture("other-authored-launch-descriptor").world(); + var authored = fixture.authored(); + var noProjections = + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), authored.associationRead(), authored.descriptor(), List.of())); + var extraProjection = + AuthoredInitialActorCoreProjection.fromValidatedBinding( + UUID.randomUUID(), + sourceBinding( + authored.associationRead().association(), + authored.associationRead().association().sourceOperationId())); + var ambiguousProjections = + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), + authored.associationRead(), + authored.descriptor(), + List.of(authored.projections().getFirst(), extraProjection))); + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + for (var changed : + List.of( + good.toBuilder() + .setRequest(good.getRequest().toBuilder().setPointerVersion(99)) + .build(), + good.toBuilder() + .setCatalog( + good.getCatalog().toBuilder().setRealmId(UUID.randomUUID().toString())) + .build(), + good.toBuilder() + .setPointer( + good.getPointer().toBuilder() + .setAdmissibleGameInstanceId(UUID.randomUUID().toString())) + .build(), + good.toBuilder().setCatalog(good.getCatalog().toBuilder().setVisible(false)).build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setWorldDisplayName("Different world")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setRealmDisplayName("Different realm")) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setAdmissionState("CLOSED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder().setCanonicalVersionId(UUID.randomUUID().toString()).build(), + good.toBuilder().setOriginalControlPlaneRequestId("different-original").build(), + good.toBuilder().setOriginalOwnerAttemptId(UUID.randomUUID().toString()).build(), + good.toBuilder().setOriginalOwnerFence(good.getOriginalOwnerFence() + 1).build(), + good.toBuilder().setActiveLifecycleEpoch(good.getActiveLifecycleEpoch() + 1).build(), + good.toBuilder().setAuthoredSource(noProjections).build(), + good.toBuilder().setAuthoredSource(ambiguousProjections).build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder() + .setCanonicalResultBytes(ByteString.copyFromUtf8("{}"))) + .build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder().setResultDigest(digest('0'))) + .build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder().setWorldLifecycleEvidence(ByteString.copyFromUtf8("{}")).build(), + good.toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFrom(inactive.canonicalBytes())) + .build(), + good.toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFrom(otherLaunch.canonicalBytes())) + .build(), + good.toBuilder().setUnknownFields(unknown()).build())) { + owner.response.set(changed); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(RuntimeException.class); + } + assertThat(owner.received).isNotEmpty().allMatch(fixture.request()::equals); + owner.response.set(good); + assertThat(client.read(fixture.request()).response()).isEqualTo(good); + } + } + + @Test + void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + owner.response.set( + fixture.response().toBuilder() + .setWorldLifecycleEvidence( + ByteString.copyFrom( + new byte[AccountCharacterCreatePublicSourceClient.MAX_SOURCE_WIRE_BYTES])) + .build()); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.RESOURCE_EXHAUSTED)); + assertThat(owner.received).containsExactly(fixture.request()); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static AccountCharacterCreatePublicSourceClient client(Owner owner) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + owner.server.getPort()); + return new AccountCharacterCreatePublicSourceClient( + endpoints, + pki.clientProperties(directory, pki.identity("account")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Owner owner(String name) throws Exception { + var response = new AtomicReference<>(fixture.response()); + var received = new CopyOnWriteArrayList(); + var targetResponse = new AtomicReference<>(targetResponse()); + var targetReceived = new CopyOnWriteArrayList(); + var targetError = new AtomicReference(); + var identity = pki.identity(name); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + new CharacterCreatePublicSourceServiceGrpc + .CharacterCreatePublicSourceServiceImplBase() { + @Override + public void readCharacterCreatePublicSource( + ReadCharacterCreatePublicSourceRequest request, + StreamObserver observer) { + received.add(request); + observer.onNext(response.get()); + observer.onCompleted(); + } + + @Override + public void resolveCharacterCreatePublicTarget( + ResolveCharacterCreatePublicTargetRequest request, + StreamObserver observer) { + targetReceived.add(request); + var error = targetError.get(); + if (error != null) { + observer.onError(error.asRuntimeException()); + return; + } + observer.onNext(targetResponse.get()); + observer.onCompleted(); + } + }) + .build() + .start(); + return new Owner(server, response, received, targetResponse, targetReceived, targetError); + } + + private record Owner( + Server server, + AtomicReference response, + List received, + AtomicReference targetResponse, + List targetReceived, + AtomicReference targetError) + implements AutoCloseable { + @Override + public void close() throws InterruptedException { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private record Fixture( + ReadCharacterCreatePublicSourceRequest request, + ReadCharacterCreatePublicSourceResponse response, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence world) {} + + // Common's authored-core fixture lives in its private unit-test source and is not exported. + // Build only the owner-shaped values needed here, using the exported World fixture and real + // codecs. + private static Fixture fixture() throws Exception { + return fixture("canonical-instance-launch-descriptor"); + } + + private static Fixture fixture(String descriptorId) throws Exception { + var originalWorld = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + var originalDescriptor = originalWorld.launchBinding().descriptor(); + var selector = originalWorld.launchBinding().releaseAttestation().worldStartLocationEvidence(); + var tenant = originalWorld.request().canonicalTenantId(); + var version = originalWorld.request().canonicalVersionId(); + var intakeId = UUID.randomUUID(); + var operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, intakeId, tenant, "tenant-key", "synthetic-world", "Synthetic World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + evidenceDigest); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + intakeId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + intakeId, + operationId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "world-lifecycle-control-request", + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + 19L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + descriptorId, + 42L, + false, + null, + "{}", + originalDescriptor.generationConfigRevision(), + 9L, + 7L, + originalDescriptor.publishedReleaseBundleRef(), + false, + null); + var oldRelease = originalWorld.launchBinding().releaseAttestation(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + tenant, + version, + descriptor.worldSlug(), + source.operationId(), + evidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + oldRelease.publishWorkflowId(), + oldRelease.commitId(), + oldRelease.participantDigests(), + oldRelease.manifestHash(), + oldRelease.manifestSchemaVersion(), + oldRelease.requiredManifestAssetKeys(), + oldRelease.artifactDigests(), + oldRelease.commandDefinitions(), + oldRelease.generationConfigRevision(), + selector); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + FIXTURE_ID, + NAMESPACE, + tenant, + descriptor.worldSlug(), + originalWorld.request().canonicalGameInstanceId(), + originalWorld.request().playableStateNamespaceId(), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + version, + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var world = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + new CompleteLaunchBindingEvidence(descriptor, release), + originalWorld.startLocation(), + originalWorld.runtimeRoomInstanceId(), + "ACTIVE", + 7L, + originalWorld.rowVersion(), + originalWorld.captureId(), + originalWorld.graphSha256(), + originalWorld.preparationInputDigest(), + originalWorld.operationalRegionAssignments()); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + 19L, + version, + UUID.fromString(selector.request().appliedCommitId()), + selector.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + intakeId, + operationId, + source.operationId(), + descriptor.worldSlug(), + evidenceDigest, + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), + receipt); + var readRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + FIXTURE_ID, + postTuple(tenant, NAMESPACE).canonicalBytes(), + FIXTURE_ID, + 8L, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + version, + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(release.publishWorkflowId()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) + .setCanonicalTenantId(tenant.toString()) + .setCanonicalVersionId(version.toString()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (var participant : release.participantDigests()) { + var item = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + bundle.addParticipantDigests(item); + } + var authored = + new AuthoredInitialActorCoreReadEvidence.ReadResult( + readRequest, + new StartSessionTemplateAssociationReadEvidence.Result( + readRequest, association, bundle.build(), selector, 23L), + descriptor, + List.of( + AuthoredInitialActorCoreProjection.fromValidatedBinding( + FIXTURE_ID, sourceBinding(association, association.sourceOperationId())))); + var request = + ReadCharacterCreatePublicSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(FIXTURE_ID.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(tenant.toString()) + .setRealmId(FIXTURE_ID.toString()) + .setWorldSlug(descriptor.worldSlug()) + .setRealmSlug("realm") + .setPlayableStateNamespaceId(lifecycleRequest.playableStateNamespaceId().toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) + .setCatalogRevision(3L) + .setPointerVersion(5L) + .setEvaluatedAt("2026-10-24T00:00:00Z") + .setConnectScopeExpiresAt("2026-10-24T00:05:00Z") + .build(); + var response = + ReadCharacterCreatePublicSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog( + CharacterCreatePublicCatalog.newBuilder() + .setTenantId(tenant.toString()) + .setTenantSlug("tenant") + .setWorldSlug(request.getWorldSlug()) + .setWorldDisplayName("Synthetic World") + .setRealmId(request.getRealmId()) + .setRealmSlug("realm") + .setRealmDisplayName("Realm") + .setVisible(true) + .setPublicProduction(true) + .setStateScope("SHARED") + .setPlayableStateNamespaceId(request.getPlayableStateNamespaceId()) + .setCharacterCreationPolicy("PLAYER_CREATED") + .setCatalogRevision(3L) + .setCreationRequestId(FIXTURE_ID.toString()) + .setReceiptDigest(digest('a'))) + .setPointer( + CharacterCreatePublicPointer.newBuilder() + .setTenantId(tenant.toString()) + .setRealmId(request.getRealmId()) + .setWorldSlug(request.getWorldSlug()) + .setRealmSlug("realm") + .setAdmissionState("OPEN") + .setAdmissibleGameInstanceId(request.getCanonicalGameInstanceId()) + .setPointerVersion(5L) + .setCatalogRevision(3L) + .setUpdatedAt("2026-10-24T00:00:00.123456789Z") + .setInitialAdmissionRequestId("initial-admission") + .setInitialAdmissionOwnerProofDigest(digest('b')) + .setAdmissionPointerSnapshotDigest("c".repeat(64))) + .setCanonicalVersionId(version.toString()) + .setActiveLifecycleEpoch(7L) + .setOriginalControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setOriginalOwnerAttemptId(FIXTURE_ID.toString()) + .setOriginalOwnerFence(8L) + .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) + .setWorldLifecycleEvidence(ByteString.copyFrom(world.canonicalBytes())) + .build(); + return new Fixture(request, response, authored, world); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + UUID tenant, String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-lifecycle-control-request", + FIXTURE_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(19L, FIXTURE_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact original selected authored actor core")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + FIXTURE_ID, + 19L, + authorityBundle(pre, tenant, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID tenant, String namespace) { + String tenantText = tenant.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantText, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", FIXTURE_ID.toString(), + "applicableTenantId", tenantText), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", FIXTURE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantText, 3L), + "membershipAuthorityGeneration", Map.of(tenantText, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantText, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + FIXTURE_ID.toString(), + "controlUiTokenJti", + FIXTURE_ID.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding( + StartSessionTemplateAssociationReadEvidence.Association association, + UUID worldSourceOperationId) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":3,\"worldSlug\":\"" + + association.worldSlug() + + "\",\"worldDisplayName\":\"Synthetic World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" + + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," + + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", + tools.jackson.databind.json.JsonMapper.builder().build()); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor_created", + Audience.SOURCE_ACTOR, + "welcome_message", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + UUID.fromString("13333333-3333-4333-8333-333333333333"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + TargetProof target = + new TargetProof( + association.canonicalTenantId(), + association.canonicalVersionId(), + 23L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + UUID.fromString("1eeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + association.selectedCommitId(), + "base-0", + revisions, + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + association.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + association.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); + var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); + var dispositionEntry = + new GameplayRuleSource.Entry( + Family.DISPOSITIONS, + disposition, + commit, + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444")); + var feedbackEntry = + new GameplayRuleSource.Entry( + Family.FEEDBACK, + feedback, + commit, + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555")); + var gameplay = + new GameplayRuleSelectedSource( + gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + association.sourceEvidenceDigest(), + association.worldSlug(), + association.publishWorkflowId(), + bytes("selected publication operation bytes"), + bytes("selected release terminal evidence"), + commit, + policySnapshot, + gameplay) + .getFirst(); + } + + private static String gameplaySnapshot( + DraftCommitBinding binding, List entries) { + Map families = new java.util.LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family.name(), + entries.stream() + .filter(value -> value.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + var manifest = + GameplayRuleManifest.fromStored( + GameplayRuleManifest.canonical( + Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); + Map snapshot = new java.util.LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return CommandSource.canonical(snapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwnerTest.java new file mode 100644 index 0000000000..8cd8030b2a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeOwnerTest.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import java.time.*; +import java.util.*; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.*; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +/** Controlled owner composition. This does not establish real signing, RPC or SQL authority. */ +class AccountCharacterCreateScopeOwnerTest { + private final JwtUtil jwt = mock(JwtUtil.class); + private final FreshTenantIdentityAssociationRepository tenants = + mock(FreshTenantIdentityAssociationRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final AccountCanonicalConnectScopeReader reader = + mock(AccountCanonicalConnectScopeReader.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountCharacterCreatePrincipal principal = + mock(AccountCharacterCreatePrincipal.class); + private final AccountPlayerBootstrapCallerVerifier.VerifiedCaller caller = + mock(AccountPlayerBootstrapCallerVerifier.VerifiedCaller.class); + private final AccountCharacterCreatePublicSourceClient.AuthenticatedTarget target = + mock(AccountCharacterCreatePublicSourceClient.AuthenticatedTarget.class); + private final ResolveCharacterCreatePublicTargetResponse response = + mock(ResolveCharacterCreatePublicTargetResponse.class, RETURNS_DEEP_STUBS); + private final UUID account = UUID.randomUUID(), tenant = UUID.randomUUID(); + private final Instant now = Instant.parse("2026-11-16T00:00:00Z"); + + private AccountCharacterCreateScopeOwner owner() { + var properties = mock(AccountTokenProperties.class); + when(properties.getConnectScopeExpirationMs()).thenReturn(60000L); + return new AccountCharacterCreateScopeOwner( + "proof", + jwt, + Clock.fixed(now, ZoneOffset.UTC), + properties, + tenants, + scopes, + reader, + transactions); + } + + private void target() { + when(principal.authenticateCurrentCaller()).thenReturn(caller); + when(caller.accountUuid()).thenReturn(account); + when(caller.accountId()).thenReturn(42L); + when(principal.authenticateCurrentAccount()).thenReturn(account); + when(target.response()).thenReturn(response); + when(response.getRequest().getTargetNamespace()).thenReturn("proof"); + var catalog = response.getCatalog(); + when(catalog.getVisible()).thenReturn(true); + when(catalog.getPublicProduction()).thenReturn(true); + when(catalog.getStateScope()).thenReturn("SHARED"); + when(catalog.getCharacterCreationPolicy()).thenReturn("PLAYER_CREATED"); + when(catalog.getTenantId()).thenReturn(tenant.toString()); + when(catalog.getRealmId()).thenReturn(UUID.randomUUID().toString()); + when(catalog.getTenantSlug()).thenReturn("tenant"); + when(catalog.getWorldSlug()).thenReturn("world"); + when(catalog.getRealmSlug()).thenReturn("realm"); + when(catalog.getPlayableStateNamespaceId()).thenReturn(UUID.randomUUID().toString()); + when(catalog.getCatalogRevision()).thenReturn(1L); + when(response.getCanonicalGameInstanceId()).thenReturn(UUID.randomUUID().toString()); + when(response.getPointer().getPointerVersion()).thenReturn(1L); + } + + @Test + void preseededTargetNeverMintsCreationScope() { + target(); + when(response.getCatalog().getCharacterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + assertThatThrownBy(() -> owner().issueCanonicalCharacterCreateScope(principal, target)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(jwt, scopes, tenants, reader, transactions); + } + + @Test + void wrongNamespaceNeverMintsCreationScope() { + target(); + when(response.getRequest().getTargetNamespace()).thenReturn("other"); + assertThatThrownBy(() -> owner().issueCanonicalCharacterCreateScope(principal, target)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(jwt, scopes, tenants, reader, transactions); + } + + @Test + void persistsExactSignedTargetWithCurrentTenantAndReadsItBack() { + target(); + var signed = mock(Claims.class); + Jws jws = mock(Jws.class); + when(jws.getPayload()).thenReturn(signed); + when(jwt.parseToken("signed-scope")).thenReturn(jws); + when(jwt.generateToken(eq(account.toString()), eq(now.plusSeconds(60)), anyMap())) + .thenAnswer( + call -> { + Map claims = call.getArgument(2); + when(signed.get(anyString())).thenAnswer(read -> claims.get(read.getArgument(0))); + when(signed.getSubject()).thenReturn(account.toString()); + when(signed.getExpiration()).thenReturn(Date.from(now.plusSeconds(60))); + when(signed.getIssuedAt()).thenReturn(Date.from(now)); + return "signed-scope"; + }); + var source = mock(FreshTenantCreationEvidence.class); + when(source.targetNamespace()).thenReturn("proof"); + when(source.canonicalTenantId()).thenReturn(tenant); + when(source.operationId()).thenReturn(UUID.randomUUID()); + when(source.evidenceDigest()).thenReturn("sha256:" + "a".repeat(64)); + when(tenants.read(tenant)).thenReturn(Optional.of(source)); + final CanonicalJoinScopeV2[] retained = new CanonicalJoinScopeV2[1]; + doAnswer( + call -> { + retained[0] = call.getArgument(1); + return null; + }) + .when(scopes) + .insertCanonical(eq(42L), any(), any()); + when(reader.read(account, "signed-scope")).thenAnswer(call -> retained[0]); + var result = owner().issueCanonicalCharacterCreateScope(principal, target); + assertThat(result).isSameAs(retained[0]); + assertThat(result.accountId()).isEqualTo(account); + assertThat(result.tenantId()).isEqualTo(tenant); + assertThat(result.connectScopeExpiresAt()).isEqualTo(now.plusSeconds(60).toString()); + verify(principal, times(2)).authenticateCurrentAccount(); + verify(scopes).insertCanonical(eq(42L), eq(result), any()); + verify(reader).read(account, "signed-scope"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeServiceTest.java new file mode 100644 index 0000000000..aa81451660 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateScopeServiceTest.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreatePublicSourceClient.AuthenticatedTarget; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import org.junit.jupiter.api.Test; + +/** Controlled composition proof; mocked capabilities do not establish genuine owner authority. */ +class AccountCharacterCreateScopeServiceTest { + private final AccountCharacterCreateScopeOwner accounts = + mock(AccountCharacterCreateScopeOwner.class); + private final AccountCharacterCreatePublicSourceClient sources = + mock(AccountCharacterCreatePublicSourceClient.class); + private final AccountCharacterCreatePrincipal principal = + mock(AccountCharacterCreatePrincipal.class); + private final AccountCharacterCreateScopeService service = + new AccountCharacterCreateScopeService("scope-proof", accounts, sources); + + @Test + void authenticatesBeforeResolvingFriendlySelectorsAndIssuingFromOwnerCapability() { + UUID read = UUID.randomUUID(); + when(principal.authenticateCurrentAccount()).thenReturn(UUID.randomUUID()); + AuthenticatedTarget target = target("scope-proof"); + when(sources.resolve("demo", "production", read)).thenReturn(target); + CanonicalJoinScopeV2 scope = mock(CanonicalJoinScopeV2.class); + when(accounts.issueCanonicalCharacterCreateScope(principal, target)).thenReturn(scope); + + assertThat(service.issue(principal, "demo", "production", read)).isSameAs(scope); + var order = inOrder(principal, sources, accounts); + order.verify(principal).authenticateCurrentAccount(); + order.verify(sources).resolve("demo", "production", read); + order.verify(accounts).issueCanonicalCharacterCreateScope(principal, target); + } + + @Test + void deniesDifferentNamespaceBeforeAccountIssuance() { + UUID read = UUID.randomUUID(); + AuthenticatedTarget target = target("other-namespace"); + when(sources.resolve("demo", "production", read)).thenReturn(target); + assertThatThrownBy(() -> service.issue(principal, "demo", "production", read)) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(accounts); + } + + @Test + void bootstrapRevocationStopsBeforeTargetRead() { + when(principal.authenticateCurrentAccount()).thenThrow(new IllegalStateException("revoked")); + assertThatThrownBy(() -> service.issue(principal, "demo", "production", UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(sources, accounts); + } + + @Test + void verificationUsesOnlyConfiguredNamespaceAndActualAccountOwner() { + CanonicalJoinScopeV2 scope = mock(CanonicalJoinScopeV2.class); + when(accounts.verifyCanonicalCharacterCreateScope(principal, "opaque-scope", "scope-proof")) + .thenReturn(scope); + assertThat(service.verify(principal, "opaque-scope")).isSameAs(scope); + verifyNoInteractions(sources); + } + + private static AuthenticatedTarget target(String namespace) { + AuthenticatedTarget target = mock(AuthenticatedTarget.class); + when(target.response()) + .thenReturn( + ResolveCharacterCreatePublicTargetResponse.newBuilder() + .setRequest( + ResolveCharacterCreatePublicTargetRequest.newBuilder() + .setTargetNamespace(namespace)) + .build()); + return target; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateServiceTest.java new file mode 100644 index 0000000000..65e713976d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateServiceTest.java @@ -0,0 +1,451 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateOwnerClients.ResolvedSource; +import net.firedevops.firemud.accountservice.charactercreate.AccountCharacterCreateRepository.Protection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +/** + * Controlled dependency proof; this does not establish bootstrap JWT or coupled owner authority. + */ +class AccountCharacterCreateServiceTest { + private static final String NAMESPACE = "character-create-proof"; + private static final Instant NOW = Instant.parse("2026-10-24T00:00:00Z"); + private final AccountCharacterCreateRepository repository = + mock(AccountCharacterCreateRepository.class); + private final AccountCharacterCreateOwnerClients owners = + mock(AccountCharacterCreateOwnerClients.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountCharacterCreatePrincipal principal = + mock(AccountCharacterCreatePrincipal.class); + private final AccountCharacterCreateIntent intent = + AccountCharacterCreateTestActions.intent( + NAMESPACE, UUID.randomUUID(), UUID.randomUUID(), NOW.plusSeconds(300)); + private final Protection protection = + new Protection(intent, UUID.randomUUID(), 17L, NOW, new byte[] {1}, new byte[] {2}); + + @AfterEach + void clearContext() { + SessionContext.clear(); + } + + @Test + void commitsOriginalIntentAndProtectionReadbackBeforeDelegating() { + principal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.empty()); + when(owners.resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId())) + .thenReturn(new ResolvedSource(intent.actionBytes(), intent.originalSourceReadback())); + when(repository.retain(any())).thenReturn(intent); + readyOriginal(); + + service().submit(principal, intent.createCharacterRequestId(), intent.connectScopeId()); + + var order = inOrder(principal, repository, owners, transactions); + order.verify(principal).authenticateCurrentAccount(); + order + .verify(repository) + .findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId()); + order.verify(transactions).commit(any()); + order.verify(owners).resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId()); + order.verify(repository).retain(any()); + order.verify(transactions).commit(any()); + order.verify(repository).findOperation(NAMESPACE, intent.operationId()); + order.verify(transactions).commit(any()); + order.verify(owners).requireExactOriginalSource(intent); + order.verify(principal).authenticateCurrentAccount(); + order.verify(repository).acquire(intent); + order.verify(transactions).commit(any()); + order.verify(repository).findProtection(intent); + order.verify(transactions).commit(any()); + order.verify(principal).authenticateCurrentAccount(); + order.verify(owners).delegateProtected(intent, protection); + } + + @Test + void revocationDuringOriginalSourceReadCannotAcquireProtection() { + readyOriginal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + var denied = new IllegalStateException("credential revoked"); + when(principal.authenticateCurrentAccount()).thenReturn(intent.accountId()).thenThrow(denied); + assertThatThrownBy( + () -> + service() + .submit(principal, intent.createCharacterRequestId(), intent.connectScopeId())) + .isSameAs(denied); + verify(owners).requireExactOriginalSource(intent); + verify(repository, never()).acquire(any()); + verify(owners, never()).delegateProtected(any(), any()); + } + + @Test + void revocationAfterProtectionCommitCannotDelegateOrEraseProtection() { + readyOriginal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + var denied = new IllegalStateException("credential revoked"); + when(principal.authenticateCurrentAccount()) + .thenReturn(intent.accountId(), intent.accountId()) + .thenThrow(denied); + assertThatThrownBy( + () -> + service() + .submit(principal, intent.createCharacterRequestId(), intent.connectScopeId())) + .isSameAs(denied); + verify(repository).acquire(intent); + verify(repository).findProtection(intent); + verify(owners, never()).delegateProtected(any(), any()); + verify(repository, never()).settle(any(), any()); + } + + @Test + void invalidOpaqueScopesFailBeforeAnySourceOrStorageAccess() { + principal(); + for (String scope : List.of("", " \t\n", "s".repeat(2049))) { + assertThatThrownBy( + () -> service().submit(principal, intent.createCharacterRequestId(), scope)) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(repository, owners, transactions); + } + + @Test + void retriesUseOriginalSourceWithoutResolvingNewTarget() { + principal(); + readyOriginal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + + service().submit(principal, intent.createCharacterRequestId(), intent.connectScopeId()); + + verify(owners, never()).resolvePublicProduction(any(), any(), any()); + verify(repository, never()).retain(any()); + verify(owners).requireExactOriginalSource(intent); + verify(owners).delegateProtected(intent, protection); + } + + @Test + void changedConnectScopeCannotBorrowOriginalIntent() { + principal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + + assertThatThrownBy( + () -> + service() + .submit(principal, intent.createCharacterRequestId(), "changed-issued-scope")) + .isInstanceOf(StatusRuntimeException.class); + + verifyNoInteractions(owners); + verify(repository, never()).acquire(any()); + } + + @Test + void originalSourceReadbackFailureCannotAcquireOrDelegate() { + principal(); + readyOriginal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + doThrow(Status.UNAVAILABLE.asRuntimeException()) + .when(owners) + .requireExactOriginalSource(intent); + + assertThatThrownBy( + () -> + service() + .submit(principal, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class); + + verify(repository, never()).acquire(any()); + verify(owners, never()).delegateProtected(any(), any()); + } + + @Test + void expiryCannotDelegateOrReleaseAnExistingProtection() { + principal(); + readyOriginal(); + when(repository.findOriginal(NAMESPACE, intent.accountId(), intent.createCharacterRequestId())) + .thenReturn(Optional.of(intent)); + var service = + new AccountCharacterCreateService( + repository, + owners, + transactions, + NAMESPACE, + Clock.fixed(NOW.plusSeconds(300), ZoneOffset.UTC)); + + assertThatThrownBy( + () -> + service.submit( + principal, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("expired"); + + verify(repository, never()).acquire(any()); + verify(owners, never()).delegateProtected(any(), any()); + } + + @Test + void missingCapabilityAndGenericSessionContextsCannotReachOwnerSources() { + assertThatThrownBy( + () -> + service().submit(null, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class); + SessionContext.setContext(intent.accountId().toString(), List.of("player"), Map.of()); + assertThatThrownBy( + () -> + service().submit(null, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class); + SessionContext.setContext( + intent.accountId().toString(), + List.of("admin"), + Map.of(), + true, + "game-session-service", + "controlled-instance"); + assertThatThrownBy( + () -> + service().submit(null, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository, owners, transactions); + } + + @Test + void failedPrincipalRevalidationCannotReachStorageOrOwnerSources() { + when(principal.authenticateCurrentAccount()) + .thenThrow(Status.UNAUTHENTICATED.asRuntimeException()); + + assertThatThrownBy( + () -> + service() + .submit(principal, intent.createCharacterRequestId(), intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class); + + verifyNoInteractions(repository, owners, transactions); + } + + @Test + void originalAndProtectionReadsRequireExactCreationOwnerPeerAndOriginalBinding() { + readyOriginal(); + assertThatThrownBy( + () -> service().readOriginalForOwner(intent.operationId(), intent.mutationDigest())) + .isInstanceOf(StatusRuntimeException.class); + peer( + NAMESPACE, + "social-groups-service", + () -> { + assertThatThrownBy( + () -> + service().readOriginalForOwner(intent.operationId(), intent.mutationDigest())) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + protection.protectionId(), + protection.protectionFence())) + .isInstanceOf(StatusRuntimeException.class); + }); + for (String workload : + List.of("entity-management-service", "game-session-service", "world-management-service")) { + peer( + "other-namespace", + workload, + () -> { + assertThatThrownBy( + () -> + service() + .readOriginalForOwner(intent.operationId(), intent.mutationDigest())) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + protection.protectionId(), + protection.protectionFence())) + .isInstanceOf(StatusRuntimeException.class); + }); + peer( + NAMESPACE, + workload, + () -> { + assertThat( + service() + .readOriginalForOwner(intent.operationId(), intent.mutationDigest()) + .sameBinding(intent)) + .isTrue(); + assertThat( + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + protection.protectionId(), + protection.protectionFence()) + .sameBinding(protection)) + .isTrue(); + assertThatThrownBy( + () -> service().readOriginalForOwner(intent.operationId(), "0".repeat(64))) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + UUID.randomUUID(), + protection.protectionFence())) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + protection.protectionId(), + protection.protectionFence() + 1L)) + .isInstanceOf(StatusRuntimeException.class); + principal(); + assertThatThrownBy( + () -> + service() + .readOriginalForOwner(intent.operationId(), intent.mutationDigest())) + .isInstanceOf(StatusRuntimeException.class); + SessionContext.setContext( + null, List.of(), Map.of(), true, workload, "controlled-instance"); + assertThatThrownBy( + () -> + service() + .readProtectionForOwner( + intent.operationId(), + intent.mutationDigest(), + protection.protectionId(), + protection.protectionFence())) + .isInstanceOf(StatusRuntimeException.class); + SessionContext.clear(); + }); + } + } + + @Test + void missingGenuineOwnerClientsAreUnavailableAndNeverAssertAbort() { + var unavailable = AccountCharacterCreateOwnerClients.unavailable(); + assertThatThrownBy( + () -> + unavailable.resolvePublicProduction(NAMESPACE, principal, intent.connectScopeId())) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + assertThatThrownBy(() -> unavailable.requireExactOriginalSource(intent)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + assertThatThrownBy(() -> unavailable.delegateProtected(intent, protection)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + } + + @Test + void immutableIntentRejectsAccountDigestPrivatePolicyAndSourceRebinding() { + assertThatThrownBy( + () -> + copy( + intent.accountId(), + "0".repeat(64), + intent.actionBytes(), + intent.originalSourceReadback())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + copy( + UUID.randomUUID(), + intent.mutationDigest(), + intent.actionBytes(), + intent.originalSourceReadback())) + .isInstanceOf(IllegalArgumentException.class); + byte[] privateAction = + new String(intent.actionBytes(), StandardCharsets.UTF_8) + .replace("\"publicProduction\":true", "\"publicProduction\":false") + .getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + copy( + intent.accountId(), + intent.mutationDigest(), + privateAction, + intent.originalSourceReadback())) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + intent.sameBinding( + copy( + intent.accountId(), + intent.mutationDigest(), + intent.actionBytes(), + new byte[] {3}))) + .isFalse(); + } + + private AccountCharacterCreateIntent copy( + UUID account, String digest, byte[] action, byte[] source) { + return new AccountCharacterCreateIntent( + intent.operationId(), + intent.createCharacterRequestId(), + intent.connectScopeId(), + account, + action, + digest, + source); + } + + private void readyOriginal() { + when(repository.findOperation(NAMESPACE, intent.operationId())).thenReturn(Optional.of(intent)); + when(repository.acquire(intent)).thenReturn(protection); + when(repository.findProtection(intent)).thenReturn(Optional.of(protection)); + } + + private AccountCharacterCreateService service() { + when(transactions.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + return new AccountCharacterCreateService( + repository, owners, transactions, NAMESPACE, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private void principal() { + when(principal.authenticateCurrentAccount()).thenReturn(intent.accountId()); + SessionContext.setContext(intent.accountId().toString(), List.of("player"), Map.of()); + } + + private static void peer(String namespace, String workload, Runnable action) { + var identity = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity).run(action); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolverTest.java new file mode 100644 index 0000000000..66c8bb59f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateSourceResolverTest.java @@ -0,0 +1,958 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.io.IOException; +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicCatalog; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicPointer; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * Actual closed source/strict action codec proof with controlled principal, scope verification and + * authenticated-transport capability mocks. The complete owner-shaped fixture is copied from the + * native source-client test; this does not establish genuine publication, bootstrap or scope + * custody. + */ +class AccountCharacterCreateSourceResolverTest { + private static final UUID FIXTURE_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + private static final String NAMESPACE = "test"; + private static final String OPAQUE_SCOPE = "Issued.Scope.Mixed_CASE-opaque"; + private final UUID account = UUID.randomUUID(); + private final AccountCharacterCreatePrincipal principal = + mock(AccountCharacterCreatePrincipal.class); + private final AccountCharacterCreateScopeService scopes = + mock(AccountCharacterCreateScopeService.class); + private final AccountCharacterCreatePublicSourceClient sources = + mock(AccountCharacterCreatePublicSourceClient.class); + private Fixture fixture; + private CanonicalJoinScopeV2 scope; + private AccountCharacterCreateSourceResolver resolver; + + @BeforeEach + void setUp() throws Exception { + fixture = fixture(); + scope = scope(fixture.request()); + resolver = new AccountCharacterCreateSourceResolver(NAMESPACE, scopes, sources); + when(principal.authenticateCurrentAccount()).thenReturn(account); + when(scopes.verify(principal, OPAQUE_SCOPE)).thenReturn(scope); + when(sources.read(any())) + .thenAnswer( + invocation -> + authenticated( + fixture.response().toBuilder() + .setRequest( + (ReadCharacterCreatePublicSourceRequest) invocation.getArgument(0)) + .build())); + } + + @Test + void buildsStrictActionFromEntireActualSourceAndRetainsEveryOwnerByte() throws Exception { + var resolved = resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE); + var response = + ReadCharacterCreatePublicSourceResponse.parseFrom(resolved.originalSourceReadback()); + var action = CharacterCreateOperatorActionCodec.decode(resolved.actionBytes()); + assertThat(CharacterCreateOperatorActionCodec.encode(action)) + .containsExactly(resolved.actionBytes()); + assertThat(resolved.originalSourceReadback()).containsExactly(response.toByteArray()); + assertThat(response.getAuthoredSource().toByteArray()) + .containsExactly(fixture.response().getAuthoredSource().toByteArray()); + assertThat(response.getWorldLifecycleEvidence()) + .isEqualTo(fixture.response().getWorldLifecycleEvidence()); + assertThat(response.getCatalog()).isEqualTo(fixture.response().getCatalog()); + assertThat(response.getPointer()).isEqualTo(fixture.response().getPointer()); + assertThat(action.target().accountId()).isEqualTo(account.toString()); + assertThat(action.expectedVersion().evaluatedAt()) + .isEqualTo(Instant.parse(scope.evaluatedAt())); + assertThat(action.expectedVersion().connectScopeExpiresAt()) + .isEqualTo(Instant.parse(scope.connectScopeExpiresAt())); + assertThat(action.expectedVersion().activeLifecycleEpoch()).isEqualTo("7"); + assertThat(action.mutation().canonicalCreationInput()).isEqualTo("{}"); + var projection = fixture.authored().projections().getFirst(); + var authored = action.mutation().authoredSource(); + assertThat(authored.bindingId()).isEqualTo(projection.bindingId().toString()); + assertThat(authored.bindingDigest()).isEqualTo(projection.bindingDigest()); + assertThat(authored.policy().canonicalPolicyJson()) + .isEqualTo(projection.policy().canonicalJson()); + assertThat(authored.core().canonicalJson()).isEqualTo(projection.core().canonicalJson()); + assertThat(authored.descriptor().canonicalJson()) + .isEqualTo(projection.descriptor().canonicalJson()); + assertThat(authored.disposition().definitionJson()) + .isEqualTo(projection.disposition().definitionJson()); + assertThat(authored.safeFeedback().definitionJson()) + .isEqualTo(projection.safeFeedback().definitionJson()); + assertThat(authored.disposition().revisionOrder()) + .isEqualTo(projection.disposition().revisionOrder()); + assertThat(authored.safeFeedback().revisionOrder()) + .isEqualTo(projection.safeFeedback().revisionOrder()); + var requested = ArgumentCaptor.forClass(ReadCharacterCreatePublicSourceRequest.class); + verify(sources).read(requested.capture()); + var request = requested.getValue(); + assertThat(request.getReadRequestId()).isNotEqualTo(fixture.request().getReadRequestId()); + assertThat(request.toBuilder().setReadRequestId(fixture.request().getReadRequestId()).build()) + .isEqualTo(fixture.request()); + var order = org.mockito.Mockito.inOrder(principal, scopes, sources); + order.verify(principal).authenticateCurrentAccount(); + order.verify(scopes).verify(principal, OPAQUE_SCOPE); + order.verify(sources).read(request); + } + + @Test + void namespacePrincipalScopeAccountAndExpiryFailuresCannotReadSource() { + assertThatThrownBy(() -> resolver.resolvePublicProduction("other", principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, null, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + when(principal.authenticateCurrentAccount()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + when(principal.authenticateCurrentAccount()).thenReturn(account); + var otherScope = + new CanonicalJoinScopeV2( + "other-opaque", + account, + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + when(scopes.verify(principal, OPAQUE_SCOPE)).thenReturn(otherScope); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + var isolated = + new CanonicalJoinScopeV2( + OPAQUE_SCOPE, + account, + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + "ISOLATED", + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + when(scopes.verify(principal, OPAQUE_SCOPE)).thenReturn(isolated); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + when(scopes.verify(principal, OPAQUE_SCOPE)) + .thenThrow(Status.PERMISSION_DENIED.withDescription("scope expired").asRuntimeException()); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .hasMessageContaining("scope expired"); + verifyNoInteractions(sources); + } + + @Test + void everyIssuedSelectorAndOriginalTimeMustMatchTheActualSourceEcho() { + for (var change : + List.>of( + request -> request.setTargetNamespace("other"), + request -> request.setReadRequestId(UUID.randomUUID().toString()), + request -> request.setCanonicalTenantId(UUID.randomUUID().toString()), + request -> request.setRealmId(UUID.randomUUID().toString()), + request -> request.setWorldSlug("other"), + request -> request.setRealmSlug("other"), + request -> request.setPlayableStateNamespaceId(UUID.randomUUID().toString()), + request -> request.setPlayableStateScope("ISOLATED"), + request -> request.setCanonicalGameInstanceId(UUID.randomUUID().toString()), + request -> request.setCatalogRevision(4), + request -> request.setPointerVersion(6), + request -> request.setEvaluatedAt("2026-10-24T00:00:01Z"), + request -> request.setConnectScopeExpiresAt("2026-10-24T00:06:00Z"))) { + doAnswer( + invocation -> { + ReadCharacterCreatePublicSourceRequest request = invocation.getArgument(0); + return authenticated( + fixture.response().toBuilder() + .setRequest(change.apply(request.toBuilder())) + .build()); + }) + .when(sources) + .read(any()); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void completeOwnerSourcesMustRefusePolicyTargetEpochAndPublicationSubstitution() { + var good = fixture.response(); + for (var changed : + List.of( + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setTenantSlug("other")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setPublicProduction(false)) + .build(), + good.toBuilder().setCatalog(good.getCatalog().toBuilder().setVisible(false)).build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setStateScope("ISOLATED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setCharacterCreationPolicy("PRESEEDED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setCatalogRevision(4)) + .build(), + good.toBuilder().setPointer(good.getPointer().toBuilder().setPointerVersion(6)).build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setAdmissionState("CLOSED")) + .build(), + good.toBuilder().setCanonicalVersionId(UUID.randomUUID().toString()).build(), + good.toBuilder().setActiveLifecycleEpoch(8).build(), + good.toBuilder().setOriginalOwnerFence(9).build(), + good.toBuilder().setOriginalOwnerAttemptId(UUID.randomUUID().toString()).build(), + good.toBuilder().setOriginalControlPlaneRequestId("substituted").build(), + good.toBuilder().clearAuthoredSource().build(), + good.toBuilder() + .setAuthoredSource(good.getAuthoredSource().toBuilder().clearProjections()) + .build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder() + .addProjections(good.getAuthoredSource().getProjections(0))) + .build(), + good.toBuilder().setWorldLifecycleEvidence(ByteString.copyFromUtf8("{}")).build(), + good.toBuilder().setUnknownFields(unknown()).build())) { + doAnswer( + invocation -> + authenticated( + changed.toBuilder() + .setRequest( + (ReadCharacterCreatePublicSourceRequest) invocation.getArgument(0)) + .build())) + .when(sources) + .read(any()); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void historicalRereadUsesExactOriginalRequestAndFullBytesWithoutScopeOrClockRefresh() + throws Exception { + var resolved = resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE); + var intent = intent(resolved); + var original = + ReadCharacterCreatePublicSourceResponse.parseFrom(intent.originalSourceReadback()); + clearInvocations(principal, scopes, sources); + + resolver.requireExactOriginalSource(intent); + + verify(sources).read(original.getRequest()); + verifyNoInteractions(principal, scopes); + // Metadata omitted by the action itself is still exact historical source authority. + doReturn( + authenticated( + original.toBuilder() + .setCatalog(original.getCatalog().toBuilder().setReceiptDigest(digest('f'))) + .build())) + .when(sources) + .read(original.getRequest()); + assertThatThrownBy(() -> resolver.requireExactOriginalSource(intent)) + .isInstanceOf(RuntimeException.class); + } + + @Test + void malformedNoncanonicalAndReboundRetainedSourceFailsBeforeReread() throws Exception { + var resolved = resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE); + var original = + ReadCharacterCreatePublicSourceResponse.parseFrom(resolved.originalSourceReadback()); + clearInvocations(sources); + // Duplicate schema tag is parseable, but its closed roundtrip differs. + byte[] duplicate = + Arrays.copyOf( + resolved.originalSourceReadback(), resolved.originalSourceReadback().length + 2); + duplicate[duplicate.length - 2] = 8; + duplicate[duplicate.length - 1] = 1; + for (byte[] invalid : + List.of( + new byte[] {1}, + duplicate, + original.toBuilder().setUnknownFields(unknown()).build().toByteArray(), + original.toBuilder().setActiveLifecycleEpoch(8).build().toByteArray())) { + var changed = + new AccountCharacterCreateIntent( + UUID.randomUUID(), + UUID.randomUUID(), + OPAQUE_SCOPE, + account, + resolved.actionBytes(), + CharacterCreateOperatorActionCodec.mutationDigest(resolved.actionBytes()), + invalid); + assertThatThrownBy(() -> resolver.requireExactOriginalSource(changed)) + .isInstanceOf(RuntimeException.class); + } + verifyNoInteractions(sources); + } + + @Test + void unavailableOwnerAndSourceOnlyDelegationRemainFailClosed() { + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(sources).read(any()); + assertThatThrownBy(() -> resolver.resolvePublicProduction(NAMESPACE, principal, OPAQUE_SCOPE)) + .hasMessageContaining("UNAVAILABLE"); + clearInvocations(sources); + assertThatThrownBy(() -> resolver.delegateProtected(null, null)) + .hasMessageContaining("UNAVAILABLE"); + verifyNoInteractions(sources); + } + + private AccountCharacterCreateIntent intent( + AccountCharacterCreateOwnerClients.ResolvedSource source) { + return new AccountCharacterCreateIntent( + UUID.randomUUID(), + UUID.randomUUID(), + OPAQUE_SCOPE, + account, + source.actionBytes(), + CharacterCreateOperatorActionCodec.mutationDigest(source.actionBytes()), + source.originalSourceReadback()); + } + + private CanonicalJoinScopeV2 scope(ReadCharacterCreatePublicSourceRequest request) { + return new CanonicalJoinScopeV2( + OPAQUE_SCOPE, + account, + UUID.fromString(request.getCanonicalTenantId()), + UUID.fromString(request.getRealmId()), + fixture.response().getCatalog().getTenantSlug(), + request.getWorldSlug(), + request.getRealmSlug(), + UUID.fromString(request.getPlayableStateNamespaceId()), + request.getPlayableStateScope(), + UUID.fromString(request.getCanonicalGameInstanceId()), + request.getCatalogRevision(), + request.getPointerVersion(), + request.getEvaluatedAt(), + request.getConnectScopeExpiresAt()); + } + + private static AccountCharacterCreatePublicSourceClient.AuthenticatedSource authenticated( + ReadCharacterCreatePublicSourceResponse response) { + var capability = mock(AccountCharacterCreatePublicSourceClient.AuthenticatedSource.class); + when(capability.response()).thenReturn(response); + return capability; + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private record Fixture( + ReadCharacterCreatePublicSourceRequest request, + ReadCharacterCreatePublicSourceResponse response, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence world) {} + + // Common's authored-core fixture lives in its private unit-test source and is not exported. + // Build only the owner-shaped values needed here, using the exported World fixture and real + // codecs. + private static Fixture fixture() throws Exception { + return fixture("canonical-instance-launch-descriptor"); + } + + private static Fixture fixture(String descriptorId) throws Exception { + var originalWorld = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + var originalDescriptor = originalWorld.launchBinding().descriptor(); + var selector = originalWorld.launchBinding().releaseAttestation().worldStartLocationEvidence(); + var tenant = originalWorld.request().canonicalTenantId(); + var version = originalWorld.request().canonicalVersionId(); + var intakeId = UUID.randomUUID(); + var operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, intakeId, tenant, "tenant-key", "synthetic-world", "Synthetic World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + evidenceDigest); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + intakeId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + intakeId, + operationId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "world-lifecycle-control-request", + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + 19L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + descriptorId, + 42L, + false, + null, + "{}", + originalDescriptor.generationConfigRevision(), + 9L, + 7L, + originalDescriptor.publishedReleaseBundleRef(), + false, + null); + var oldRelease = originalWorld.launchBinding().releaseAttestation(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + tenant, + version, + descriptor.worldSlug(), + source.operationId(), + evidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + oldRelease.publishWorkflowId(), + oldRelease.commitId(), + oldRelease.participantDigests(), + oldRelease.manifestHash(), + oldRelease.manifestSchemaVersion(), + oldRelease.requiredManifestAssetKeys(), + oldRelease.artifactDigests(), + oldRelease.commandDefinitions(), + oldRelease.generationConfigRevision(), + selector); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + FIXTURE_ID, + NAMESPACE, + tenant, + descriptor.worldSlug(), + originalWorld.request().canonicalGameInstanceId(), + originalWorld.request().playableStateNamespaceId(), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + version, + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var world = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + new CompleteLaunchBindingEvidence(descriptor, release), + originalWorld.startLocation(), + originalWorld.runtimeRoomInstanceId(), + "ACTIVE", + 7L, + originalWorld.rowVersion(), + originalWorld.captureId(), + originalWorld.graphSha256(), + originalWorld.preparationInputDigest(), + originalWorld.operationalRegionAssignments()); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + 19L, + version, + UUID.fromString(selector.request().appliedCommitId()), + selector.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + intakeId, + operationId, + source.operationId(), + descriptor.worldSlug(), + evidenceDigest, + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), + receipt); + var readRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + FIXTURE_ID, + postTuple(tenant, NAMESPACE).canonicalBytes(), + FIXTURE_ID, + 8L, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + version, + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(release.publishWorkflowId()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) + .setCanonicalTenantId(tenant.toString()) + .setCanonicalVersionId(version.toString()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (var participant : release.participantDigests()) { + var item = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + bundle.addParticipantDigests(item); + } + var authored = + new AuthoredInitialActorCoreReadEvidence.ReadResult( + readRequest, + new StartSessionTemplateAssociationReadEvidence.Result( + readRequest, association, bundle.build(), selector, 23L), + descriptor, + List.of( + AuthoredInitialActorCoreProjection.fromValidatedBinding( + FIXTURE_ID, sourceBinding(association, association.sourceOperationId())))); + var request = + ReadCharacterCreatePublicSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(FIXTURE_ID.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(tenant.toString()) + .setRealmId(FIXTURE_ID.toString()) + .setWorldSlug(descriptor.worldSlug()) + .setRealmSlug("realm") + .setPlayableStateNamespaceId(lifecycleRequest.playableStateNamespaceId().toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) + .setCatalogRevision(3L) + .setPointerVersion(5L) + .setEvaluatedAt("2026-10-24T00:00:00Z") + .setConnectScopeExpiresAt("2026-10-24T00:05:00Z") + .build(); + var response = + ReadCharacterCreatePublicSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog( + CharacterCreatePublicCatalog.newBuilder() + .setTenantId(tenant.toString()) + .setTenantSlug("tenant") + .setWorldSlug(request.getWorldSlug()) + .setWorldDisplayName("Synthetic World") + .setRealmId(request.getRealmId()) + .setRealmSlug("realm") + .setRealmDisplayName("Realm") + .setVisible(true) + .setPublicProduction(true) + .setStateScope("SHARED") + .setPlayableStateNamespaceId(request.getPlayableStateNamespaceId()) + .setCharacterCreationPolicy("PLAYER_CREATED") + .setCatalogRevision(3L) + .setCreationRequestId(FIXTURE_ID.toString()) + .setReceiptDigest(digest('a'))) + .setPointer( + CharacterCreatePublicPointer.newBuilder() + .setTenantId(tenant.toString()) + .setRealmId(request.getRealmId()) + .setWorldSlug(request.getWorldSlug()) + .setRealmSlug("realm") + .setAdmissionState("OPEN") + .setAdmissibleGameInstanceId(request.getCanonicalGameInstanceId()) + .setPointerVersion(5L) + .setCatalogRevision(3L) + .setUpdatedAt("2026-10-24T00:00:00.123456789Z") + .setInitialAdmissionRequestId("initial-admission") + .setInitialAdmissionOwnerProofDigest(digest('b')) + .setAdmissionPointerSnapshotDigest("c".repeat(64))) + .setCanonicalVersionId(version.toString()) + .setActiveLifecycleEpoch(7L) + .setOriginalControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setOriginalOwnerAttemptId(FIXTURE_ID.toString()) + .setOriginalOwnerFence(8L) + .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) + .setWorldLifecycleEvidence(ByteString.copyFrom(world.canonicalBytes())) + .build(); + return new Fixture(request, response, authored, world); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + UUID tenant, String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-lifecycle-control-request", + FIXTURE_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(19L, FIXTURE_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact original selected authored actor core")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + FIXTURE_ID, + 19L, + authorityBundle(pre, tenant, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID tenant, String namespace) { + String tenantText = tenant.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantText, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", FIXTURE_ID.toString(), + "applicableTenantId", tenantText), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", FIXTURE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantText, 3L), + "membershipAuthorityGeneration", Map.of(tenantText, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantText, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + FIXTURE_ID.toString(), + "controlUiTokenJti", + FIXTURE_ID.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding( + StartSessionTemplateAssociationReadEvidence.Association association, + UUID worldSourceOperationId) { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":3,\"worldSlug\":\"" + + association.worldSlug() + + "\",\"worldDisplayName\":\"Synthetic World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" + + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," + + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", + tools.jackson.databind.json.JsonMapper.builder().build()); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor_created", + Audience.SOURCE_ACTOR, + "welcome_message", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + UUID.fromString("13333333-3333-4333-8333-333333333333"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + TargetProof target = + new TargetProof( + association.canonicalTenantId(), + association.canonicalVersionId(), + 23L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + UUID.fromString("1eeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + association.selectedCommitId(), + "base-0", + revisions, + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + association.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + association.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); + var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); + var dispositionEntry = + new GameplayRuleSource.Entry( + Family.DISPOSITIONS, + disposition, + commit, + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444")); + var feedbackEntry = + new GameplayRuleSource.Entry( + Family.FEEDBACK, + feedback, + commit, + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555")); + var gameplay = + new GameplayRuleSelectedSource( + gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + association.sourceEvidenceDigest(), + association.worldSlug(), + association.publishWorkflowId(), + bytes("selected publication operation bytes"), + bytes("selected release terminal evidence"), + commit, + policySnapshot, + gameplay) + .getFirst(); + } + + private static String gameplaySnapshot( + DraftCommitBinding binding, List entries) { + Map families = new java.util.LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family.name(), + entries.stream() + .filter(value -> value.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + var manifest = + GameplayRuleManifest.fromStored( + GameplayRuleManifest.canonical( + Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); + Map snapshot = new java.util.LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return CommandSource.canonical(snapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java index 064af7e88b..260f737068 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -59,7 +59,7 @@ void listGameplayRealmsAppliesDeadlineAndMapsDeadlineExceeded() throws Exception } @ParameterizedTest - @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED", "AUTH_UNAVAILABLE"}) void listGameplayWorldsMapsRetryableApplicationFailuresToUnavailable(String code) throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -78,7 +78,7 @@ void listGameplayWorldsMapsRetryableApplicationFailuresToUnavailable(String code } @ParameterizedTest - @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED", "AUTH_UNAVAILABLE"}) void listGameplayRealmsMapsRetryableApplicationFailuresToUnavailable(String code) throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -112,13 +112,15 @@ void getAdmissionPointerAppliesDeadlineAndMapsUnavailable() throws Exception { verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } - @Test - void getAdmissionPointerMapsInternalApplicationFailureToUnavailable() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"INTERNAL", "AUTH_UNAVAILABLE"}) + void getAdmissionPointerMapsRetryableApplicationFailureToUnavailable(String code) + throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); when(stub.getAdmissionPointer(any())) .thenReturn( GetAdmissionPointerResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("INTERNAL").setMessage("store failed")) + .setError(ErrorDetail.newBuilder().setCode(code).setMessage("store failed")) .build()); GameSessionClient client = newClient(stub); @@ -132,15 +134,17 @@ void getAdmissionPointerMapsInternalApplicationFailureToUnavailable() throws Exc verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } - @Test - void getAdmissionPointerPreservesInvalidArgumentAsDomainFailure() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"INVALID_ARGUMENT", "NOT_FOUND", "ADMISSION_POINTER_UNAVAILABLE"}) + void getAdmissionPointerPreservesUnavailableEvidenceAsDomainFailure(String code) + throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); when(stub.getAdmissionPointer(any())) .thenReturn( GetAdmissionPointerResponse.newBuilder() .setError( ErrorDetail.newBuilder() - .setCode("INVALID_ARGUMENT") + .setCode(code) .setMessage("Unknown gameplay realm selection")) .build()); GameSessionClient client = newClient(stub); @@ -152,7 +156,8 @@ void getAdmissionPointerPreservesInvalidArgumentAsDomainFailure() throws Excepti assertThat(failure.getCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); assertThat(failure.getMessage()) .isEqualTo( - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying" + + " gameplay entry"); verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } @@ -184,14 +189,29 @@ void reachableAdmissionPointerUnavailableResponsePropagatesAsDomainFailure() thr .setCode("ADMISSION_POINTER_UNAVAILABLE") .setMessage("incomplete authority")) .build()); + when(stub.listGameplayRealms(any())) + .thenReturn( + ListGameplayRealmsResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("ADMISSION_POINTER_UNAVAILABLE") + .setMessage("incomplete authority")) + .build()); GameSessionClient client = newClient(stub); - IllegalStateException failure = - assertThrows(IllegalStateException.class, client::listGameplayWorlds); + AuthenticationException worldFailure = + assertThrows(AuthenticationException.class, client::listGameplayWorlds); + AuthenticationException realmFailure = + assertThrows(AuthenticationException.class, () -> client.listGameplayRealms("demo")); - assertThat(failure) - .hasMessage("Gameplay world discovery failed: ADMISSION_POINTER_UNAVAILABLE"); - verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + assertThat(worldFailure.getCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(realmFailure.getCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(worldFailure.getMessage()) + .isEqualTo( + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying" + + " gameplay entry"); + assertThat(realmFailure.getMessage()).isEqualTo(worldFailure.getMessage()); + verify(stub, org.mockito.Mockito.times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfigurationTest.java new file mode 100644 index 0000000000..edbc93aa6b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPlayerAdmissionReceivingConfigurationTest.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class AccountPlayerAdmissionReceivingConfigurationTest { + private final ApplicationContextRunner context = + new ApplicationContextRunner() + .withUserConfiguration(AccountPlayerAdmissionReceivingConfiguration.class); + + @Test + void absentByDefault() { + context.run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountPlayerAdmissionEntitlementGrpcService.class); + }); + } + + @ParameterizedTest + @ValueSource( + strings = { + "spring.profiles.active=isolated-player-admission-receiving", + "firemud.account.player-admission-receiving.enabled=true" + }) + void neitherSelectionAloneRegistersReceiver(String selection) { + context + .withPropertyValues(selection) + .run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountPlayerAdmissionEntitlementGrpcService.class); + }); + } + + @Test + void enabledWithoutSourceOwnerFailsClosed() { + enabled() + .withPropertyValues("firemud.grpc.workload-namespace=test") + .run(ctx -> assertThat(ctx).hasFailed()); + } + + @Test + void enabledWithoutNamespaceFailsClosed() { + enabled() + .withBean( + AccountPlayerAdmissionEntitlementOwner.class, + () -> mock(AccountPlayerAdmissionEntitlementOwner.class)) + .run(ctx -> assertThat(ctx).hasFailed()); + } + + @Test + void explicitReceivingUsesOnlySuppliedOwnerWithoutProvisioningAuthority() { + var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); + enabled() + .withPropertyValues("firemud.grpc.workload-namespace=test") + .withBean(AccountPlayerAdmissionEntitlementOwner.class, () -> owner) + .run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).hasSingleBean(AccountPlayerAdmissionEntitlementGrpcService.class); + assertThat( + ctx.getBean(AccountPlayerAdmissionEntitlementGrpcService.class) + .bindService() + .getMethods()) + .hasSize(1); + verifyNoInteractions(owner); + }); + } + + private ApplicationContextRunner enabled() { + return context.withPropertyValues( + "spring.profiles.active=isolated-player-admission-receiving", + "firemud.account.player-admission-receiving.enabled=true"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java new file mode 100644 index 0000000000..b38790fbf5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +class EmailLinkConfigurationTest { + @Test + void localAndProductionLinksUseReadOnlyFrontendLandingsAndPublicPostCompletion() { + assertProfile( + "application.yml", + "http://localhost:5173/verify-email#token=%s", + "http://localhost:5173/reset-password#token=%s"); + assertProfile( + "application-prod.yml", + "${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/verify-email#token=%s}", + "${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password#token=%s}"); + } + + @Test + void configuredPublicPostIsAcceptedWithoutBearerButGetAndNeighborsAreDenied() throws Exception { + for (String resource : List.of("application.yml", "application-prod.yml")) { + Properties properties = load(resource); + HttpAuthProperties auth = new HttpAuthProperties(); + List routes = new ArrayList<>(); + for (int index = 0; index < 32; index++) { + String prefix = "firemud.auth.http.public-routes[" + index + "]"; + String method = properties.getProperty(prefix + ".method"); + String path = properties.getProperty(prefix + ".path-pattern"); + if (method == null || path == null) { + continue; + } + HttpAuthProperties.HttpPublicRoute route = new HttpAuthProperties.HttpPublicRoute(); + route.setMethod(method); + route.setPathPattern(path); + routes.add(route); + } + auth.setPublicRoutes(routes); + HttpJwtAuthInterceptor interceptor = + new HttpJwtAuthInterceptor(Mockito.mock(JwtUtil.class), auth); + + assertThat( + interceptor.preHandle( + request("POST", "/auth/verify-email"), new MockHttpServletResponse(), null)) + .as(resource) + .isTrue(); + assertThat( + interceptor.preHandle( + request("POST", "/auth/complete-password-reset"), + new MockHttpServletResponse(), + null)) + .as(resource) + .isTrue(); + for (MockHttpServletRequest denied : + List.of( + request("GET", "/auth/verify-email"), + request("GET", "/auth/reset-password"), + request("POST", "/auth/verify-email/internal"))) { + MockHttpServletResponse response = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(denied, response, null)).as(resource).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + } + } + } + + private static MockHttpServletRequest request(String method, String path) { + return new MockHttpServletRequest(method, path); + } + + private static void assertProfile(String resource, String verificationUrl, String resetUrl) { + Properties properties = load(resource); + assertThat(properties.getProperty("firemud.mail.verification-url")).isEqualTo(verificationUrl); + assertThat(properties.getProperty("firemud.mail.reset-url")).isEqualTo(resetUrl); + + boolean publicVerificationPost = false; + boolean publicVerificationGet = false; + for (int index = 0; index < 32; index++) { + String prefix = "firemud.auth.http.public-routes[" + index + "]"; + if (!"/auth/verify-email".equals(properties.getProperty(prefix + ".path-pattern"))) { + continue; + } + publicVerificationPost |= "POST".equals(properties.getProperty(prefix + ".method")); + publicVerificationGet |= "GET".equals(properties.getProperty(prefix + ".method")); + } + assertThat(publicVerificationPost).isTrue(); + assertThat(publicVerificationGet).isFalse(); + } + + private static Properties load(String resource) { + YamlPropertiesFactoryBean loader = new YamlPropertiesFactoryBean(); + Path moduleLocal = Path.of("src", "main", "resources", resource); + Path repositoryLocal = + Path.of("services", "account-service", "src", "main", "resources", resource); + loader.setResources( + new FileSystemResource(Files.exists(moduleLocal) ? moduleLocal : repositoryLocal)); + Properties properties = loader.getObject(); + assertThat(properties).isNotNull(); + return properties; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index d5cd84e263..d7fd126f6a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -241,7 +241,8 @@ void connectTokenSetsCookieAndReturnsMetadataOnly() throws Exception { .andExpect(jsonPath("$.data.gameInstanceId").value(42)) .andExpect(jsonPath("$.data.realmSlug").value("production")) .andExpect(jsonPath("$.data.connectScopeId").value("scope-1")) - .andExpect(jsonPath("$.data.jti").value("jti-1")) + .andExpect(jsonPath("$.data.jti").doesNotHaveJsonPath()) + .andExpect(content().string(not(containsString("jti-1")))) .andExpect(jsonPath("$.data.requestId").value("req-7")) .andExpect(jsonPath("$.data.issuedAt").value("2026-03-30T00:00:00Z")) .andExpect(jsonPath("$.data.expiresAt").value("2026-03-30T00:00:30Z")) @@ -469,4 +470,13 @@ void verifyEmailReturnsSuccess() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } + + @Test + void emailedGetRequestsNeverConsumeTokens() throws Exception { + for (String path : + List.of("/auth/verify-email", "/auth/complete-password-reset", "/auth/reset-password")) { + mockMvc.perform(get(path).param("token", "tok")).andExpect(status().is4xxClientError()); + } + verifyNoInteractions(accountService); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java index 7bb283741a..6e399b9400 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java @@ -6,6 +6,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; @@ -100,4 +101,95 @@ void revokeRealmAccessRejectsMalformedAccountIdBeforeDispatch() throws Exception verifyNoInteractions(accountService); } + + @Test + void validPrivilegedGrantMutationsFailClosedBeforeDispatch() throws Exception { + for (String role : java.util.List.of("platformAdmin", "moderator")) { + String token = jwtTokenWithGlobalRole(role); + + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("AUTH_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("Lifecycle-qualified realm-grant mutations are unavailable")); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("AUTH_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("Lifecycle-qualified realm-grant mutations are unavailable")); + } + + verifyNoInteractions(accountService); + } + + @Test + void missingOrNonprivilegedAuthenticationStillDeniesGrantMutations() throws Exception { + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isUnauthorized()); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isUnauthorized()); + + String playerToken = jwtTokenWithGlobalRole("player"); + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + playerToken) + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isForbidden()); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + jwtTokenWithGlobalRole("player")) + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + + private String jwtTokenWithGlobalRole(String role) { + return jwtUtil.generateToken( + "f22f310d-5464-45f0-9dc4-c37353004403", + java.util.Map.of( + "accountId", + "f22f310d-5464-45f0-9dc4-c37353004403", + "globalRoles", + java.util.List.of(role))); + } + + private String validGrantRequestBody() throws Exception { + return objectMapper.writeValueAsString( + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "operator", "preview access", "request-1")); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBindingTest.java new file mode 100644 index 0000000000..7f88288355 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLeaveMembershipBindingTest.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountLeaveMembershipBindingTest { + @Test + void exactBindingIsStableAndEveryIdentityComponentChangesTheDigest() { + UUID account = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + var binding = new AccountLeaveMembershipBinding("request:é", account, tenant, "caller:绑定"); + assertThat( + new AccountLeaveMembershipBinding( + binding.requestId(), account, tenant, binding.callerBinding()) + .digest()) + .isEqualTo(binding.digest()); + assertThat( + new AccountLeaveMembershipBinding("different", account, tenant, binding.callerBinding()) + .digest()) + .isNotEqualTo(binding.digest()); + assertThat( + new AccountLeaveMembershipBinding( + binding.requestId(), UUID.randomUUID(), tenant, binding.callerBinding()) + .digest()) + .isNotEqualTo(binding.digest()); + assertThat( + new AccountLeaveMembershipBinding( + binding.requestId(), account, UUID.randomUUID(), binding.callerBinding()) + .digest()) + .isNotEqualTo(binding.digest()); + assertThat( + new AccountLeaveMembershipBinding(binding.requestId(), account, tenant, "different") + .digest()) + .isNotEqualTo(binding.digest()); + } + + @Test + void refusesAbsentOrMalformedCallerAndRequestIdentity() { + UUID account = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + for (String invalid : + new String[] { + "", " ", "x".repeat(257), String.valueOf((char) 0xD800), "a" + (char) 0 + "b" + }) { + assertThatThrownBy( + () -> new AccountLeaveMembershipBinding(invalid, account, tenant, "caller")) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> new AccountLeaveMembershipBinding("request", account, tenant, " ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountLeaveMembershipBinding("request", new UUID(0, 0), tenant, "caller")) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java new file mode 100644 index 0000000000..44f8772a00 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java @@ -0,0 +1,567 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +/** + * Unit proof uses explicit typed upstream authority fixtures, not caller-supplied authority DTOs. + */ +class AccountHostedTermsServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + + @Test + void affirmativeAcceptancePersistsExactShownCatalogAndReturnsOriginalReceipt() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(60)); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance expected = acceptance(action, party, terms); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.empty()); + when(fixture.repository.insertAcceptance( + any(UUID.class), any(), any(), any(), any(byte[].class))) + .thenReturn(expected); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(expected); + verify(fixture.repository) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void nonaffirmativeOrUnverifiedForeignPartyCannotWriteAcceptance() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction no = action(fixture, terms, false); + fixture.acceptanceAuthority(no); + assertThatThrownBy(() -> fixture.service.accept(no.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + + AccountHostedTermsService.AcceptanceAction foreign = action(fixture, terms, true); + fixture.acceptanceAuthority(foreign); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party(fixture.partyId, UUID.randomUUID())); + assertThatThrownBy(() -> fixture.service.accept(foreign.actionRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("own locally verified"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedShownDigestOperatorOrVersionIsDenied() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion stored = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + HostedTermsCatalogVersion other = terms(fixture.scopeId, null, 1, 1, "other-terms", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, stored, true); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, stored, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, stored.versionId())).thenReturn(other); + + assertThatThrownBy(() -> fixture.service.accept(action.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedOperatorIdentityOrVersionCannotBeAcceptedAsTheShownTerms() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction base = action(fixture, terms, true); + AccountHostedTermsService.AcceptanceAction changedName = + new AccountHostedTermsService.AcceptanceAction( + base.actionRequestId(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + "Different Operator", + base.shownOperatorIdentityVersion(), + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedName); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(base.actionRequestId())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> fixture.service.accept(base.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + AccountHostedTermsService.AcceptanceAction changedVersion = + new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + base.shownOperatorLegalIdentity(), + 2, + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedVersion); + when(fixture.repository.readAcceptanceByRequest(changedVersion.actionRequestId())) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> fixture.service.accept(changedVersion.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + } + + @Test + void exactRetryRecoversOriginalEvidenceWithoutRewritingOrReplacingIt() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance receipt = + acceptance(action, party(fixture.partyId, fixture.accountId), terms); + fixture.acceptanceAuthority(action); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.of(receipt)); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(receipt); + verify(fixture.parties, never()).readIndividualSource(any(), any()); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void materialityAdvancesOnlyItsIndependentGenerationAndNonmaterialityPreservesIt() { + Fixture material = new Fixture(); + HostedTermsCatalogVersion oldMaterial = + terms(material.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation materialOperation = + operation( + material.requestId, + material.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(material.repository.claimPublication(any(), any(), any())).thenReturn(materialOperation); + when(material.repository.lockScope(material.scopeId)) + .thenReturn(scope(material.scopeId, oldMaterial, NOW, null)); + when(material.fences.requestSourceChange(any())).thenReturn(true); + when(material.fences.sourceMutationPermitted(any())).thenReturn(true); + material.publicationAuthority( + publication( + material.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult materialResult = + material.service.publish(material.requestId); + assertThat(materialResult.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(materialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(materialResult.candidate().materialGeneration()).isEqualTo(2); + + Fixture nonmaterial = new Fixture(); + HostedTermsCatalogVersion oldNonmaterial = + terms(nonmaterial.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation nonmaterialOperation = + operation( + nonmaterial.requestId, + nonmaterial.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(nonmaterial.repository.claimPublication(any(), any(), any())) + .thenReturn(nonmaterialOperation); + when(nonmaterial.repository.lockScope(nonmaterial.scopeId)) + .thenReturn(scope(nonmaterial.scopeId, oldNonmaterial, NOW, null)); + when(nonmaterial.fences.requestSourceChange(any())).thenReturn(true); + when(nonmaterial.fences.sourceMutationPermitted(any())).thenReturn(true); + nonmaterial.publicationAuthority( + publication( + nonmaterial.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult nonmaterialResult = + nonmaterial.service.publish(nonmaterial.requestId); + assertThat(nonmaterialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(nonmaterialResult.candidate().materialGeneration()).isEqualTo(1); + } + + @Test + void unresolvedOwnerSettlementKeepsPublicationPendingWithoutAdvancingCatalogHead() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + when(fixture.repository.claimPublication(any(), any(), any())) + .thenReturn( + operation( + fixture.requestId, + fixture.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED)); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.fences.requestSourceChange(any())).thenReturn(false); + fixture.publicationAuthority( + publication( + fixture.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + + AccountHostedTermsService.PublicationResult result = fixture.service.publish(fixture.requestId); + assertThat(result.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + verify(fixture.repository).markOwnerSettlementPending(any(), any(), any(byte[].class)); + verify(fixture.repository, never()).completePublication(any(), any(), any(), any()); + } + + @Test + void dueDisclosedDeadlineDeniesOldCurrentnessWhileSourceSettlementIsPending() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(10)); + HostedTermsCatalogVersion next = + terms(fixture.scopeId, current.versionId(), 2, 2, "terms-v2", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation pending = + new HostedTermsRepository.PublicationOperation( + fixture.requestId, + fixture.scopeId, + new byte[] {1}, + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, + next.versionId(), + new byte[] {2}, + null, + null, + null); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, pending)); + when(fixture.repository.readCandidate(pending)).thenReturn(next); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + + @Test + void staleGenerationAndChangedOrUnavailableIdentityNeverReturnCurrentness() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource acceptedParty = party(fixture.partyId, fixture.accountId); + IndividualCreatorPartySource changedParty = + new IndividualCreatorPartySource( + fixture.partyId, + fixture.accountId, + VerificationStatus.VERIFIED, + 2, + "test-policy-v2", + 2L, + "test-verification-v2", + 2L, + 1); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, UUID.randomUUID(), 2, 2, "terms-v2", NOW); + IndividualHostedTermsAcceptance stale = + acceptance( + action(fixture, terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW), true), + acceptedParty, + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW)); + IndividualHostedTermsAcceptance currentAcceptance = + acceptance(action(fixture, current, true), acceptedParty, current); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(acceptedParty, acceptedParty, changedParty) + .thenThrow(new IllegalStateException("source unavailable")); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.repository.readCurrentAcceptance(fixture.partyId, fixture.scopeId, current)) + .thenReturn(Optional.empty(), Optional.of(stale), Optional.of(currentAcceptance)); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No current affirmative"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source unavailable"); + } + + @Test + void catalogAndAcceptanceEncodingsBindExactBytesWithoutCallerTimeAuthority() { + Fixture fixture = new Fixture(); + byte[] document = new byte[] {0, 1, (byte) 0xff, 13, 10}; + HostedTermsCatalogVersion version = terms(fixture.scopeId, null, 1, 1, document, NOW); + byte[] original = version.documentBytes(); + original[0] = 9; + assertThat(version.documentBytes()).containsExactly(document); + assertThat(version.documentDigest()).isEqualTo(HostedTermsEncoding.digest(document)); + assertThat(HostedTermsEncoding.catalog(version)) + .isEqualTo(HostedTermsEncoding.catalog(version)); + assertThatThrownBy( + () -> + new HostedTermsCatalogVersion( + UUID.randomUUID(), + fixture.scopeId, + null, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest("different".getBytes()), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-publication", + 1, + "test-notice", + 1, + NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Document digest"); + } + + private static HostedTermsRepository.ScopeSnapshot scope( + UUID id, + HostedTermsCatalogVersion current, + Instant now, + HostedTermsRepository.PublicationOperation pending) { + return new HostedTermsRepository.ScopeSnapshot( + id, current, OffsetDateTime.ofInstant(now, ZoneOffset.UTC), pending); + } + + private static HostedTermsRepository.PublicationOperation operation( + UUID requestId, + UUID scopeId, + String request, + HostedTermsRepository.PublicationStatus status) { + byte[] payload = request.getBytes(); + return new HostedTermsRepository.PublicationOperation( + requestId, + scopeId, + payload, + HostedTermsEncoding.digest(payload), + status, + null, + null, + null, + null, + null); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + String document, + Instant effectiveAt) { + return terms(scope, predecessor, source, generation, document.getBytes(), effectiveAt); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + byte[] document, + Instant effectiveAt) { + return new HostedTermsCatalogVersion( + UUID.randomUUID(), + scope, + predecessor, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest(document), + source, + generation, + predecessor == null + ? HostedTermsCatalogVersion.Materiality.INITIAL + : generation == 2 + ? HostedTermsCatalogVersion.Materiality.MATERIAL + : HostedTermsCatalogVersion.Materiality.NONMATERIAL, + predecessor == null ? null : "test-materiality", + predecessor == null ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-policy", + 1L, + "test-verification", + 1L, + 1); + } + + private static AccountHostedTermsService.AcceptanceAction action( + Fixture fixture, HostedTermsCatalogVersion terms, boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + affirmative, + fixture.accountId, + fixture.partyId, + fixture.scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-authenticated-action", + 1, + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + String document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator", + 1, + document.getBytes(), + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualHostedTermsAcceptance acceptance( + AccountHostedTermsService.AcceptanceAction action, + IndividualCreatorPartySource party, + HostedTermsCatalogVersion terms) { + byte[] source = HostedTermsEncoding.individualParty(party); + byte[] actionBytes = HostedTermsEncoding.affirmativeAction(action); + return new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + action.actionRequestId(), + party.creatorPartyId(), + party.accountId(), + terms.hostedScopeId(), + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + terms.sourceVersion(), + terms.materialGeneration(), + source, + HostedTermsEncoding.digest(source), + actionBytes, + HostedTermsEncoding.digest(actionBytes), + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static final class Fixture { + private final UUID requestId = UUID.randomUUID(); + private final UUID scopeId = UUID.randomUUID(); + private final UUID accountId = UUID.randomUUID(); + private final UUID partyId = UUID.randomUUID(); + private final HostedTermsRepository repository = mock(HostedTermsRepository.class); + private final IndividualCreatorPartyRepository parties = + mock(IndividualCreatorPartyRepository.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountHostedTermsService.OperatorPublicationAuthority publicationAuthority = + mock(AccountHostedTermsService.OperatorPublicationAuthority.class); + private final AccountHostedTermsService.IndividualAcceptanceAuthority acceptanceAuthority = + mock(AccountHostedTermsService.IndividualAcceptanceAuthority.class); + private final AccountHostedTermsService service = + new AccountHostedTermsService( + new NoopTransactionManager(), + repository, + parties, + fences, + publicationAuthority, + acceptanceAuthority); + + private void acceptanceAuthority(AccountHostedTermsService.AcceptanceAction action) { + when(acceptanceAuthority.resolve(action.actionRequestId())).thenReturn(action); + } + + private void publicationAuthority(AccountHostedTermsService.PublicationEvidence evidence) { + when(publicationAuthority.resolve(requestId)).thenReturn(evidence); + } + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java new file mode 100644 index 0000000000..4080386540 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java @@ -0,0 +1,307 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.junit.jupiter.api.Test; + +class HostedTermsEnvironmentBindingTest { + @Test + void canonicalPublicationBindsBoundaryScopeOperatorCatalogPublisherEventAndPredecessor() { + UUID requestId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogVersionId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "official/production-cluster-a", + scopeId, + "Test Operator Legal Name", + 4, + catalogVersionId, + 9, + "environment-secrets-owner@production", + "deployment-ref:event-37:traffic-open-12", + priorBinding, + 2L); + + byte[] original = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence)) + .containsExactly(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publicationDigest(requestId, evidence)) + .isEqualTo(HostedTermsEncoding.digest(original)); + + PublicationEvidence changed = + new PublicationEvidence( + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + UUID.randomUUID(), + evidence.predecessorSourceVersion()); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, changed)) + .isNotEqualTo(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(UUID.randomUUID(), evidence)) + .isNotEqualTo(original); + } + + @Test + void independentBindingCounterAndExactReceiptUseNamespacedHostedTermsSourceKey() { + UUID requestId = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "production", + UUID.randomUUID(), + "Test Operator", + 1, + UUID.randomUUID(), + 7, + "test-only-environment-owner", + "test-only-publication-event-17", + UUID.randomUUID(), + 8L); + byte[] publication = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + HostedTermsEncoding.digest(publication), + evidence.predecessorBindingId(), + evidence.predecessorSourceVersion(), + 9); + + var source = binding.sourceEvidence(); + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.key()).isEqualTo("HOSTED_TERMS:environment-boundary/production"); + assertThat(source.scopeId()).isNotEqualTo(binding.hostedScopeId().toString()); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("9"); + assertThat(source.evidence()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(binding)); + assertThat(HostedTermsEnvironmentBindingEncoding.receiptDigest(binding)) + .isEqualTo(HostedTermsEncoding.digest(source.evidence())); + assertThat(binding.catalogSourceVersion()).isEqualTo(7); + assertThat(binding.sourceVersion()).isEqualTo(9); + } + + @Test + void initialBindingCannotInventPredecessorAndUpdatesAdvanceExactlyOnce() { + UUID requestId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new PublicationEvidence( + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-1", + null, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("present together"); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-2", + HostedTermsEncoding.digest(new byte[] {1}), + priorBinding, + 4L, + 7)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact predecessor"); + } + + @Test + void currentEnvironmentEvidenceRequiresExactOwnerDigest() { + byte[] evidence = new byte[] {1, 2, 3}; + var current = + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-1", + evidence, + HostedTermsEncoding.digest(evidence)); + byte[] returned = current.exactOwnerEvidence(); + returned[0] = 9; + assertThat(current.exactOwnerEvidence()).containsExactly(evidence); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-2", + evidence, + HostedTermsEncoding.digest(new byte[] {8}))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest conflicts"); + } + + @Test + void currentnessSourceRetainsExactScheduledCatalogAndDisclosedDeadline() { + Instant currentAt = Instant.parse("2026-10-08T00:00:00Z"); + byte[] currentDocument = "current terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion current = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + UUID.randomUUID(), + null, + "Test Operator", + 1, + currentDocument, + HostedTermsEncoding.digest(currentDocument), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "current-publication", + 1, + "current-notice", + 1, + currentAt); + byte[] partySource = new byte[] {11, 12}; + byte[] affirmativeAction = new byte[] {21, 22}; + IndividualHostedTermsAcceptance acceptance = + new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.documentDigest(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + current.sourceVersion(), + current.materialGeneration(), + partySource, + HostedTermsEncoding.digest(partySource), + affirmativeAction, + HostedTermsEncoding.digest(affirmativeAction), + OffsetDateTime.ofInstant(currentAt, ZoneOffset.UTC)); + + Instant disclosedAt = Instant.parse("2026-10-09T00:00:00Z"); + byte[] nextDocument = "scheduled terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion deadline = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + nextDocument, + HostedTermsEncoding.digest(nextDocument), + 2, + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + "audited-nonmaterial-classification", + 1L, + "scheduled-publication", + 2, + "scheduled-notice", + 2, + disclosedAt); + + byte[] exactDeadline = HostedTermsEncoding.catalog(deadline); + byte[] source = HostedTermsEncoding.currentnessSource(current, acceptance, deadline); + String sourceJson = new String(source, StandardCharsets.UTF_8); + assertThat(sourceJson).contains("account-hosted-terms-currentness-source/v2"); + assertThat(sourceJson) + .contains(Base64.getEncoder().encodeToString(exactDeadline)) + .contains(HostedTermsEncoding.digest(exactDeadline)); + assertThat( + new String( + HostedTermsEncoding.currentnessSource(current, acceptance), StandardCharsets.UTF_8)) + .contains("\"disclosedDeadlineCatalog\":null") + .contains("\"disclosedDeadlineCatalogDigest\":null"); + + HostedTermsCatalogVersion changedDeadline = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + deadline.operatorLegalIdentity(), + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + disclosedAt.plusSeconds(1)); + assertThat(HostedTermsEncoding.currentnessSource(current, acceptance, changedDeadline)) + .isNotEqualTo(source); + + HostedTermsCatalogVersion changedOperator = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + "Different Operator", + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + deadline.effectiveAt()); + assertThatThrownBy( + () -> HostedTermsEncoding.currentnessSource(current, acceptance, changedOperator)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact immutable next catalog"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepositoryTest.java new file mode 100644 index 0000000000..0d2d17086d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceObservationRepositoryTest.java @@ -0,0 +1,207 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountControlUiCurrentSourceObservationRepositoryTest { + private static final UUID ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private final DSLContext dsl = mock(DSLContext.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountControlUiCurrentSourceObservationRepository observer = + new AccountControlUiCurrentSourceObservationRepository(dsl, accounts, sources); + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentAndReadOnlyOwnerTransactionsDenyBeforeJdbcOrOwnerLookup() { + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl, accounts, sources); + } + + @ParameterizedTest + @ValueSource(strings = {"autocommit", "readOnly", "isolation"}) + void invalidJdbcContextDeniesBeforeAnyOwnerLookup(String condition) throws Exception { + var connection = writableConnection(); + when(connection.getAutoCommit()).thenReturn(condition.equals("autocommit")); + when(connection.isReadOnly()).thenReturn(condition.equals("readOnly")); + when(connection.getTransactionIsolation()) + .thenReturn( + condition.equals("isolation") + ? Connection.TRANSACTION_REPEATABLE_READ + : Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(accounts, sources); + } + + @Test + void absentExistingAccountNeverEnrollsOrReadsUpstream() throws Exception { + writableConnection(); + when(accounts.findByAccountUuidForUpdate(ID)).thenReturn(Optional.empty()); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + verify(accounts).findByAccountUuidForUpdate(ID); + verifyNoMoreInteractions(accounts); + verifyNoInteractions(sources); + } + + @ParameterizedTest + @ValueSource(strings = {"identity", "numericProvenance", "lifecycle"}) + void mismatchedAccountProvenanceDeniesBeforeSourceRead(String condition) throws Exception { + writableConnection(); + Account account = account(); + if (condition.equals("identity")) account.setAccountUuid(UUID.randomUUID()); + if (condition.equals("numericProvenance")) account.setAccountUuidSourceNumericId(43L); + if (condition.equals("lifecycle")) + account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + when(accounts.findByAccountUuidForUpdate(ID)).thenReturn(Optional.of(account)); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(sources); + } + + @Test + void exactExistingCorrelatedSourcesReturnOnlyInformationalObservation() throws Exception { + writableConnection(); + var snapshot = correlatedSources(); + var roles = roles(); + when(dsl.fetchOne(anyString(), eq(ID))).thenReturn(roles); + var observation = observer.observeExisting(ID); + assertThat(observation.accountId()).isEqualTo(ID); + assertThat(observation.sources()).isSameAs(snapshot); + assertThat(observation.globalRoleSourceVersion()).isEqualTo(3L); + assertThat(observation.toString()).contains("non-authorizing"); + verify(accounts).findByAccountUuidForUpdate(ID); + verify(sources).readCurrentIssuerAccountSources(ISSUER, ID); + verifyNoMoreInteractions(accounts, sources); + } + + @Test + void mismatchedSourceNumericIdentityDeniesBeforeRoleRead() throws Exception { + writableConnection(); + var snapshot = correlatedSources(); + when(snapshot.account().accountSourceNumericId()).thenReturn(43L); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + verify(dsl).connection(any(ConnectionRunnable.class)); + verifyNoMoreInteractions(dsl); + } + + @ParameterizedTest + @ValueSource(strings = {"identity", "numericProvenance", "provenance", "roles", "version"}) + void contradictoryRoleOwnerCannotBecomeObservation(String condition) throws Exception { + writableConnection(); + correlatedSources(); + var roleRow = roles(); + if (condition.equals("identity")) + when(roleRow.get("account_uuid", UUID.class)).thenReturn(UUID.randomUUID()); + if (condition.equals("numericProvenance")) + when(roleRow.get("account_uuid_source_numeric_id", Long.class)).thenReturn(43L); + if (condition.equals("provenance")) + when(roleRow.get("account_uuid_provenance", String.class)).thenReturn("OTHER"); + if (condition.equals("roles")) + when(roleRow.get("global_roles", String[].class)).thenReturn(new String[] {"ADMIN"}); + if (condition.equals("version")) + when(roleRow.get("global_role_source_version", Long.class)).thenReturn(0L); + when(dsl.fetchOne(anyString(), eq(ID))).thenReturn(roleRow); + assertThatThrownBy(() -> observer.observeExisting(ID)) + .isInstanceOf(IllegalStateException.class); + } + + private Connection writableConnection() throws Exception { + TransactionSynchronizationManager.setActualTransactionActive(true); + Connection connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + return connection; + } + + private static Account account() { + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(ID); + account.setAccountUuidSourceNumericId(42L); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setLifecycleState(AccountLifecycleState.ACTIVE); + return account; + } + + private IssuerAccountSourceSnapshot correlatedSources() { + when(accounts.findByAccountUuidForUpdate(ID)).thenReturn(Optional.of(account())); + var snapshot = mock(IssuerAccountSourceSnapshot.class); + var issuer = mock(CurrentSourceEvidence.class); + var source = mock(CurrentSourceEvidence.class); + var fence = new IssuanceFence(ID, 1L, 1L); + when(snapshot.issuer()).thenReturn(issuer); + when(issuer.scope()).thenReturn(AuthorityScope.issuer(ISSUER)); + when(snapshot.account()).thenReturn(source); + when(source.scope()).thenReturn(AuthorityScope.account(ID)); + when(source.accountSourceNumericId()).thenReturn(42L); + when(source.accountUuidProvenance()).thenReturn("ACCOUNT_REPOSITORY_INSERT"); + when(source.issuanceFence()).thenReturn(fence); + when(snapshot.issuanceFence()).thenReturn(fence); + when(snapshot.canonicalIssuerProjection()).thenReturn(mock(IssuerGenerationProjection.class)); + when(snapshot.canonicalAccountProjection()).thenReturn(mock(AccountGenerationProjection.class)); + when(sources.readCurrentIssuerAccountSources(ISSUER, ID)).thenReturn(snapshot); + return snapshot; + } + + private static Record roles() { + var roles = mock(Record.class); + when(roles.get("account_uuid", UUID.class)).thenReturn(ID); + when(roles.get("account_uuid_source_numeric_id", Long.class)).thenReturn(42L); + when(roles.get("account_uuid_provenance", String.class)) + .thenReturn("ACCOUNT_REPOSITORY_INSERT"); + when(roles.get("global_roles", String[].class)).thenReturn(new String[0]); + when(roles.get("global_role_source_version", Long.class)).thenReturn(3L); + return roles; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java index 8f97cbddc3..a1e408d47a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -257,6 +258,45 @@ void unsupportedDurabilityAtCommitDenies(String fault) throws Exception { } } + @ParameterizedTest + @ValueSource(strings = {"decision", "carrier", "digest"}) + void changedFinalReadbackCannotReachPhysicalCommitOrMintAcknowledgement(String fault) + throws Exception { + var fixture = new Fixture(); + var changed = mock(AccountGameplayAdmissionLeaseEvidence.class); + when(changed.canonicalJson()) + .thenReturn(fault.equals("carrier") ? "changed-carrier" : "synthetic-unit-carrier"); + when(changed.sha256()).thenReturn(fault.equals("digest") ? "b".repeat(64) : "a".repeat(64)); + try (var repositories = + mockConstruction( + AccountGameplayAdmissionLeaseRepository.class, + (repository, context) -> { + when(repository.readExact(fixture.evidence)) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + fixture.evidence, State.PENDING, null, null))); + when(repository.recordCommitted(fixture.evidence, fixture.decision)) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + changed, + State.COMMITTED, + fault.equals("decision") ? UUID.randomUUID() : fixture.decision, + null)); + })) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + try (var verificationResult = + verify(fixture.clockStatement, never()).executeQuery(anyString())) { + // Mockito verification does not execute a query and returns no ResultSet. + assertThat(verificationResult).isNull(); + } + assertThat(repositories.constructed()).hasSize(1); + } + } + @Test void finalizationStampMustBelongToActualOriginalTransaction() throws Exception { var fixture = new Fixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java new file mode 100644 index 0000000000..1349aed2dd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java @@ -0,0 +1,429 @@ +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.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerEventReadback; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerSourceSnapshotReadOwnerTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + private final AccountAuthoritySourceEvidenceRepository sourceRepository = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountIssuerSourceSnapshotReadOwner owner = + new AccountIssuerSourceSnapshotReadOwner(sourceRepository, transactionManager, NAMESPACE); + + @BeforeEach + void installTransactionManagerBehavior() { + when(transactionManager.getTransaction(any())) + .thenAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + return transactionStatus; + }); + doAnswer( + invocation -> { + clearTransactionMarkers(); + return null; + }) + .when(transactionManager) + .commit(transactionStatus); + doAnswer( + invocation -> { + clearTransactionMarkers(); + return null; + }) + .when(transactionManager) + .rollback(transactionStatus); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void missingWrongAndCrossNamespacePeersAreRejectedBeforeRequestParsingOrStorage() { + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.read(null)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus(Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(null))); + } + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void authenticatedPlayerContextIsRejectedEvenWithAnExactWorkloadPeer() { + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), java.util.Map.of()); + try { + assertStatus(Status.Code.PERMISSION_DENIED, () -> peer().call(() -> owner.read(null))); + verifyNoInteractions(sourceRepository, transactionManager); + } finally { + SessionContext.clear(); + } + } + + @Test + void rejectsAmbientTransactionSynchronizationAndReadOnlyContextBeforeStorage() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + clearTransactionMarkers(); + + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + TransactionSynchronizationManager.clearSynchronization(); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void readsZeroAndAdvancedOwnerSnapshotsAndRejectsChangedExpectedSource() throws Exception { + UUID operation = UUID.randomUUID(); + UUID freshOperation = UUID.randomUUID(); + var zero = sourceSnapshot(1, Optional.empty(), Optional.empty()); + var advanced = sourceSnapshot(2, Optional.of(issuerEvent()), Optional.of(issuerEvent())); + var eventDrift = + sourceSnapshot( + 2, + Optional.of(issuerEvent("different-historical-event-18")), + Optional.of(issuerEvent("different-historical-event-18"))); + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenReturn(zero, zero, advanced, advanced, advanced, eventDrift); + + var captured = peer().call(() -> owner.read(request(operation))); + assertThat(captured.evidence().issuerAuthGeneration()).isEqualTo("1"); + assertThat(captured.evidence().sourceVersion()).isEqualTo("1"); + assertThat(captured.evidence().lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(captured.evidence().sourceEvent()).isEmpty(); + + var exactRetry = + peer().call(() -> owner.read(request(operation, Optional.of(captured.evidence())))); + assertThat(exactRetry.evidence()).isEqualTo(captured.evidence()); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(operation, Optional.of(captured.evidence()))))); + + var newCapture = peer().call(() -> owner.read(request(freshOperation))); + assertThat(newCapture.evidence().issuerAuthGeneration()).isEqualTo("2"); + assertThat(newCapture.evidence().sourceVersion()).isEqualTo("2"); + assertThat(newCapture.evidence().lastCommittedOutboxSequence()).isEqualTo("1"); + assertThat(newCapture.evidence().reconciliationOperationId()).isEqualTo(freshOperation); + var retained = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify( + newCapture.evidence().sourceEvent().orElseThrow()); + assertThat(retained.eventId()).isEqualTo("historical-issuer-event-17"); + assertThat(retained.requestId()).isEqualTo("historical-issuer-event-17"); + assertThat(retained.eventId()).isNotEqualTo(freshOperation.toString()); + + var exactAdvancedRetry = + peer().call(() -> owner.read(request(freshOperation, Optional.of(newCapture.evidence())))); + assertThat(exactAdvancedRetry.evidence()).isEqualTo(newCapture.evidence()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call( + () -> owner.read(request(freshOperation, Optional.of(newCapture.evidence()))))); + + ArgumentCaptor definitions = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager, times(6)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.isReadOnly()).isFalse(); + }); + verify(transactionManager, times(4)).commit(transactionStatus); + verify(transactionManager, times(2)).rollback(transactionStatus); + } + + @Test + void malformedUnknownUnsupportedAndMismatchedExpectedRequestsFailBeforeSql() { + UUID operation = UUID.randomUUID(); + var valid = request(operation); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var wrongNamespace = valid.toBuilder().setTargetNamespace("other").build(); + var unsupportedIssuer = valid.toBuilder().setIssuerId("other-issuer").build(); + var wrongExpected = + valid.toBuilder() + .setExpectedSource( + AccountIssuerSourceSnapshotGrpcCodec.toWire( + AccountIssuerSourceSnapshotEvidenceForTest.zero(UUID.randomUUID()))) + .build(); + + for (ReadCurrentIssuerAuthoritySourceRequest request : + List.of(unknown, wrongNamespace, unsupportedIssuer, wrongExpected)) { + assertThatThrownBy(() -> peer().call(() -> owner.read(request))) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void sourceOutageMapsUnavailableAndContradictoryRetainedEventMapsFailedPrecondition() { + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenThrow(new DataAccessException("database offline")); + assertStatus( + Status.Code.UNAVAILABLE, () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + + var corrupt = sourceSnapshot(2, Optional.of(issuerEvent()), Optional.of(issuerEvent())); + var source = corrupt.source(); + Event validEvent = corrupt.latestEvent().orElseThrow(); + Event malformedEvent = + new Event( + validEvent.outboxStreamKey(), + validEvent.requestId(), + validEvent.outboxSequence(), + validEvent.eventId(), + validEvent.eventDigest(), + "not-json".getBytes(StandardCharsets.UTF_8)); + var badHistory = + new AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + source, Optional.of(malformedEvent)); + doReturn(badHistory).when(sourceRepository).readCurrentCanonicalIssuerSource(ISSUER); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + } + + @Test + void missingCanonicalIssuerDeniesWithoutCreatingOrReadingAnotherScope() { + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenThrow( + new AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + verify(sourceRepository).readCurrentCanonicalIssuerSource(ISSUER); + verify(sourceRepository, never()).initializeIssuerIfAbsent(any()); + } + + @Test + void readsSelectedHistoryAndCurrentSourceTogetherInTheOwnedTransaction() throws Exception { + var selected = issuerEvent(); + var latest = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "next-event", "next-event", STREAM, "2", ISSUER, "3", "3", "SIGNER_COMPROMISE")); + var current = sourceSnapshot(3, Optional.of(latest), Optional.of(latest)); + when(sourceRepository.readExactCanonicalIssuerEvent( + ISSUER, 1L, selected.eventId(), selected.eventDigest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return new CanonicalIssuerEventReadback(current, selected); + }); + UUID operation = UUID.randomUUID(); + var result = peer().call(() -> owner.readExactEvent(exactRequest(operation))); + assertThat(result.authenticatedCallerWorkload()).isEqualTo(CALLER); + var snapshot = result.readback().currentSnapshot(); + assertThat(snapshot.reconciliationOperationId()).isEqualTo(operation); + assertThat(snapshot.lastCommittedOutboxSequence()).isEqualTo("2"); + assertThat(snapshot.sourceEvent()).contains(latest.canonicalJson()); + assertThat(result.readback().selectedEvent()).isEqualTo(selected); + verify(sourceRepository, never()).readCurrentCanonicalIssuerSource(any()); + verify(transactionManager).commit(transactionStatus); + } + + @Test + void exactHistoryAuthenticatesAndValidatesSelectorBeforeOpeningStorage() { + var request = exactRequest(UUID.randomUUID()); + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.readExactEvent(null)); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + peer("spiffe://firemud/ns/other/sa/game-session-service") + .call(() -> owner.readExactEvent(request))); + var malformed = request.toBuilder().setOutboxSequence("01").build(); + assertThatThrownBy(() -> peer().call(() -> owner.readExactEvent(malformed))) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.readExactEvent(request))); + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void missingExactHistoryAndStorageFailureReturnNoReadback() { + var selected = issuerEvent(); + var request = exactRequest(UUID.randomUUID()); + when(sourceRepository.readExactCanonicalIssuerEvent( + ISSUER, 1L, selected.eventId(), selected.eventDigest())) + .thenThrow( + new AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException(), + new DataAccessException("database offline")); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.readExactEvent(request))); + assertStatus(Status.Code.UNAVAILABLE, () -> peer().call(() -> owner.readExactEvent(request))); + verify(transactionManager, times(2)).rollback(transactionStatus); + } + + private static ReadExactIssuerAuthorityEventRequest exactRequest(UUID operation) { + var selected = issuerEvent(); + var scope = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, Optional.empty()); + var request = + new AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest( + scope, 1L, selected.eventId(), selected.eventDigest()); + return AccountIssuerSourceSnapshotGrpcCodec.toExactEventRequest(request, NAMESPACE, CALLER); + } + + private static AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot + sourceSnapshot( + long generation, + Optional event, + Optional eventForOutbox) { + long sequence = generation - 1L; + Optional eventId = event.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventId); + Optional digest = + event.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventDigest); + var checkpoint = + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + STREAM, sequence, eventId, digest); + var current = + new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + generation, + generation, + null, + checkpoint, + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 9L, + null); + Optional latest = + eventForOutbox.map( + sourceEvent -> + new Event( + STREAM, + sourceEvent.requestId(), + sequence, + sourceEvent.eventId(), + sourceEvent.eventDigest(), + sourceEvent.canonicalJsonUtf8())); + return new AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + current, latest); + } + + private static AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent() { + return issuerEvent("historical-issuer-event-17"); + } + + private static AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent(String eventId) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, eventId, STREAM, "1", ISSUER, "2", "2", "SIGNER_COMPROMISE")); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request(UUID operation) { + return request(operation, Optional.empty()); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, Optional expected) { + var typed = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + return AccountIssuerSourceSnapshotGrpcCodec.toRequest(typed, NAMESPACE, CALLER); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context peer() { + return peer(CALLER); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static void clearTransactionMarkers() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + } + + /** Builds a fully typed initial source for request-shape tests without asserting authority. */ + private static final class AccountIssuerSourceSnapshotEvidenceForTest { + private static AccountIssuerSourceSnapshotEvidence zero(UUID operation) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, "1", "1", STREAM, "0", Optional.empty()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java new file mode 100644 index 0000000000..38bb559393 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java @@ -0,0 +1,48 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateOperationRepositoryTest { + @Test + void storageDeniesOutsideWritableOwnerTransactionBeforeDataAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountSecurityStateOperationRepository(dsl); + assertThatThrownBy(() -> repository.findByRequestId(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + verifyNoInteractions(dsl); + assertThat( + repository + .getClass() + .isAnnotationPresent(org.springframework.stereotype.Repository.class)) + .isTrue(); + assertThat( + repository.getClass().isAnnotationPresent(org.springframework.stereotype.Service.class)) + .isFalse(); + } + + @Test + void detectorExactlyCoversIndependentCredentialFreeChangedFamilies() { + var before = new AccountState(false, List.of("PASSWORD"), List.of(), "ACTIVE"); + var after = + new AccountState( + true, List.of("EMAIL_OTP", "PASSWORD"), List.of("support"), "SECURITY_LOCKED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, after)) + .containsExactly( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED", + "LOGIN_AUTH_MODES_CHANGED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, before)).isEmpty(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/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/repository/ConnectTokenRequestFingerprintTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ConnectTokenRequestFingerprintTest.java new file mode 100644 index 0000000000..9494c516e3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ConnectTokenRequestFingerprintTest.java @@ -0,0 +1,85 @@ +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.util.UUID; +import net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint; +import org.junit.jupiter.api.Test; + +class ConnectTokenRequestFingerprintTest { + private static final UUID ACCOUNT = UUID.fromString("7c9b1c20-e15c-4809-b6fb-d2ecc253460b"); + private static final UUID TENANT = UUID.fromString("e16c4af2-c203-4f1a-a0a8-ab1163234e46"); + + @Test + void fixedVersionedCanonicalVector() { + var lookup = ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", "request"); + assertThat(lookup.requestDigest()) + .isEqualTo("sha256:3cff276388fd178b00aa6b01788178709c1f8d20320e865aad418b15da577123"); + assertThat(lookup.digestVersion()).isEqualTo(1); + assertThat(lookup.accountId()).isEqualTo(ACCOUNT); + assertThat(lookup.tenantId()).isEqualTo(TENANT); + assertThat(lookup.connectScopeId()).isEqualTo("scope"); + assertThat(lookup.requestId()).isEqualTo("request"); + } + + @Test + void exactInputsDoNotNormalizeOrCollideAcrossFields() { + var base = ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", "request"); + assertThat( + ConnectTokenRequestFingerprint.lookup(TENANT, TENANT, "scope", "request") + .requestDigest()) + .isNotEqualTo(base.requestDigest()); + assertThat( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, ACCOUNT, "scope", "request") + .requestDigest()) + .isNotEqualTo(base.requestDigest()); + assertThat( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "Scope", "request") + .requestDigest()) + .isNotEqualTo(base.requestDigest()); + assertThat( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", " request ") + .requestDigest()) + .isNotEqualTo(base.requestDigest()); + assertThat(ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "ab", "c").requestDigest()) + .isNotEqualTo( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "a", "bc").requestDigest()); + assertThat( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", "\u00e9") + .requestDigest()) + .isNotEqualTo( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", "e\u0301") + .requestDigest()); + assertThat( + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", "a=\\\"\n") + .requestDigest()) + .startsWith("sha256:"); + } + + @Test + void rejectsInvalidIdentityAndMalformedOrOversizeUtf8() { + assertThatThrownBy( + () -> ConnectTokenRequestFingerprint.lookup(null, TENANT, "scope", "request")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ConnectTokenRequestFingerprint.lookup(ACCOUNT, new UUID(0, 0), "scope", "request")) + .isInstanceOf(IllegalArgumentException.class); + for (String invalid : + new String[] {"", " ", "a\0b", "\uD800", "x".repeat(129), "\u00e9".repeat(65)}) { + assertThatThrownBy( + () -> ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "scope", invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + ConnectTokenRequestFingerprint.lookup(ACCOUNT, TENANT, "x".repeat(2049), "request")) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + ConnectTokenRequestFingerprint.lookup( + ACCOUNT, TENANT, "x".repeat(2048), "\u00e9".repeat(64)) + .requestDigest()) + .startsWith("sha256:"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityHistoricalReceiptReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityHistoricalReceiptReadbackTest.java new file mode 100644 index 0000000000..2ff1341581 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityHistoricalReceiptReadbackTest.java @@ -0,0 +1,388 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class AccountAuthorityHistoricalReceiptReadbackTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + + @Test + void retainedPasswordResetUsesImmutableReceiptWithoutMakingItsVerifierCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event retained = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "a".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(retained, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "c".repeat(64)))); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + AccountAuthorityGenerationRepository.ScopeState current = accountState(3L, 3L, 8L, 7L); + + readback.requireRetainedEvent(account, retained, current); + + verify(resets).findByRequestId(receipt.requestId()); + verifyNoInteractions(logouts); + } + + @Test + void latestPasswordResetStillRequiresItsRecordedVerifierToBeCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event latest = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "b".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(latest, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, latest.eventId(), latest.eventDigest()))); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(latest)); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account, accountState(2L, 2L, 7L, 6L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the current password verifier"); + } + + @Test + void retainedLogoutAllEventRequiresItsExactImmutableReceipt() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event retained = + logoutAllEvent( + ACCOUNT_UUID, UUID.fromString("a980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L); + LogoutAllReceipt receipt = logoutReceipt(retained, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "d".repeat(64)))); + when(logouts.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + readback.requireRetainedEvent(account(), retained, accountState(3L, 3L, 8L, 7L)); + + verify(logouts).findByRequestId(receipt.requestId()); + verifyNoInteractions(resets); + } + + @Test + void retainedReadRejectsChangedEventBytesAndMissingReceipts() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event valid = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "e".repeat(64)); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "f".repeat(64)))); + byte[] changedPayload = valid.payload(); + changedPayload[changedPayload.length - 2] ^= 1; + Event changedBytes = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + valid.eventDigest(), + changedPayload); + + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedBytes, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event is invalid"); + + Event changedDigest = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + "sha256:" + "0".repeat(64), + valid.payload()); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedDigest, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + Event unsupportedSchema = + new Event( + valid.outboxStreamKey(), + "unsupported-request", + 1L, + "unsupported-event", + "sha256:" + "1".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), unsupportedSchema, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("schema is missing"); + + Event wrongAccount = + passwordResetEvent( + UUID.fromString("d980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L, "f".repeat(64)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), wrongAccount, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + PasswordResetReceipt receipt = passwordResetReceipt(valid, 7L, 6L); + PasswordResetReceipt mismatchedReceipt = + new PasswordResetReceipt( + receipt.accountId(), + receipt.accountUuid(), + receipt.tokenHash(), + receipt.operationKind(), + receipt.requestId(), + receipt.requestDigestVersion(), + receipt.requestDigest(), + receipt.tokenExpiresAt(), + receipt.passwordVerifierDigest(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + "sha256:" + "2".repeat(64), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + when(resets.findByRequestId(valid.requestId())) + .thenReturn(Optional.empty(), Optional.of(mismatchedReceipt)); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt does not match its source event"); + } + + private Account account() { + Account account = new Account(); + account.setId(11L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(11L); + account.setPasswordHash("unused-on-sequence-zero"); + return account; + } + + private AccountAuthorityGenerationRepository.ScopeState accountState( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, fence, fenceSourceVersion)); + } + + private Event passwordResetEvent( + UUID accountUuid, long sequence, long generation, long sourceVersion, String tokenHash) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String requestId = "account-password-reset-request-v1:" + tokenHash; + String eventId = "account-password-reset-event-v1:" + tokenHash; + var sealed = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, requestId, sequence, eventId, sealed.eventDigest(), sealed.canonicalJsonUtf8()); + } + + private PasswordResetReceipt passwordResetReceipt( + Event event, long fence, long fenceSourceVersion) { + String tokenHash = event.requestId().substring("account-password-reset-request-v1:".length()); + LocalDateTime tokenDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5); + String verifierDigest = "b".repeat(64); + return new PasswordResetReceipt( + 11L, + ACCOUNT_UUID, + tokenHash, + "PASSWORD_RESET", + event.requestId(), + 1, + passwordResetRequestDigest( + ACCOUNT_UUID, tokenHash, tokenDeadline.toString(), verifierDigest), + tokenDeadline, + verifierDigest, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion); + } + + private Event logoutAllEvent( + UUID accountUuid, UUID requestId, long sequence, long generation, long sourceVersion) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String eventId = "account-logout-all-event-v1:" + requestId; + var sealed = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, + requestId.toString(), + sequence, + eventId, + sealed.eventDigest(), + sealed.canonicalJsonUtf8()); + } + + private LogoutAllReceipt logoutReceipt(Event event, long fence, long fenceSourceVersion) { + UUID requestId = UUID.fromString(event.requestId()); + String tokenHash = "c".repeat(64); + String tokenProfile = "control-ui"; + return new LogoutAllReceipt( + requestId, + 11L, + ACCOUNT_UUID, + "ACCOUNT_LOGOUT_ALL", + 1, + AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, tokenProfile, tokenHash), + tokenHash, + tokenProfile, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion, + "LOGOUT_ALL_COMMITTED"); + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenDeadline, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, "account-password-reset-request/v1"); + updateLengthPrefixed(digest, "PASSWORD_RESET"); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenDeadline); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index 19bad6232f..a7a078ac59 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.service; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -33,6 +34,74 @@ class AccountAuthoritySourceEventReadbackTest { private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + @Test + void sequenceZeroRequiresOriginalPositiveBaselineWithoutReceipts() { + var outbox = mock(AccountAuthorityOutboxRepository.class); + var resets = mock(AccountPasswordResetOperationRepository.class); + var logouts = mock(AccountLogoutAllOperationRepository.class); + var security = mock(AccountSecurityStateOperationRepository.class); + var readback = new AccountAuthoritySourceEventReadback(outbox, resets, logouts, security); + String stream = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(stream)).thenReturn(Optional.empty()); + + var snapshot = readback.requireCurrentLatest(account(), accountState(1L, 1L, 4L, 3L)); + + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.latestEvent()).isEmpty(); + verify(outbox, never()) + .findEvent( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(resets, logouts, security); + } + + @Test + void sequenceZeroCannotRepairProgressedSourceWithoutHistory() { + var outbox = mock(AccountAuthorityOutboxRepository.class); + var resets = mock(AccountPasswordResetOperationRepository.class); + var logouts = mock(AccountLogoutAllOperationRepository.class); + var security = mock(AccountSecurityStateOperationRepository.class); + var readback = new AccountAuthoritySourceEventReadback(outbox, resets, logouts, security); + when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 5L, 4L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original positive 1/1 baseline"); + verify(outbox, never()) + .findEvent( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(resets, logouts, security); + } + + @Test + void checkpointCannotAuthorizePristineOrSingleCounterProgression() { + var outbox = mock(AccountAuthorityOutboxRepository.class); + var resets = mock(AccountPasswordResetOperationRepository.class); + var logouts = mock(AccountLogoutAllOperationRepository.class); + var security = mock(AccountSecurityStateOperationRepository.class); + var readback = new AccountAuthoritySourceEventReadback(outbox, resets, logouts, security); + String stream = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(stream)) + .thenReturn( + Optional.of(new Checkpoint(stream, 1L, "event-id", "sha256:" + "a".repeat(64)))); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(1L, 1L, 4L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("contradictory event history"); + for (var counters : java.util.List.of(new long[] {2L, 1L}, new long[] {1L, 2L})) { + assertThatThrownBy( + () -> + readback.requireCurrentLatest( + account(), accountState(counters[0], counters[1], 4L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("history is not proven"); + } + verify(outbox, never()) + .findEvent( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(resets, logouts, security); + } + @Test void unsupportedGenericAccountEventMapsToTypedUnavailableEvidence() { UUID accountUuid = UUID.fromString("11111111-1111-4111-8111-111111111111"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityStructuralReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityStructuralReadbackTest.java new file mode 100644 index 0000000000..d2c6631c1e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthorityStructuralReadbackTest.java @@ -0,0 +1,238 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class AccountAuthorityStructuralReadbackTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + + @Test + void structuralSecurityStateSnapshotAcceptsCompleteCurrentAndRetainedEvents() { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + AccountSourceSnapshot originalSnapshot = structuralSnapshot(original, 2L, 2L); + AccountSourceSnapshot newer = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + + assertThat(originalSnapshot.latestEvent()).contains(original); + assertThat(new AccountSourceEventReadback(newer, original).requestedEvent()) + .isEqualTo(original); + } + + @Test + void structuralSecurityStateSnapshotBindsEveryEventIndexAndCompleteCanonicalBytes() + throws Exception { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + JsonMapper json = JsonMapper.builder().build(); + ObjectNode substituted = (ObjectNode) json.readTree(original.payload()); + ((ObjectNode) substituted.get("accountState")).put("emailVerified", false); + ObjectNode wrongScope = (ObjectNode) json.readTree(original.payload()); + wrongScope.put("sourceScope", "account/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + for (Event invalid : + List.of( + new Event( + original.outboxStreamKey(), + "33333333-3333-4333-8333-333333333333", + 1L, + original.eventId(), + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId() + "other", + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId(), + "sha256:" + "a".repeat(64), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 2L, + original.eventId(), + original.eventDigest(), + original.payload()), + withPayload(original, substituted.toString().getBytes(StandardCharsets.UTF_8)), + withPayload(original, wrongScope.toString().getBytes(StandardCharsets.UTF_8)), + withPayload( + original, + (" " + new String(original.payload(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8)))) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class); + } + Event foreign = + securityStateEvent(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), 1L, "2", "2"); + assertThatThrownBy(() -> structuralSnapshot(foreign, 2L, 2L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void structuralSecurityStateCountersRequireCurrentEqualityAndRetainedNotAhead() { + Event generationMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "3", "2"); + Event versionMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "2", "3"); + Event arbitraryPrecision = + securityStateEvent(ACCOUNT_UUID, 1L, "922337203685477580812345678901234567890", "2"); + AccountSourceSnapshot current = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + for (Event invalid : List.of(generationMismatch, versionMismatch, arbitraryPrecision)) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + assertThatThrownBy(() -> new AccountSourceEventReadback(current, arbitraryPrecision)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + + @Test + void structurallyValidSecurityStateWithoutReceiptCannotPassOwnerReadback() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event event = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + assertThat(structuralSnapshot(event, 2L, 2L).latestEvent()).contains(event); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new Checkpoint(event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(event)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), event, accountState(3L, 3L, 3L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + verifyNoInteractions(resets, logouts); + } + + private AccountSourceSnapshot structuralSnapshot( + Event event, long generation, long sourceVersion) { + return new AccountSourceSnapshot( + ACCOUNT_UUID, + accountState(generation, sourceVersion, 2L, 2L), + "account:auth-authority:v1:account/" + ACCOUNT_UUID, + event.outboxSequence(), + Optional.of(event)); + } + + private Event withPayload(Event original, byte[] payload) { + return new Event( + original.outboxStreamKey(), + original.requestId(), + original.outboxSequence(), + original.eventId(), + original.eventDigest(), + payload); + } + + private Event securityStateEvent( + UUID accountUuid, long sequence, String generation, String sourceVersion) { + String requestId = "11111111-1111-4111-8111-111111111111"; + String stream = "account:auth-authority:v1:account/" + accountUuid; + var event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + Long.toString(sequence))), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))); + return new Event( + stream, + requestId, + sequence, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + } + + private Account account() { + Account account = new Account(); + account.setId(11L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(11L); + account.setPasswordHash("unused-on-sequence-zero"); + return account; + } + + private AccountAuthorityGenerationRepository.ScopeState accountState( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, fence, fenceSourceVersion)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java index 611243e7a8..fbd1193174 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java @@ -234,6 +234,32 @@ void refusesAbsentScopeAndMismatchWithImmutablePersistedV2Evidence() { assertThat(wrongDigest.transactions.rollbacks).isEqualTo(1); } + @Test + void missingCompanionEvidenceAfterSelectorReadCannotAuthorizeScope() { + Fixture f = new Fixture(); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn(Optional.empty()); + assertCode("CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, f.scope.connectScopeId())); + verify(f.scopes).findCanonical(f.scope.connectScopeId()); + verify(f.scopes) + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + assertThat(f.transactions.commits).isZero(); + assertThat(f.transactions.rollbacks).isEqualTo(1); + } + + @Test + void expiryAfterRetainedReadCannotReturnPreviouslyCurrentScope() { + Fixture f = new Fixture(); + Clock advancing = Mockito.mock(Clock.class); + when(advancing.instant()) + .thenReturn(f.clock.instant(), Instant.parse(f.scope.connectScopeExpiresAt())); + var reader = new AccountCanonicalConnectScopeReader(f.jwt, f.scopes, f.transactions, advancing); + assertCode("CONNECT_SCOPE_INVALID", () -> reader.read(ACCOUNT, f.scope.connectScopeId())); + assertThat(f.transactions.commits).isEqualTo(1); + verify(f.scopes).findCanonical(f.scope.connectScopeId()); + } + @Test void mapsDatabaseFailureAndCommitFailureToSafeAuthorityUnavailable() { Fixture readFailure = new Fixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index edef33bdaf..34230ed49a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -481,6 +481,59 @@ void mismatchedAuditReadbackCannotCommitTheGlobalOperation() { .commitCanonicalFirstJoin(anyString(), any(), anyString(), any()); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void absentOrUnavailableAuditReadbackCannotTerminalizePendingJoin(boolean unavailable) { + Fixture fixture = new Fixture(); + fixture.arrangePending(); + var readback = + when(fixture.audit.findExactCanonicalTenantEnvelopeForUpdate(fixture.auditEnvelope)); + if (unavailable) readback.thenThrow(new IllegalStateException("audit readback unavailable")); + else readback.thenReturn(Optional.empty()); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + unavailable ? "audit readback unavailable" : "Canonical JOIN audit readback is absent"); + verify(fixture.operations, never()) + .commitCanonicalFirstJoin(anyString(), any(), anyString(), any()); + // The exception escapes the mandatory owner transaction. Physical rollback is not mocked proof. + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void absentOrUnavailableCommittedAuditCannotBeRecreatedFromMembership(boolean unavailable) { + Fixture fixture = new Fixture(); + fixture.arrangeCommittedReplay(); + var readback = + when( + fixture.audit.findCanonicalTenantEnvelopeForUpdate( + fixture.expectedProof.auditEventId())); + if (unavailable) readback.thenThrow(new IllegalStateException("audit readback unavailable")); + else readback.thenReturn(Optional.empty()); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + unavailable + ? "audit readback unavailable" + : "Committed canonical JOIN audit is absent"); + verify(fixture.memberships, never()).createFreshMembershipForJoin(any(), any()); + verify(fixture.roles, never()).replaceCanonical(any(), any(), any(), any(), anyLong(), any()); + verify(fixture.audit, never()) + .appendCanonicalTenant(any(), anyString(), anyString(), anyString()); + verify(fixture.operations, never()) + .commitCanonicalFirstJoin(anyString(), any(), anyString(), any()); + } + @Test void readOnlyTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { Fixture fixture = new Fixture(); 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 895c108fda..3498d5326b 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 @@ -946,6 +946,21 @@ void conflictingCallerIsDeniedBeforeMembershipOrEventSourcesAreRead() { verifyNoInteractions(fixture.pairs, fixture.authority, fixture.outbox, fixture.sourceEvidence); } + @Test + void eventPublicationRejectsReadOnlyOwnerTransactionBeforeAnyLookup() { + Fixture fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Account JOIN requires a writable owner transaction"); + fixture.verifyNoOwnerInteractions(); + } + @Test void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { Fixture fixture = new Fixture(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java index cc3908be00..0d41159651 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java @@ -150,6 +150,64 @@ void exactOwnerEvidenceIsImportedReadBackAndGenerationInitializedInsideOneTransa verify(generations).initializeTenantIfAbsent(evidence.canonicalTenantId()); } + @Test + void missingAssociationReadbackCannotInitializeTenantGeneration() { + assertAssociationMismatchCannotInitializeGeneration(false, true); + } + + @Test + void substitutedAssociationReadbackCannotInitializeTenantGeneration() { + assertAssociationMismatchCannotInitializeGeneration(false, false); + } + + @Test + void substitutedImportedAssociationCannotInitializeTenantGeneration() { + assertAssociationMismatchCannotInitializeGeneration(true, false); + } + + private static void assertAssociationMismatchCannotInitializeGeneration( + boolean substituteImport, boolean missingReadback) { + GameDesignFreshTenantIdentityClient client = mock(GameDesignFreshTenantIdentityClient.class); + FreshTenantIdentityAssociationRepository associations = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + TransactionTemplate transaction = mock(TransactionTemplate.class); + var original = evidence(REQUEST_ID, REQUEST_DIGEST); + var substituted = + evidence(UUID.fromString("22222222-2222-4222-8222-222222222222"), REQUEST_DIGEST); + when(client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)).thenReturn(original); + when(associations.importVerified(original)) + .thenReturn(substituteImport ? substituted : original); + when(associations.read(original.canonicalTenantId())) + .thenReturn( + missingReadback + ? java.util.Optional.empty() + : java.util.Optional.of(substituteImport ? original : substituted)); + when(transaction.execute( + ArgumentMatchers + .> + any())) + .thenAnswer( + invocation -> + ((TransactionCallback) invocation.getArgument(0)) + .doInTransaction(mock(TransactionStatus.class))); + + FreshTenantIdentityEnrollmentService service = + new FreshTenantIdentityEnrollmentService(client, associations, generations, transaction); + + assertThatThrownBy(() -> service.enroll(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + missingReadback ? "readback is absent" : "readback differs from owner evidence"); + + verify(client).resolveCreation(REQUEST_ID, REQUEST_DIGEST); + verify(associations).importVerified(original); + verify(associations).read(original.canonicalTenantId()); + verifyNoInteractions(generations); + } + private static net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence evidence( UUID creationRequestId, String requestDigest) { UUID operationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java new file mode 100644 index 0000000000..75bd826804 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java @@ -0,0 +1,212 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class IssuerGenerationProjectionTest { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String STREAM = "account:auth-authority:v1:issuer/" + ISSUER; + + @Test + void baselineOmitsAllEventFieldsAndUsesOnlyCanonicalAccountIssuerKey() { + var projection = IssuerGenerationProjection.fromSource(source(1L, Optional.empty())); + assertThat(IssuerGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.key()).isEqualTo("session:auth:generation:issuer:" + ISSUER); + assertThat(projection.toJson()) + .doesNotContain("sourceEvent", "lastAppliedSourceEventId", "lastAppliedSourceEventDigest"); + assertThatThrownBy(() -> IssuerGenerationProjection.keyForIssuer("other-issuer")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactPositiveOwnerEventRetainsIdentityDigestScopeAndCheckpoint() { + var event = AccountAuthoritySourceEventV1Codec.sealIssuer(eventFields("2", "2", "1")); + var projection = IssuerGenerationProjection.fromSource(source(2L, Optional.of(event))); + assertThat(IssuerGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.lastAppliedSourceEventId()).contains(event.eventId()); + assertThat(projection.lastAppliedSourceEventDigest()).contains(event.eventDigest()); + assertThat(projection.sourceEvent()).contains(event.canonicalJson()); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "3", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of("different-event"), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of("sha256:" + "f".repeat(64)), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of( + event + .canonicalJson() + .replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":\"3\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void largeCanonicalCountersRemainExactWithoutFloatingPointNarrowing() { + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + eventFields("9007199254740993", "9007199254740993", "9007199254740992")); + var projection = + new IssuerGenerationProjection( + ISSUER, + event.issuerAuthGeneration(), + event.sourceVersion(), + STREAM, + event.outboxSequence(), + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson())); + var parsed = IssuerGenerationProjection.parse(projection.toJson()); + assertThat(parsed.generationValue()).isEqualTo(new BigInteger("9007199254740993")); + assertThat(parsed.sourceVersionValue()).isEqualTo(new BigInteger("9007199254740993")); + assertThat(parsed.outboxSequenceValue()).isEqualTo(new BigInteger("9007199254740992")); + } + + @Test + void closedParserRejectsDuplicateUnknownNullTrailingAndNoncanonicalForms() { + String json = IssuerGenerationProjection.fromSource(source(1L, Optional.empty())).toJson(); + for (String invalid : + List.of( + json + " {}", + " " + json, + json.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":1"), + json.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":null"), + json.replace( + "\"issuerAuthGeneration\":\"1\"", + "\"issuerAuthGeneration\":\"1\",\"issuerAuthGeneration\":\"1\""), + json.substring(0, json.length() - 1) + ",\"unknown\":\"1\"}", + json.substring(0, json.length() - 1) + ",\"sourceEvent\":null}")) { + assertThatThrownBy(() -> IssuerGenerationProjection.parse(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String counter : List.of("0", "-1", "+1", "01", " 1", "1 ", "1.0", "1e3", "")) { + assertThatThrownBy( + () -> + IssuerGenerationProjection.parse( + json.replace( + "\"issuerAuthGeneration\":\"1\"", + "\"issuerAuthGeneration\":\"" + counter + "\""))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void sequenceZeroCannotInventAdvancedStateAndPositiveSequenceCannotOmitEvidence() { + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "0", + Optional.empty(), + Optional.empty(), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.empty(), + Optional.empty(), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountAuthoritySourceEventV1Codec.IssuerPreimage eventFields( + String generation, String version, String sequence) { + String request = UUID.randomUUID().toString(); + return new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + request, request, STREAM, sequence, ISSUER, generation, version, "ISSUER_SECURITY_CHANGE"); + } + + private static CanonicalIssuerSourceSnapshot source( + long generation, Optional event) { + var source = + new CurrentSourceEvidence( + new AuthorityScope(ScopeKind.ISSUER, ISSUER, null, null), + generation, + generation, + null, + new SourceCheckpoint( + STREAM, + generation - 1L, + event.map(e -> e.eventId()), + event.map(e -> e.eventDigest())), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + return new CanonicalIssuerSourceSnapshot( + source, + event.map( + e -> + new Event( + STREAM, + e.requestId(), + generation - 1L, + e.eventId(), + e.eventDigest(), + e.canonicalJsonUtf8()))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java new file mode 100644 index 0000000000..5139851fc4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java @@ -0,0 +1,188 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ExactIssuerAuthorityEventReadback; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountIssuerAuthoritySourceGrpcService; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import org.junit.jupiter.api.Test; + +class AccountIssuerAuthoritySourceGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + private final AccountIssuerSourceSnapshotReadOwner owner = + mock(AccountIssuerSourceSnapshotReadOwner.class); + private final AccountIssuerAuthoritySourceGrpcService service = + new AccountIssuerAuthoritySourceGrpcService(owner); + + @Test + void encodesOnlyTheOwnerReturnedClosedSnapshotAndCompletesOnce() { + UUID operation = UUID.randomUUID(); + var typedRequest = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, Optional.empty()); + var request = AccountIssuerSourceSnapshotGrpcCodec.toRequest(typedRequest, NAMESPACE, CALLER); + var evidence = + new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, "1", "1", STREAM, "0", Optional.empty()); + when(owner.read(request)) + .thenReturn( + new AccountIssuerSourceSnapshotReadOwner.ReadResult(typedRequest, CALLER, evidence)); + var observer = new RecordingObserver(); + + service.readCurrentIssuerAuthoritySource(request, observer); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value).isEqualTo(AccountIssuerSourceSnapshotGrpcCodec.toWire(evidence)); + verify(owner).read(request); + } + + @Test + void preservesCanonicalStatusClassesAndSanitizesTheirDescriptions() { + var observer = new RecordingObserver(); + when(owner.read(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("raw SQL row and event payload") + .asRuntimeException()); + + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), observer); + + assertThat(observer.error.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.error.getDescription()).doesNotContain("raw SQL"); + assertThat(observer.completed).isFalse(); + } + + @Test + void mapsMalformedRequestAndUnexpectedOwnerFailureWithoutLeakingDetails() { + var invalid = new RecordingObserver(); + when(owner.read(any())) + .thenThrow( + new IllegalArgumentException("raw request data"), + new IllegalStateException("connection password detail")); + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), invalid); + assertThat(invalid.error.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(invalid.error.getDescription()).doesNotContain("raw request"); + + var unavailable = new RecordingObserver(); + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), unavailable); + assertThat(unavailable.error.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.error.getDescription()).doesNotContain("password detail"); + } + + @Test + void encodesOwnerHistoryAndRejectsAConflictingOwnerResult() { + UUID operation = UUID.randomUUID(); + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "event-a", "event-a", STREAM, "1", ISSUER, "2", "2", "SIGNER_COMPROMISE")); + var scope = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, Optional.empty()); + var typedRequest = + new AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest( + scope, 1L, event.eventId(), event.eventDigest()); + var request = + AccountIssuerSourceSnapshotGrpcCodec.toExactEventRequest(typedRequest, NAMESPACE, CALLER); + var evidence = + new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + CALLER, + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of(event.canonicalJson())); + var baseline = + new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, "1", "1", STREAM, "0", Optional.empty()); + when(owner.readExactEvent(request)) + .thenReturn( + new AccountIssuerSourceSnapshotReadOwner.ExactEventReadResult( + typedRequest, + CALLER, + new AccountIssuerSourceSnapshotGrpcCodec.ExactEventReadback(evidence, event)), + new AccountIssuerSourceSnapshotReadOwner.ExactEventReadResult( + typedRequest, + CALLER, + new AccountIssuerSourceSnapshotGrpcCodec.ExactEventReadback(baseline, event))); + + var accepted = new RecordingObserver(); + service.readExactIssuerAuthorityEvent(request, accepted); + assertThat(accepted.error).isNull(); + assertThat(accepted.completed).isTrue(); + assertThat(accepted.value.getCurrentSnapshot()) + .isEqualTo(AccountIssuerSourceSnapshotGrpcCodec.toWire(evidence)); + assertThat(accepted.value.getSelectedEvent().toByteArray()) + .isEqualTo(event.canonicalJsonUtf8()); + + var denied = new RecordingObserver(); + service.readExactIssuerAuthorityEvent(request, denied); + assertThat(denied.error.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(denied.completed).isFalse(); + assertThat(denied.value).isNull(); + } + + @Test + void sanitizesExactHistoryOwnerRefusalWithoutAReply() { + when(owner.readExactEvent(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("private retained event") + .asRuntimeException()); + var observer = new RecordingObserver(); + + service.readExactIssuerAuthorityEvent( + ReadExactIssuerAuthorityEventRequest.getDefaultInstance(), observer); + + assertThat(observer.error.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.error.getDescription()).doesNotContain("private retained event"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private Status error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index 3a75f2bc03..388a7d3c34 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -74,6 +74,31 @@ void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() thro verifyNoInteractions(owner); } + @Test + @SuppressWarnings("unchecked") + void ordinaryBindingAlwaysRejectsMissingTlsBeforeHandlerOrOwner() { + var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); + var service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); + var method = + net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc + .getReadPlayerAdmissionEntitlementMethod(); + io.grpc.ServerCall< + ReadPlayerAdmissionEntitlementRequest, ReadPlayerAdmissionEntitlementResponse> + call = mock(io.grpc.ServerCall.class); + when(call.getAttributes()).thenReturn(io.grpc.Attributes.EMPTY); + when(call.getMethodDescriptor()).thenReturn(method); + var definition = service.bindService().getMethod(method.getFullMethodName()); + var handler = + (io.grpc.ServerCallHandler< + ReadPlayerAdmissionEntitlementRequest, ReadPlayerAdmissionEntitlementResponse>) + definition.getServerCallHandler(); + handler.startCall(call, new io.grpc.Metadata()); + var status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any()); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner); + } + @ParameterizedTest @MethodSource("ownerFailures") void ownerFailuresRetainExactAvailabilityClassificationWithoutSourceDetails( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 1f83e596ae..4b36b3f3b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -520,6 +520,19 @@ void ordinaryIssuanceKeepsItsProfileContractAfterExactOwnerReadback(OrdinaryIssu var claims = jwtUtil.parseToken(token).getPayload(); assertEquals(account.getAccountUuid().toString(), claims.getSubject()); assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals("firemud-account-service", claims.getIssuer()); + String expectedAudience = + switch (mode) { + case CONTROL_UI -> "control-ui"; + case GAMEPLAY_PASSWORD, EMAIL_OTP -> "account-service"; + case PLAYER_BOOTSTRAP -> "player-bootstrap"; + }; + assertEquals(java.util.Set.of(expectedAudience), claims.getAudience()); + assertNotNull(UUID.fromString(claims.getId())); + assertFalse(claims.containsKey("tenantId")); + if (mode != OrdinaryIssuance.PLAYER_BOOTSTRAP) { + assertEquals(java.util.List.of(), claims.get("globalRoles")); + } org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); if (mode != OrdinaryIssuance.GAMEPLAY_PASSWORD) { org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); @@ -832,6 +845,27 @@ void createAccountRejectsPublicIdentityWithoutExactPersistedSourceRow() { accountAuditOutboxRepository, profileRepository, accountTenantMembershipRepository); } + @Test + void createAccountPropagatesOwnerBirthFailureBeforeRegistrationAudit() { + IllegalStateException ownerFailure = + new IllegalStateException("Account source birth unavailable"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenThrow(ownerFailure); + + IllegalStateException observed = + assertThrows( + IllegalStateException.class, + () -> + service.createAccount( + new CreateAccountRequest("demo", "demo@example.com", "password"))); + + assertSame(ownerFailure, observed); + org.mockito.Mockito.verify(accountRepository) + .save(org.mockito.ArgumentMatchers.any(Account.class)); + verifyNoInteractions( + accountAuditOutboxRepository, profileRepository, accountTenantMembershipRepository); + } + @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = @@ -3084,6 +3118,7 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), org.junit.jupiter.params.provider.Arguments.of(valid, ""), org.junit.jupiter.params.provider.Arguments.of(valid, 11L), + org.junit.jupiter.params.provider.Arguments.of(valid, java.util.List.of(valid)), org.junit.jupiter.params.provider.Arguments.of(valid, "11"), org.junit.jupiter.params.provider.Arguments.of( valid, "00000000-0000-0000-0000-000000000000"), @@ -3249,8 +3284,10 @@ void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { @Test void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { composeOrdinaryBootstrapWorldDiscovery(); + String accountUuid = "10000000-0000-4000-8000-000000000001"; String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(accountUuid, Map.of("accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -3258,6 +3295,7 @@ void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test @@ -3902,36 +3940,28 @@ void bootstrapPublicRealmFacadePreservesEmptyCanonicalOwnerResult() { } @Test - void grantRealmAccessUpsertsRuntimeGrant() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountRealmAccessGrantRepository.findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(Optional.empty()); - when(accountRealmAccessGrantRepository.save( - org.mockito.ArgumentMatchers.any(AccountRealmAccessGrant.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - var result = - service.grantRealmAccess( - new RealmAccessGrantRequest( - 11L, 7L, "demo", "preview", "operator", "preview access", "req-grant-1")); - - assertTrue(result.granted()); - assertEquals(1L, result.grantVersion()); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository) - .save(org.mockito.ArgumentMatchers.any(AccountRealmAccessGrant.class)); + void grantRealmAccessRefusesBeforeAccountOrGrantLookup() { + AuthenticationException failure = + assertThrows( + AuthenticationException.class, + () -> + service.grantRealmAccess( + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "operator", "preview access", "req-grant-1"))); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions( + accountRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository); } @Test - void revokeRealmAccessUsesDurableRepositoryRevocation() { - service.revokeRealmAccess(11L, 7L, "demo", "preview"); - - org.mockito.Mockito.verify(accountRealmAccessGrantRepository) - .revokeByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + void revokeRealmAccessRefusesBeforeGrantMutation() { + AuthenticationException failure = + assertThrows( + AuthenticationException.class, + () -> service.revokeRealmAccess(11L, 7L, "demo", "preview")); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions( + accountRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository); } @Test @@ -3971,34 +4001,17 @@ void getRealmAccessGrantForRuntimeDoesNotAuthorizeRetainedRevocationTombstone() } @Test - void grantRealmAccessReactivatesRetainedTombstoneAndAdvancesItsVersion() { - Account account = new Account(); - account.setId(11L); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AccountRealmAccessGrant revoked = new AccountRealmAccessGrant(); - revoked.setId(19L); - revoked.setAccount(account); - revoked.setTenantId(7L); - revoked.setWorldSlug("demo"); - revoked.setRealmSlug("preview"); - revoked.setGrantVersion(7L); - revoked.setGranted(false); - when(accountRealmAccessGrantRepository.findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(Optional.of(revoked)); - when(accountRealmAccessGrantRepository.save( - org.mockito.ArgumentMatchers.any(AccountRealmAccessGrant.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - var result = - service.grantRealmAccess( - new RealmAccessGrantRequest( - 11L, 7L, "demo", "preview", "operator", "regrant", "req-grant-3")); - - assertTrue(result.granted()); - assertEquals(8L, result.grantVersion()); - assertTrue(revoked.isGranted()); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository).save(revoked); + void grantRealmAccessCannotReactivateOrAdvanceRetainedGrant() { + AuthenticationException failure = + assertThrows( + AuthenticationException.class, + () -> + service.grantRealmAccess( + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "operator", "regrant", "req-grant-3"))); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions( + accountRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository); } @Test @@ -4224,6 +4237,27 @@ void exportAccountDataIncludesProfilesAcrossTenants() { assertThrows(AuthenticationException.class, () -> service.exportAccountData(2L)).getCode()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void exportAccountDataRejectsContradictoryOwnerBeforeProfileRead(boolean wrongOwner) { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + if (wrongOwner) { + account.setId(3L); + } else { + account.setAccountUuidSourceNumericId(3L); + } + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> service.exportAccountData(2L)); + + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + org.mockito.Mockito.verify(accountRepository).findById(2L); + verifyNoInteractions(profileRepository, notificationService); + } + @Test void exportTenantDataRequiresTenantMembershipOrProfile() { Account account = new Account(); @@ -4261,6 +4295,29 @@ void exportTenantDataUsesPublicAccountUuidAndRetainsTenantLocalFields() { org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); } + @Test + void deleteAccountRejectsMissingOwnerBeforeRetentionOrChildAccess() { + when(accountRepository.findById(404L)).thenReturn(Optional.empty()); + + IllegalArgumentException failure = + assertThrows(IllegalArgumentException.class, () -> service.deleteAccount(404L)); + + assertEquals("Account not found", failure.getMessage()); + org.mockito.Mockito.verify(accountRepository).findById(404L); + verifyNoInteractions( + accountJoinOperationRepository, + retainedSubscriptionEvidenceRepository, + emailVerificationTokenRepository, + passwordResetTokenRepository, + accountRealmAccessGrantRepository, + externalAccountRepository, + paymentTransactionRepository, + profileRepository, + accountTenantMembershipRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + } + @Test void deleteAccountRefusesNonterminalSubscription() { Account account = new Account(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java index 46b1f625da..86323fd545 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -5,12 +5,14 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -155,6 +157,37 @@ static void generateSigningKey() throws Exception { signingKey = generator.generateKeyPair(); } + @Test + void bothActorScopesRejectAmbientSqlBeforeExternalOrOwnerReads() throws Exception { + Fixture fixture = accountFixture(List.of()); + Object[] dependencies = { + fixture.publicJwks, + fixture.signerStates, + fixture.issuances, + fixture.sourceEvidence, + fixture.generations, + fixture.tenantEvents, + fixture.memberships, + fixture.membershipPairs, + fixture.roleSnapshots, + fixture.outbox, + fixture.authority, + fixture.accountSnapshot + }; + clearInvocations(dependencies); + for (boolean readOnly : new boolean[] {false, true}) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + assertThatThrownBy(() -> fixture.verifier.verifyAccount(fixture.compactJwt)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account JWT and Coordination reads must precede SQL ownership"); + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account JWT and Coordination reads must precede SQL ownership"); + verifyNoInteractions(dependencies); + } + } + @Test void advancedStringAccountCutoffVerifiesAgainstBothCurrentActorScopes() throws Exception { for (boolean accountOnly : new boolean[] {true, false}) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index 931ab92c65..4e34003d7e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -264,6 +264,91 @@ void currentSourceUnavailabilityDeniesWithoutMarkingOriginalTerminal() { verifyNoInteractions(fixture.registry, fixture.primary); } + @Test + void changedOriginalSourceDeniesReplayWithoutRecapturingOrTerminalizing() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.existing(); + var changed = fixture.tenantSource(); + when(changed.evidence()).thenReturn(new byte[] {99}); + when(fixture.authority.capture(original.accountId, original.tenantId, fixture.environment)) + .thenReturn(changed); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Control-ui original issuance/current recovery unavailable"); + } + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verify(fixture.authority, never()).captureInitial(any(), any()); + verifyNoInteractions(fixture.registry, fixture.primary, fixture.signers); + } + + @Test + void uncertainPreparedCommitNeverReachesSigningOrRegistry() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + fixture.allowControlledAttempt(); + var source = fixture.accountSource(); + var authenticated = mock(AccountServiceImpl.ControlUiPrimaryIdentity.class); + when(authenticated.accountId()).thenReturn(fixture.account); + when(fixture.primary.authenticateControlUiPrimaryIdentity( + anyString(), anyString(), any(Runnable.class))) + .thenAnswer( + call -> { + call.getArgument(2, Runnable.class).run(); + return authenticated; + }); + when(fixture.authority.captureAccount(fixture.account)).thenReturn(source); + when(fixture.signers.captureCurrent()) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + when(fixture.cryptography.currentKeyId()).thenReturn("test-only-mac-key"); + when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("original-request-digest"); + var prepared = fixture.storedAccount("PREPARED", fixture.recoveryExpiry, null); + var preparedWritten = new java.util.concurrent.atomic.AtomicBoolean(); + when(fixture.operations.prepare( + any(), + anyString(), + any(), + anyString(), + anyString(), + any(), + any(), + any(), + any(), + anyLong())) + .thenAnswer( + call -> { + preparedWritten.set(true); + return prepared; + }); + var uncertain = new IllegalStateException("test-only PREPARED commit acknowledgement lost"); + doAnswer( + call -> { + TransactionSynchronizationManager.clear(); + if (preparedWritten.get()) throw uncertain; + return null; + }) + .when(fixture.transactions) + .commit(any()); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy(() -> fixture.service().issueAccount(fixture.accountRequest())) + .isSameAs(uncertain); + } + assertThat(preparedWritten).isTrue(); + verify(fixture.abuse, org.mockito.Mockito.times(2)).isUsable(any()); + verify(fixture.signers, never()).sign(any(), any(), any()); + verify(fixture.operations, never()).bindCandidate(any(), anyString(), any(), any(), any()); + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions(fixture.registry, fixture.actors); + } + @Test void committedRecoveryReturnsTheExactOriginalCredentialWithoutPrimaryAuthenticationOrSigning() { Fixture fixture = new Fixture(NOW.plusSeconds(30)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java index 2d53209ccc..0ad02f069e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -423,7 +423,10 @@ key, ascii("session:auth:generation:issuer:firemud-account-service"))) { keys.getAllValues().get(1)[0], ascii("session:auth:generation:account:" + ACCOUNT_ID))) .isTrue(); - assertThat(Arrays.equals(args.getAllValues().get(0)[0], values[0])).isTrue(); + assertThat(new String(args.getAllValues().get(0)[0], StandardCharsets.US_ASCII)) + .isEqualTo("VERIFY"); + assertThat(args.getAllValues().get(0)[1]).containsExactly(values[0]); + assertThat(args.getAllValues().get(0)[2]).isEmpty(); assertThat(new String(args.getAllValues().get(1)[0], StandardCharsets.US_ASCII)) .isEqualTo("VERIFY"); assertThat(args.getAllValues().get(1)[1]).containsExactly(values[1]); @@ -431,7 +434,7 @@ key, ascii("session:auth:generation:issuer:firemud-account-service"))) { verify(commands).aclWhoami(); verify(commands, times(1)) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); - verify(commands) + verify(commands, times(2)) .get( argThat( key -> @@ -444,6 +447,31 @@ key, ascii("session:auth:generation:issuer:firemud-account-service"))) { verify(connection).close(); } + @Test + void malformedRetainedIssuerDeniesBeforeAnyProjectionScriptOrAccountWrite() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.get(any(byte[].class))).thenReturn(ascii("{not-canonical}")); + assertThatThrownBy( + () -> client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(commands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands, times(1)) + .get( + argThat( + key -> + Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service")))); + verify(connection).close(); + } + @Test void wrongLiveAccountRoleDeniesProjectionBeforeScriptLoad() throws Exception { byte[][] values = @@ -562,7 +590,7 @@ void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws client(noAckConnection) .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); - verify(noAckCommands, times(1)).get(any(byte[].class)); + verify(noAckCommands, times(2)).get(any(byte[].class)); StatefulRedisConnection readbackConnection = connection(); RedisCommands readbackCommands = readbackConnection.sync(); @@ -574,20 +602,24 @@ void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws doReturn(List.of(1L, 1L)) .when(readbackCommands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); - when(readbackCommands.get(any(byte[].class))).thenReturn(null, ascii("wrong projection")); + when(readbackCommands.get(any(byte[].class))) + .thenReturn(null, null, ascii("wrong projection"), values[1]); assertThatThrownBy( () -> client(readbackConnection) .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(readbackCommands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(readbackCommands, times(4)).get(any(byte[].class)); } @Test void staleOrConflictingIssuerProjectionStopsBeforeAccountWriteOrDurabilityAck() throws Exception { byte[][] values = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); - for (long result : List.of(-1L, -2L, -4L, -5L)) { + for (long result : List.of(-1L, -2L, -3L, -4L, -5L)) { StatefulRedisConnection connection = connection(); RedisCommands commands = connection.sync(); when(commands.scriptLoad(any(byte[].class))) @@ -607,7 +639,12 @@ void staleOrConflictingIssuerProjectionStopsBeforeAccountWriteOrDurabilityAck() anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); verify(commands, org.mockito.Mockito.never()) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); - verify(commands, org.mockito.Mockito.never()).get(any(byte[].class)); + verify(commands, times(1)) + .get( + argThat( + key -> + Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service")))); verify(connection).close(); } } @@ -651,12 +688,16 @@ void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception assertThat(account.keys().getFirst().hashTagDeclaration()) .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); assertThat(issuer.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) - .containsExactly("canonicalProjectionUtf8"); + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); assertThat(account.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); assertThat(account.resourcePath()).isEqualTo("redis/account_generation_projection_cas.lua"); assertThat(issuer.resourcePath()) - .isEqualTo("redis/lua/account-game-session-delegation-authority-project.lua"); + .isEqualTo("redis/lua/account-game-session-delegation-authority-project-v2.lua"); + assertThat(issuer.supportedCoexistence()) + .containsExactly(new RedisScriptDescriptor.SupportedCoexistence("v2", "v1")); + assertThat(issuer.compatibilityLevel()) + .isEqualTo(RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET); assertThat(issuer.sha256()).isNotEqualTo(account.sha256()); byte[] source; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisherTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisherTest.java new file mode 100644 index 0000000000..738d43ce33 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionPublisherTest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerGenerationProjectionPublisherTest { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private final AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountGameplayDelegationRedisClient redis = + mock(AccountGameplayDelegationRedisClient.class); + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void unknownIssuerDeniesBeforeAnyCollaborator() { + var manager = mock(PlatformTransactionManager.class); + var publisher = new AccountIssuerGenerationProjectionPublisher(sources, manager, redis); + assertThatThrownBy(() -> publisher.refreshCurrent("other-issuer")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(manager, sources, redis); + } + + @Test + void ambientTransactionOrSynchronizationDeniesBeforeAnyCollaborator() { + var manager = mock(PlatformTransactionManager.class); + var publisher = new AccountIssuerGenerationProjectionPublisher(sources, manager, redis); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> publisher.refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inherit"); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> publisher.refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inherit"); + verifyNoInteractions(manager, sources, redis); + } + + @Test + void readsTwiceAroundRedisAfterEachActualTemplateTransactionCompletes() { + var manager = new TrackingManager(); + var snapshot = baseline(5); + var projection = IssuerGenerationProjection.fromSource(snapshot); + when(sources.readCurrentCanonicalIssuerSource(ISSUER)) + .thenAnswer( + ignored -> { + assertThat(manager.active).isTrue(); + return snapshot; + }); + when(redis.publishIssuerAuthorityProjection(projection)) + .thenAnswer( + ignored -> { + assertThat(manager.active).isFalse(); + assertThat(manager.commits).isEqualTo(1); + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY; + }); + var actual = + new AccountIssuerGenerationProjectionPublisher(sources, manager, redis) + .refreshCurrent(ISSUER); + assertThat(actual.key()).isEqualTo(projection.key()); + assertThat(actual.json()).isEqualTo(projection.toJson()); + assertThat(actual.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat(manager.commits).isEqualTo(2); + assertThat(manager.active).isFalse(); + var order = inOrder(sources, redis); + order.verify(sources).readCurrentCanonicalIssuerSource(ISSUER); + order.verify(redis).publishIssuerAuthorityProjection(projection); + order.verify(sources).readCurrentCanonicalIssuerSource(ISSUER); + order.verifyNoMoreInteractions(); + } + + @Test + void changedFullSourceRefusesEvenWhenProjectedBytesAreIdenticalWithoutImplicitRetry() { + var before = baseline(5); + var after = baseline(6); + assertThat(IssuerGenerationProjection.fromSource(before)) + .isEqualTo(IssuerGenerationProjection.fromSource(after)); + when(sources.readCurrentCanonicalIssuerSource(ISSUER)).thenReturn(before, after); + when(redis.publishIssuerAuthorityProjection(any())) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThatThrownBy( + () -> + new AccountIssuerGenerationProjectionPublisher( + sources, new TrackingManager(), redis) + .refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit retry"); + verify(sources, times(2)).readCurrentCanonicalIssuerSource(ISSUER); + verify(redis).publishIssuerAuthorityProjection(IssuerGenerationProjection.fromSource(before)); + verifyNoMoreInteractions(sources, redis); + } + + @Test + void redisFailureDoesNotReadSqlAgainOrRetry() { + var snapshot = baseline(5); + var failure = new IllegalStateException("controlled Redis failure"); + when(sources.readCurrentCanonicalIssuerSource(ISSUER)).thenReturn(snapshot); + when(redis.publishIssuerAuthorityProjection(any())).thenThrow(failure); + assertThatThrownBy( + () -> + new AccountIssuerGenerationProjectionPublisher( + sources, new TrackingManager(), redis) + .refreshCurrent(ISSUER)) + .isSameAs(failure); + verify(sources).readCurrentCanonicalIssuerSource(ISSUER); + verify(redis).publishIssuerAuthorityProjection(IssuerGenerationProjection.fromSource(snapshot)); + verifyNoMoreInteractions(sources, redis); + } + + private static CanonicalIssuerSourceSnapshot baseline(long initializationTransaction) { + return new CanonicalIssuerSourceSnapshot( + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1, + 1, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/" + ISSUER, + 0, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + initializationTransaction, + null), + Optional.empty()); + } + + private static final class TrackingManager implements PlatformTransactionManager { + private boolean active; + private int commits; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(active).isFalse(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + active = true; + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + assertThat(active).isTrue(); + active = false; + commits++; + } + + @Override + public void rollback(TransactionStatus status) { + active = false; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionRedisClientTest.java new file mode 100644 index 0000000000..de00b36476 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountIssuerGenerationProjectionRedisClientTest.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +/** The issuer-only operation uses the installed v2 one-key contract, not the obsolete v1 store. */ +class AccountIssuerGenerationProjectionRedisClientTest { + private static final IssuerGenerationProjection BASELINE = + new IssuerGenerationProjection( + GameSessionAccountDelegationProfile.ISSUER, + "1", + "1", + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER, + "0", + Optional.empty(), + Optional.empty(), + Optional.empty()); + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issuerOnlyUsesExactlyOneCanonicalKeyCasPinnedConnectionAckAndExactReadback(boolean retry) + throws Exception { + var f = fixture(); + byte[] bytes = BASELINE.toJson().getBytes(StandardCharsets.UTF_8); + when(f.commands.get(any(byte[].class))).thenReturn(retry ? bytes : null, bytes); + when(f.commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(retry ? 0L : 1L); + assertThat(f.client.publishIssuerAuthorityProjection(BASELINE)) + .isEqualTo( + retry + ? AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY + : AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + var keys = ArgumentCaptor.forClass(byte[][].class); + var arguments = ArgumentCaptor.forClass(byte[][].class); + verify(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), keys.capture(), arguments.capture()); + assertThat(keys.getValue().length).isEqualTo(1); + assertThat(keys.getValue()[0]) + .containsExactly(BASELINE.key().getBytes(StandardCharsets.US_ASCII)); + assertThat(new String(arguments.getValue()[0], StandardCharsets.US_ASCII)) + .isEqualTo(retry ? "VERIFY" : "ABSENT"); + assertThat(arguments.getValue()[1]).containsExactly(retry ? bytes : new byte[0]); + assertThat(arguments.getValue()[2]).containsExactly(retry ? new byte[0] : bytes); + verify(f.commands).aclWhoami(); + verify(f.commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(f.commands, times(2)).get(any(byte[].class)); + verify(f.connection).close(); + } + + @ParameterizedTest + @ValueSource( + strings = {"ROLE", "RECONNECT", "MALFORMED", "CAS_REFUSAL", "AOF", "READBACK", "TTL"}) + void issuerOnlyCannotReturnSuccessForUncertainOrNoncanonicalPublication(String failure) + throws Exception { + var f = fixture(); + byte[] bytes = BASELINE.toJson().getBytes(StandardCharsets.UTF_8); + when(f.commands.get(any(byte[].class))).thenReturn(null, bytes); + switch (failure) { + case "ROLE" -> when(f.commands.aclWhoami()).thenReturn("cache_rate_limit_app"); + case "RECONNECT" -> when(f.connection.getOptions()).thenReturn(ClientOptions.create()); + case "MALFORMED" -> + when(f.commands.get(any(byte[].class))).thenReturn("{}".getBytes(StandardCharsets.UTF_8)); + case "CAS_REFUSAL" -> + when(f.commands.evalsha( + anyString(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + any(byte[][].class))) + .thenReturn(-1L); + case "AOF" -> + doReturn(List.of(1L, 0L)) + .when(f.commands) + .dispatch( + any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + case "READBACK" -> when(f.commands.get(any(byte[].class))).thenReturn(null, new byte[0]); + case "TTL" -> when(f.commands.pttl(any(byte[].class))).thenReturn(5000L); + default -> throw new IllegalArgumentException(failure); + } + assertThatThrownBy(() -> f.client.publishIssuerAuthorityProjection(BASELINE)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(f.connection).close(); + } + + @Test + void issuerOnlyPinsExactInstalledCoordinationIssuerV2Descriptor() { + var catalog = + RedisScriptCatalog.fromContributions( + List.of( + new AccountGameplayDelegationRedisScriptContribution(), + new AccountGenerationProjectionRedisScriptContribution())); + var contract = + catalog.require(AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID); + assertThat(contract.scriptId()).endsWith(".v2"); + assertThat(contract.principal()).isEqualTo("account_coord_app"); + assertThat(contract.role().name()).isEqualTo("COORDINATION"); + assertThat(contract.keys()).hasSize(1); + assertThat(contract.keys().getFirst().ownedPrefix()) + .isEqualTo(IssuerGenerationProjection.KEY_PREFIX); + assertThat(contract.arguments().stream().map(value -> value.name()).toList()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + } + + @SuppressWarnings("unchecked") + private static Fixture fixture() throws Exception { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisCommands commands = mock(RedisCommands.class); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.pttl(any(byte[].class))).thenReturn(-1L); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-1").digest(invocation.getArgument(0)))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + var client = + new AccountGameplayDelegationRedisClient( + () -> connection, + RedisScriptCatalog.fromContributions( + List.of( + new AccountGameplayDelegationRedisScriptContribution(), + new AccountGenerationProjectionRedisScriptContribution())), + new AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements(1, 1, 1000), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + AccountIssuerGenerationProjectionRedisClientTest.class.getClassLoader()); + return new Fixture(client, connection, commands); + } + + private record Fixture( + AccountGameplayDelegationRedisClient client, + StatefulRedisConnection connection, + RedisCommands commands) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java index 5be8e81608..cc858472cd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java @@ -255,6 +255,34 @@ void sessionOutagePreservesExistingUnavailableExceptionRatherThanInvalidToken() DataAccessResourceFailureException.class, () -> verifier.requireCaller(TOKEN))); } + @Test + void renewedSameAccountSessionKeepsFingerprintButStillRequiresCurrentAuthentication() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account())); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, TOKEN)).thenReturn(true); + String refreshed = "different-current-bootstrap-token"; + when(jwtUtil.parseToken(refreshed)).thenReturn(signedToken); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, refreshed)).thenReturn(true); + // Scope authority is separately tested by AccountCanonicalConnectScopeReaderTest. + var first = + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint.lookup( + verifier.requireCaller(TOKEN).accountUuid(), + OTHER_UUID, + "same-exact-scope", + "same-request"); + var retry = + net.firedevops.firemud.accountservice.repository.ConnectTokenRequestFingerprint.lookup( + verifier.requireCaller(refreshed).accountUuid(), + OTHER_UUID, + "same-exact-scope", + "same-request"); + assertEquals(first, retry); + verify(sessionService).isAccountSessionActive(ACCOUNT_ID, TOKEN); + verify(sessionService).isAccountSessionActive(ACCOUNT_ID, refreshed); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, refreshed)).thenReturn(false); + assertThrows(AuthenticationException.class, () -> verifier.requireCaller(refreshed)); + } + private AuthenticationException requireInvalidCaller() { AuthenticationException failure = assertThrows(AuthenticationException.class, () -> verifier.requireCaller(TOKEN)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBoundsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBoundsTest.java new file mode 100644 index 0000000000..1e0c1388b0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureBoundsTest.java @@ -0,0 +1,53 @@ +package unit.net.firedevops.firemud.accountservice.tenantrole; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.tenantrole.TransferCaptureBounds; +import org.junit.jupiter.api.Test; + +class TransferCaptureBoundsTest { + @Test + void reverseRequestsUseTheSameUuidStringOrderRatherThanSignedUuidOrder() { + UUID low = UUID.fromString("00000000-0000-0000-0000-000000000001"); + UUID high = UUID.fromString("ffffffff-ffff-ffff-ffff-ffffffffffff"); + assertThat(TransferCaptureBounds.orderedAccounts(high, low)).containsExactly(low, high); + assertThat(TransferCaptureBounds.orderedAccounts(low, high)).containsExactly(low, high); + assertThatThrownBy(() -> TransferCaptureBounds.orderedAccounts(low, low)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TransferCaptureBounds.orderedAccounts(low, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void envelopeIsBoundedBeforeCopyAndOwnsItsBytes() { + byte[] source = {1}; + byte[] copy = TransferCaptureBounds.copyEnvelope(source); + source[0] = 2; + assertThat(copy).containsExactly((byte) 1); + assertThat( + TransferCaptureBounds.copyEnvelope(new byte[TransferCaptureBounds.MAX_CAPTURE_BYTES])) + .hasSize(TransferCaptureBounds.MAX_CAPTURE_BYTES); + assertThatThrownBy(() -> TransferCaptureBounds.copyEnvelope(new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TransferCaptureBounds.copyEnvelope( + new byte[TransferCaptureBounds.MAX_CAPTURE_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void hostileDeclaredLengthsCannotAllocateBeyondComponentOrRemainingEnvelope() { + assertThat(TransferCaptureBounds.componentLength(16384, 16384)).isEqualTo(16384); + for (int length : new int[] {-1, 0, 16385, Integer.MAX_VALUE}) { + assertThatThrownBy(() -> TransferCaptureBounds.componentLength(length, 262144)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> TransferCaptureBounds.componentLength(2, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TransferCaptureBounds.componentLength(1, -1)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodecTest.java new file mode 100644 index 0000000000..7a2727bd5b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantrole/TransferCaptureCodecTest.java @@ -0,0 +1,212 @@ +package unit.net.firedevops.firemud.accountservice.tenantrole; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +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.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository; +import net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec; +import net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.Member; +import net.firedevops.firemud.accountservice.tenantrole.TransferCaptureCodec.Pair; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import org.junit.jupiter.api.Test; + +/** Controlled records test consistency/encoding only, never actual owner provenance. */ +class TransferCaptureCodecTest { + private static final UUID TENANT = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final VerifiedTenantProvenance PROVENANCE = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("20000000-0000-0000-0000-000000000001"), + "sha256:" + "a".repeat(64)); + + @Test + void exactTwoMembersRoundTripWithoutRefreshingOrGrantingAuthority() { + Pair pair = new Pair(member(UUID.randomUUID()), member(UUID.randomUUID())); + byte[] bytes = TransferCaptureCodec.encode(pair); + Pair read = TransferCaptureCodec.decode(bytes); + assertThat(TransferCaptureCodec.encode(read)).containsExactly(bytes); + assertThat(read.actor().event().canonicalJsonUtf8()) + .containsExactly(pair.actor().event().canonicalJsonUtf8()); + assertThat(read.actor().provenance()).isEqualTo(PROVENANCE); + assertThat(read.actor().membershipSourceVersion()).isEqualTo(4); + assertThat(read.target().issuanceFenceSourceVersion()).isEqualTo(5); + } + + @Test + void malformedLengthTruncationTrailingAndWrongMagicRefuse() { + byte[] valid = + TransferCaptureCodec.encode(new Pair(member(UUID.randomUUID()), member(UUID.randomUUID()))); + for (int length : new int[] {-1, 0, 16385, Integer.MAX_VALUE}) { + byte[] changed = valid.clone(); + ByteBuffer.wrap(changed).putInt(20, length); + assertThatThrownBy(() -> TransferCaptureCodec.decode(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + for (int length : new int[] {0, 3, valid.length - 1}) { + assertThatThrownBy(() -> TransferCaptureCodec.decode(Arrays.copyOf(valid, length))) + .isInstanceOf(IllegalArgumentException.class); + } + byte[] trailing = Arrays.copyOf(valid, valid.length + 1); + assertThatThrownBy(() -> TransferCaptureCodec.decode(trailing)) + .isInstanceOf(IllegalArgumentException.class); + valid[0] ^= 1; + assertThatThrownBy(() -> TransferCaptureCodec.decode(valid)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void decodedMembershipGenerationMustAgreeWithItsCapturedEvent() { + byte[] valid = + TransferCaptureCodec.encode(new Pair(member(UUID.randomUUID()), member(UUID.randomUUID()))); + ByteBuffer fields = ByteBuffer.wrap(valid); + fields.position(20); + skipText(fields); // provenance kind + fields.getLong(); // legacy tenant + skipText(fields); // provenance operation + skipText(fields); // provenance digest + skipText(fields); // issuer + fields.position(fields.position() + 8 * 8); // five source versions and three generations + fields.putLong(2); + assertThatThrownBy(() -> TransferCaptureCodec.decode(valid)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void skipText(ByteBuffer fields) { + int length = fields.getInt(); + fields.position(fields.position() + length); + } + + @Test + void duplicateMemberAndWrongCurrentEventOrLifecycleRefuse() { + Member member = member(UUID.randomUUID()); + assertThatThrownBy(() -> new Pair(member, member)).isInstanceOf(IllegalArgumentException.class); + UUID account = UUID.randomUUID(); + MembershipEvent event = event(account); + var roles = roles(account); + var pair = pair(account, event); + var authority = authority(account); + assertThatThrownBy( + () -> TransferCaptureCodec.fromObserved(roles, pair, authority, "LEFT", event)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TransferCaptureCodec.fromObserved( + roles, pair, authority, "ACTIVE", event(UUID.randomUUID()))) + .isInstanceOf(IllegalArgumentException.class); + var stale = new RoleSnapshot(1, null, 2, 2, List.of("player"), account, TENANT, PROVENANCE); + assertThatThrownBy( + () -> TransferCaptureCodec.fromObserved(stale, pair, authority, "ACTIVE", event)) + .isInstanceOf(IllegalArgumentException.class); + var wrongFence = + new CompositeSnapshot( + authority.issuer(), + authority.account(), + authority.tenants(), + authority.memberships(), + new IssuanceFence(account, 2, 5)); + assertThatThrownBy( + () -> TransferCaptureCodec.fromObserved(roles, pair, wrongFence, "ACTIVE", event)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void currentAccountAndIssuerRotationDoesNotRewriteHistoricalMembershipEvent() { + UUID account = UUID.randomUUID(); + var old = authority(account); + var fence = new IssuanceFence(account, 2, 6); + var now = + new CompositeSnapshot( + new ScopeState(AuthorityScope.issuer("issuer"), 2, 2, null), + new ScopeState(AuthorityScope.account(account), 2, 3, fence), + old.tenants(), + List.of(new ScopeState(AuthorityScope.membership(account, TENANT), 1, 4, fence)), + fence); + var event = event(account); + var captured = + TransferCaptureCodec.fromObserved( + roles(account), pair(account, event), now, "ACTIVE", event); + assertThat(captured.currentIssuerGeneration()).isEqualTo(2); + assertThat(captured.currentAccountGeneration()).isEqualTo(2); + assertThat(captured.currentIssuanceFence()).isEqualTo(2); + assertThat(captured.event().authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(captured.event().issuanceFence()).isEqualTo("1"); + } + + private static Member member(UUID account) { + MembershipEvent event = event(account); + return TransferCaptureCodec.fromObserved( + roles(account), pair(account, event), authority(account), "ACTIVE", event); + } + + private static RoleSnapshot roles(UUID account) { + return new RoleSnapshot(1, null, 2, 1, List.of("player"), account, TENANT, PROVENANCE); + } + + private static PairAuthority pair(UUID account, MembershipEvent event) { + return new PairAuthority( + account, TENANT, PROVENANCE, true, 1, 1, 1, event.eventId(), event.eventDigest(), false); + } + + private static CompositeSnapshot authority(UUID account) { + IssuanceFence fence = new IssuanceFence(account, 1, 5); + return new CompositeSnapshot( + new ScopeState(AuthorityScope.issuer("issuer"), 1, 1, null), + new ScopeState(AuthorityScope.account(account), 1, 2, fence), + List.of(new ScopeState(AuthorityScope.tenant(TENANT), 1, 3, null)), + List.of(new ScopeState(AuthorityScope.membership(account, TENANT), 1, 4, fence)), + fence); + } + + private static MembershipEvent event(UUID account) { + String request = + AccountTenantRoleOperationRepository.eventRequestId(UUID.randomUUID(), account); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT.toString(), "1")); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT.toString(), "1")); + tuple.put("privateRealmGrantVersions", List.of()); + Map p = new LinkedHashMap<>(); + p.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + p.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + p.put( + "eventId", + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + request) + .getBytes(StandardCharsets.UTF_8)) + .toString()); + p.put("requestId", request); + p.put("outboxStreamKey", AccountTenantRoleOperationRepository.eventStreamKey(account, TENANT)); + p.put("outboxSequence", "1"); + p.put("sourceScope", "membership/" + account + "/" + TENANT); + p.put("accountId", account.toString()); + p.put("tenantId", TENANT.toString()); + p.put("membershipExists", true); + p.put("membershipLifecycleState", "ACTIVE"); + p.put("membershipVersion", Map.of(TENANT.toString(), "1")); + p.put("membershipAuthorityGeneration", "1"); + p.put("authorityTuple", tuple); + p.put("issuanceFence", "1"); + p.put("roles", List.of("player")); + p.put("gameplayAdmissionAllowed", true); + p.put("callerBoundAuthorityInvalidated", false); + return MembershipAuthorityEventV1Codec.seal(p); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateTestActions.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateTestActions.java new file mode 100644 index 0000000000..a8830e3d19 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/charactercreate/AccountCharacterCreateTestActions.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.accountservice.charactercreate; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; + +/** Controlled public source bytes derived from the shared offline base vector, not owner proof. */ +public final class AccountCharacterCreateTestActions { + private AccountCharacterCreateTestActions() {} + + public static AccountCharacterCreateIntent intent( + String namespace, UUID accountId, UUID tenantId, Instant expiresAt) { + try (InputStream input = + Objects.requireNonNull( + AccountCharacterCreateTestActions.class.getResourceAsStream( + "/charactercreate/public-action.json"))) { + String raw = + new String(input.readAllBytes(), StandardCharsets.UTF_8) + .strip() + .replace( + "\"targetNamespace\":\"firemud\"", "\"targetNamespace\":\"" + namespace + "\"") + .replace("a4000000-0000-4000-8000-000000000001", accountId.toString()) + .replace("a1000000-0000-4000-8000-000000000001", tenantId.toString()) + .replace("2026-10-11T12:39:56.987654321Z", expiresAt.toString()); + byte[] bytes = raw.getBytes(StandardCharsets.UTF_8); + return new AccountCharacterCreateIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "Issued.Scope.Mixed_CASE-" + UUID.randomUUID(), + accountId, + bytes, + CharacterCreateOperatorActionCodec.mutationDigest(bytes), + "controlled-owner-source-readback".getBytes(StandardCharsets.UTF_8)); + } catch (IOException failure) { + throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable", failure); + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java index 5d363e4a17..1cee39a392 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java @@ -13,6 +13,7 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.config.AccountCredentialAbuseConfiguration; import net.firedevops.firemud.test.TestContainerImages; @@ -35,7 +36,7 @@ public static GenericContainer container() { .withStartupTimeout(Duration.ofSeconds(30)) .withCreateContainerCmdModifier( command -> - java.util.Objects.requireNonNull(command.getHostConfig()) + Objects.requireNonNull(command.getHostConfig()) .withMemory(PROCESS_BYTES) .withMemorySwap(PROCESS_BYTES) .withPidsLimit(128L)) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 03ece80be6..799c1109a8 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -57,6 +57,35 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable private final Path temporary; private IssuedCreator originalCreator; + /** + * Explicit test-only shared-abuse owner. The caller owns its separate Cache/Rate-Limit Redis + * lifecycle; this fixture neither provisions it nor supplies an admitting fallback. Controlled + * policy/key inputs do not establish deployed authority or production activation. + */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + AccountCredentialAbuseService credentialAbuse) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + null, + Clock.systemUTC(), + false, + Objects.requireNonNull(credentialAbuse, "Explicit shared-abuse owner required")); + } + public AccountControlUiOriginalOrderFixture( String jdbcUrl, String username, @@ -246,7 +275,37 @@ private AccountControlUiOriginalOrderFixture( migrationTarget, serviceClock, ownedCompositionConnections, - AccountControlUiOwnerSourcesFixture.defaultCreation(gameDesignTenant)); + (AccountCredentialAbuseService) null); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock, + boolean ownedCompositionConnections, + AccountCredentialAbuseService credentialAbuse) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + ownedCompositionConnections, + AccountControlUiOwnerSourcesFixture.defaultCreation(gameDesignTenant), + credentialAbuse); } private AccountControlUiOriginalOrderFixture( @@ -263,6 +322,37 @@ private AccountControlUiOriginalOrderFixture( boolean ownedCompositionConnections, FreshTenantCreationEvidence creationEvidence) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + ownedCompositionConnections, + creationEvidence, + null); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock, + boolean ownedCompositionConnections, + FreshTenantCreationEvidence creationEvidence, + AccountCredentialAbuseService credentialAbuse) + throws Exception { this.temporary = temporary; Objects.requireNonNull(actorClock, "actorClock"); Objects.requireNonNull(serviceClock, "serviceClock"); @@ -282,7 +372,10 @@ private AccountControlUiOriginalOrderFixture( try { allocatedAbuseKey = new DigestKey("fixture-key", new byte[32]); credentialAbuseKey = allocatedAbuseKey; - credentialAbuse = testCredentialAbuseService(credentialAbuseKey); + this.credentialAbuse = + credentialAbuse != null + ? credentialAbuse + : testCredentialAbuseService(credentialAbuseKey); signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); var lifecycle = signerFixture; lifecycle.commit(); @@ -376,7 +469,7 @@ private AccountControlUiOriginalOrderFixture( issuance = new AccountControlUiIssuanceService( f.primary, - credentialAbuse, + this.credentialAbuse, operations, f.authority, f.fences, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java index fe88911972..2f7ceb6446 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -516,7 +516,7 @@ private static RedisScriptCatalog loginScriptCatalog() throws IOException { List.of( "/redis/scripts/account-game-session-delegation-pending-register.json", "/redis/scripts/account-game-session-delegation-activate-committed.json", - "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer-v2.json", "/redis/scripts/account-initial-gameplay-login-dispose.json")) { try (var input = AccountPlayerAdmissionSharedOwnerFixture.class.getResourceAsStream(resource)) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java new file mode 100644 index 0000000000..2d53b9a2e8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.common.account.authority; + +import io.grpc.ManagedChannel; +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.Collection; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventReadback; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered, fail-closed mTLS client for Account's issuer-authority source read. */ +public final class AccountIssuerAuthoritySourceClient + extends AbstractReloadingBlockingGrpcClient< + AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceBlockingStub> { + private static final Duration RPC_DEADLINE = Duration.ofSeconds(5); + private static final int DEFAULT_PORT = 6565; + + private final String configuredNamespace; + private final String clientWorkloadUri; + private final String accountWorkloadUri; + private final CommonGrpcClientProperties tlsPropertiesForValidation; + private volatile boolean initialized; + private volatile boolean clientClosed; + + public AccountIssuerAuthoritySourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String configuredNamespace) { + super( + Objects.requireNonNull(endpoints, "endpoints is required"), + requireFileBackedMutualTls(tlsProperties), + Objects.requireNonNull(channelFactory, "channelFactory is required"), + AccountIssuerAuthoritySourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("configuredNamespace must be one canonical DNS label"); + } + this.configuredNamespace = configuredNamespace; + this.clientWorkloadUri = + "spiffe://firemud/ns/" + configuredNamespace + "/sa/game-session-service"; + this.accountWorkloadUri = "spiffe://firemud/ns/" + configuredNamespace + "/sa/account-service"; + this.tlsPropertiesForValidation = tlsProperties.copy(); + } + + /** + * Initializes this explicitly constructed client; it is not component-scanned or auto-configured. + */ + @PostConstruct + public synchronized void init() throws SSLException, IOException { + if (clientClosed) { + throw new IllegalStateException("issuer-source client is closed"); + } + if (initialized) { + return; + } + try { + validateFileBackedMutualTls(); + initReloadingClient(); + initialized = true; + } catch (IOException | RuntimeException | Error failure) { + clientClosed = true; + throw failure; + } + } + + /** + * Reads and independently validates the exact Account issuer snapshot for the supplied request. + */ + public AccountIssuerSourceSnapshotEvidence read( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request) { + requireReadableCall(request); + var wireRequest = + AccountIssuerSourceSnapshotGrpcCodec.toRequest( + request, configuredNamespace, clientWorkloadUri); + AccountIssuerAuthoritySourceSnapshot wireResponse = + stub() + .withDeadlineAfter(RPC_DEADLINE.toMillis(), TimeUnit.MILLISECONDS) + .readCurrentIssuerAuthoritySource(wireRequest); + return decodeResponse(wireResponse, request, clientWorkloadUri); + } + + /** Reads one immutable retained event and independently validates the current issuer snapshot. */ + public ExactEventReadback readExactEvent(ExactEventRequest request) { + requireReadableCall(request); + var wireRequest = + AccountIssuerSourceSnapshotGrpcCodec.toExactEventRequest( + request, configuredNamespace, clientWorkloadUri); + var wireResponse = + stub() + .withDeadlineAfter(RPC_DEADLINE.toMillis(), TimeUnit.MILLISECONDS) + .readExactIssuerAuthorityEvent(wireRequest); + return AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + wireResponse, request, clientWorkloadUri); + } + + @Override + public synchronized void close() throws IOException { + clientClosed = true; + initialized = false; + super.close(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected int defaultPort() { + return DEFAULT_PORT; + } + + @Override + protected AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceBlockingStub + buildStub(ManagedChannel channel) { + return AccountIssuerAuthoritySourceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(accountWorkloadUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(accountWorkloadUri)); + } + + static AccountIssuerSourceSnapshotEvidence decodeResponse( + AccountIssuerAuthoritySourceSnapshot wireResponse, + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, + String authenticatedCallerWorkload) { + return AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireResponse, request, authenticatedCallerWorkload); + } + + private void requireReadableCall(Object request) { + requireReadableLifecycle(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "issuer-source read cannot run inside an ambient transaction or synchronization"); + } + Objects.requireNonNull(request, "request is required"); + + // A hot-reloaded certificate must retain the exact client workload identity before any RPC is + // sent. + validateFileBackedMutualTls(); + } + + private void requireReadableLifecycle() { + if (clientClosed) { + throw new IllegalStateException("issuer-source client is closed"); + } + if (!initialized || stub() == null) { + throw new IllegalStateException("issuer-source client is not initialized"); + } + } + + private void validateFileBackedMutualTls() { + requireFileBackedMutualTls(tlsPropertiesForValidation); + validateClientCertificateIdentity(); + } + + private static CommonGrpcClientProperties requireFileBackedMutualTls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "issuer-source client requires TLS with file-backed client mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certChain"); + requireReadableFile(tlsProperties.getPrivateKey(), "privateKey"); + requireReadableFile(tlsProperties.getCaCert(), "caCert"); + return tlsProperties; + } + + private void validateClientCertificateIdentity() { + CommonGrpcClientProperties tlsProperties = currentTlsProperties(); + String certificatePath = tlsProperties.getCertChain(); + if (certificatePath == null || certificatePath.isBlank()) { + throw new IllegalStateException("issuer-source client certificate chain is not configured"); + } + Path path = Path.of(certificatePath); + try (InputStream input = Files.newInputStream(path)) { + Collection certificates = + CertificateFactory.getInstance("X.509").generateCertificates(input); + if (certificates.isEmpty() + || !(certificates.iterator().next() instanceof X509Certificate leaf)) { + throw new IllegalStateException("issuer-source client certificate chain has no X.509 leaf"); + } + GrpcPeerIdentity identity = + GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> + new IllegalStateException( + "issuer-source client leaf must contain one canonical workload URI SAN")); + if (!clientWorkloadUri.equals(identity.uri())) { + throw new IllegalStateException( + "issuer-source client leaf SAN must match the configured Game Session workload"); + } + } catch (IOException | java.security.cert.CertificateException failure) { + throw new IllegalStateException( + "issuer-source client certificate chain cannot be read", failure); + } + } + + private static void requireReadableFile(String configuredPath, String name) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException("issuer-source client " + name + " file is required"); + } + Path path; + try { + path = Path.of(configuredPath); + } catch (RuntimeException invalidPath) { + throw new IllegalArgumentException( + "issuer-source client " + name + " must be a file-backed path", invalidPath); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "issuer-source client " + name + " must be a readable regular file"); + } + } + + private CommonGrpcClientProperties currentTlsProperties() { + return tlsPropertiesForValidation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java new file mode 100644 index 0000000000..20cc916ad6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.account.authority; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Immutable, closed Account issuer-source snapshot evidence. Shape validation alone does not + * authenticate an Account response or authorize a Game Session projection update. + */ +public record AccountIssuerSourceSnapshotEvidence( + UUID reconciliationOperationId, + String targetNamespace, + String callerWorkload, + String issuerId, + String issuerAuthGeneration, + String sourceVersion, + String outboxStreamKey, + String lastCommittedOutboxSequence, + Optional sourceEvent) { + public static final int SCHEMA_VERSION = 1; + public static final String ISSUER_ID = "firemud-account-service"; + public static final String ISSUER_STREAM_KEY = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID; + public static final int MAX_SOURCE_EVENT_BYTES = 64 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + + public AccountIssuerSourceSnapshotEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + validateCallerWorkload(targetNamespace, callerWorkload); + requireNonNil(reconciliationOperationId, "reconciliationOperationId"); + if (!ISSUER_ID.equals(issuerId)) { + throw new IllegalArgumentException("issuerId must be the supported Account issuer"); + } + if (!ISSUER_STREAM_KEY.equals(outboxStreamKey)) { + throw new IllegalArgumentException("outboxStreamKey must be the canonical issuer stream"); + } + requirePositiveDecimal(issuerAuthGeneration, "issuerAuthGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + BigInteger sequence = + requireNonnegativeDecimal(lastCommittedOutboxSequence, "lastCommittedOutboxSequence"); + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent presence is required"); + + if (sequence.signum() == 0) { + if (!"1".equals(issuerAuthGeneration) || !"1".equals(sourceVersion)) { + throw new IllegalArgumentException( + "sequence-zero issuer source must have generation and source version one"); + } + if (sourceEvent.isPresent()) { + throw new IllegalArgumentException("sequence-zero issuer source must omit sourceEvent"); + } + } else { + BigInteger generation = new BigInteger(issuerAuthGeneration); + BigInteger version = new BigInteger(sourceVersion); + if (generation.compareTo(BigInteger.ONE) <= 0 || version.compareTo(BigInteger.ONE) <= 0) { + throw new IllegalArgumentException( + "advanced issuer source must have generation and source version greater than one"); + } + String canonicalEvent = + sourceEvent.orElseThrow( + () -> new IllegalArgumentException("positive issuer sequence requires sourceEvent")); + byte[] eventBytes = strictUtf8(canonicalEvent, "sourceEvent"); + if (eventBytes.length == 0 || eventBytes.length > MAX_SOURCE_EVENT_BYTES) { + throw new IllegalArgumentException("sourceEvent must be nonempty and at most 64 KiB"); + } + verifyIssuerEvent( + canonicalEvent, issuerAuthGeneration, sourceVersion, lastCommittedOutboxSequence); + } + } + + /** Returns fresh UTF-8 storage on every call so callers cannot mutate retained evidence. */ + public Optional sourceEventBytes() { + return sourceEvent.map(value -> strictUtf8(value, "sourceEvent")); + } + + public static void validateCallerWorkload(String targetNamespace, String callerWorkload) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + String expected = "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service"; + var identity = GrpcPeerIdentity.parseUri(callerWorkload); + if (identity.isEmpty() + || !expected.equals(callerWorkload) + || !identity.orElseThrow().isInNamespace(targetNamespace) + || !identity.orElseThrow().isService("game-session-service")) { + throw new IllegalArgumentException( + "callerWorkload must be the canonical same-namespace Game Session SPIFFE URI"); + } + } + + private static void verifyIssuerEvent( + String canonicalEvent, String generation, String version, String sequence) { + AccountAuthoritySourceEventV1Codec.SourceEvent verified = + AccountAuthoritySourceEventV1Codec.verify(canonicalEvent); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent)) { + throw new IllegalArgumentException("sourceEvent must use the closed issuer event schema"); + } + if (!canonicalEvent.equals(issuerEvent.canonicalJson())) { + throw new IllegalArgumentException("sourceEvent must use the exact canonical JSON encoding"); + } + if (!issuerEvent.eventId().equals(issuerEvent.requestId())) { + throw new IllegalArgumentException("issuer source eventId must equal requestId"); + } + if (!ISSUER_ID.equals(issuerEvent.issuerId()) + || !ISSUER_STREAM_KEY.equals(issuerEvent.outboxStreamKey()) + || !generation.equals(issuerEvent.issuerAuthGeneration()) + || !version.equals(issuerEvent.sourceVersion()) + || !sequence.equals(issuerEvent.outboxSequence())) { + throw new IllegalArgumentException( + "issuer source event must exactly match the snapshot issuer checkpoint"); + } + } + + private static BigInteger requirePositiveDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a positive canonical decimal string"); + } + return new BigInteger(value); + } + + private static BigInteger requireNonnegativeDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!NONNEGATIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a nonnegative canonical decimal string"); + } + return new BigInteger(value); + } + + private static byte[] strictUtf8(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException(field + " is not valid Unicode for UTF-8", malformed); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java new file mode 100644 index 0000000000..4768c9f05c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java @@ -0,0 +1,396 @@ +package net.firedevops.firemud.common.account.authority; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ExactIssuerAuthorityEventReadback; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Strict closed-proto mapping for the Account issuer-source owner read. */ +public final class AccountIssuerSourceSnapshotGrpcCodec { + private static final Pattern POSITIVE_OWNER_SEQUENCE = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private AccountIssuerSourceSnapshotGrpcCodec() {} + + /** Immutable request value; unknown wire fields are rejected before one can be constructed. */ + public record ReadRequest( + UUID reconciliationOperationId, + String targetNamespace, + String issuerId, + Optional expectedSource) { + public ReadRequest { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(reconciliationOperationId, "reconciliationOperationId"); + if (!AccountIssuerSourceSnapshotEvidence.ISSUER_ID.equals(issuerId)) { + throw new IllegalArgumentException("issuerId must be the supported Account issuer"); + } + expectedSource = + Objects.requireNonNull(expectedSource, "expectedSource presence is required"); + expectedSource.ifPresent( + source -> + requireRequestBinding(source, targetNamespace, reconciliationOperationId, issuerId)); + } + } + + /** Exact historical selector, scoped independently of any expected current snapshot. */ + public record ExactEventRequest( + ReadRequest scope, long outboxSequence, String expectedEventId, String expectedEventDigest) { + public ExactEventRequest { + Objects.requireNonNull(scope, "scope is required"); + if (scope.expectedSource().isPresent()) { + throw new IllegalArgumentException("exact event scope cannot carry an expected snapshot"); + } + if (outboxSequence <= 0L || outboxSequence == Long.MAX_VALUE) { + throw new IllegalArgumentException("outboxSequence must be in the positive owner range"); + } + if (expectedEventId == null + || expectedEventId.isBlank() + || expectedEventId.length() > 512 + || !expectedEventId.equals(expectedEventId.strip()) + || !StandardCharsets.UTF_8.newEncoder().canEncode(expectedEventId)) { + throw new IllegalArgumentException("expectedEventId must be bounded canonical text"); + } + if (expectedEventDigest == null || !EVENT_DIGEST.matcher(expectedEventDigest).matches()) { + throw new IllegalArgumentException( + "expectedEventDigest must be a canonical SHA-256 digest"); + } + } + } + + /** Independently validated source evidence returned by the exact event read. */ + public record ExactEventReadback( + AccountIssuerSourceSnapshotEvidence currentSnapshot, IssuerEvent selectedEvent) {} + + public static ReadExactIssuerAuthorityEventRequest toExactEventRequest( + ExactEventRequest request, String configuredNamespace, String authenticatedCallerWorkload) { + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + ReadRequest scope = request.scope(); + requireConfiguredNamespace(scope, configuredNamespace); + return ReadExactIssuerAuthorityEventRequest.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(scope.targetNamespace()) + .setReconciliationOperationId(scope.reconciliationOperationId().toString()) + .setIssuerId(scope.issuerId()) + .setOutboxSequence(Long.toString(request.outboxSequence())) + .setExpectedEventId(request.expectedEventId()) + .setExpectedEventDigest(request.expectedEventDigest()) + .build(); + } + + public static ExactEventRequest fromExactEventRequest( + ReadExactIssuerAuthorityEventRequest wire, + String configuredNamespace, + String authenticatedCallerWorkload) { + requireNoUnknownFields(wire, "exact issuer event request"); + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + requireSchemaVersion(wire.getSchemaVersion(), "exact issuer event request"); + ReadRequest scope = + new ReadRequest( + canonicalNonNilUuid(wire.getReconciliationOperationId(), "reconciliationOperationId"), + wire.getTargetNamespace(), + wire.getIssuerId(), + Optional.empty()); + requireConfiguredNamespace(scope, configuredNamespace); + return new ExactEventRequest( + scope, + parseOwnerSequence(wire.getOutboxSequence()), + wire.getExpectedEventId(), + wire.getExpectedEventDigest()); + } + + public static ExactIssuerAuthorityEventReadback toExactEventResponse( + AccountIssuerSourceSnapshotEvidence current, + IssuerEvent selected, + ExactEventRequest request, + String authenticatedCallerWorkload) { + AccountIssuerAuthoritySourceSnapshot currentWire = + toResponse(current, request.scope(), authenticatedCallerWorkload); + ByteString selectedBytes = ByteString.copyFromUtf8(selected.canonicalJson()); + requireEventSize(selectedBytes, "selectedEvent"); + IssuerEvent verified = verifyExactEvent(current, selected.canonicalJson(), request); + if (!verified.equals(selected)) { + throw new IllegalArgumentException( + "selected issuer event differs from its canonical payload"); + } + return ExactIssuerAuthorityEventReadback.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setCurrentSnapshot(currentWire) + .setSelectedEvent(selectedBytes) + .build(); + } + + public static ExactEventReadback fromExactEventResponse( + ExactIssuerAuthorityEventReadback wire, + ExactEventRequest request, + String authenticatedCallerWorkload) { + requireNoUnknownFields(wire, "exact issuer event response"); + requireSchemaVersion(wire.getSchemaVersion(), "exact issuer event response"); + if (!wire.hasCurrentSnapshot()) { + throw new IllegalArgumentException("currentSnapshot is required"); + } + AccountIssuerSourceSnapshotEvidence current = + fromResponse(wire.getCurrentSnapshot(), request.scope(), authenticatedCallerWorkload); + return new ExactEventReadback( + current, + verifyExactEvent(current, decodeUtf8(wire.getSelectedEvent(), "selectedEvent"), request)); + } + + private static IssuerEvent verifyExactEvent( + AccountIssuerSourceSnapshotEvidence current, + String canonicalEvent, + ExactEventRequest request) { + long currentSequence = Long.parseLong(current.lastCommittedOutboxSequence()); + if (!(AccountAuthoritySourceEventV1Codec.verify(canonicalEvent) instanceof IssuerEvent event) + || !canonicalEvent.equals(event.canonicalJson()) + || !event.eventId().equals(event.requestId()) + || !event.issuerId().equals(request.scope().issuerId()) + || !event.outboxStreamKey().equals(current.outboxStreamKey()) + || !event.outboxSequence().equals(Long.toString(request.outboxSequence())) + || !event.eventId().equals(request.expectedEventId()) + || !event.eventDigest().equals(request.expectedEventDigest()) + || request.outboxSequence() > currentSequence + || (request.outboxSequence() == currentSequence + && !current.sourceEvent().orElseThrow().equals(canonicalEvent))) { + throw new IllegalArgumentException("selected issuer event does not match the exact read"); + } + return event; + } + + private static long parseOwnerSequence(String value) { + if (!POSITIVE_OWNER_SEQUENCE.matcher(value).matches()) { + throw new IllegalArgumentException("outboxSequence must be a positive canonical decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException outOfRange) { + throw new IllegalArgumentException( + "outboxSequence must be in the positive owner range", outOfRange); + } + } + + public static ReadCurrentIssuerAuthoritySourceRequest toRequest( + ReadRequest request, String configuredNamespace, String authenticatedCallerWorkload) { + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + requireConfiguredNamespace(request, configuredNamespace); + request + .expectedSource() + .ifPresent(source -> requireCaller(source, authenticatedCallerWorkload)); + + ReadCurrentIssuerAuthoritySourceRequest.Builder builder = + ReadCurrentIssuerAuthoritySourceRequest.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReconciliationOperationId(request.reconciliationOperationId().toString()) + .setIssuerId(request.issuerId()); + request.expectedSource().ifPresent(source -> builder.setExpectedSource(toWire(source))); + return builder.build(); + } + + public static ReadRequest fromRequest( + ReadCurrentIssuerAuthoritySourceRequest wire, + String configuredNamespace, + String authenticatedCallerWorkload) { + requireNoUnknownFields(wire, "issuer source request"); + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + requireSchemaVersion(wire.getSchemaVersion(), "issuer source request"); + Optional expected = + wire.hasExpectedSource() + ? Optional.of(fromWire(wire.getExpectedSource())) + : Optional.empty(); + ReadRequest request = + new ReadRequest( + canonicalNonNilUuid(wire.getReconciliationOperationId(), "reconciliationOperationId"), + wire.getTargetNamespace(), + wire.getIssuerId(), + expected); + requireConfiguredNamespace(request, configuredNamespace); + request + .expectedSource() + .ifPresent(source -> requireCaller(source, authenticatedCallerWorkload)); + return request; + } + + /** Maps the response only when it still matches the exact request and authenticated caller. */ + public static AccountIssuerAuthoritySourceSnapshot toResponse( + AccountIssuerSourceSnapshotEvidence source, + ReadRequest request, + String authenticatedCallerWorkload) { + validateCallContext(request.targetNamespace(), authenticatedCallerWorkload); + requireResponseBinding(source, request, authenticatedCallerWorkload); + return toWire(source); + } + + /** Parses a response without permitting a changed source to replace an expected snapshot. */ + public static AccountIssuerSourceSnapshotEvidence fromResponse( + AccountIssuerAuthoritySourceSnapshot wire, + ReadRequest request, + String authenticatedCallerWorkload) { + AccountIssuerSourceSnapshotEvidence source = fromWire(wire); + validateCallContext(request.targetNamespace(), authenticatedCallerWorkload); + requireResponseBinding(source, request, authenticatedCallerWorkload); + return source; + } + + public static AccountIssuerAuthoritySourceSnapshot toWire( + AccountIssuerSourceSnapshotEvidence source) { + AccountIssuerAuthoritySourceSnapshot.Builder builder = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(source.targetNamespace()) + .setCallerWorkload(source.callerWorkload()) + .setReconciliationOperationId(source.reconciliationOperationId().toString()) + .setIssuerId(source.issuerId()) + .setIssuerAuthGeneration(source.issuerAuthGeneration()) + .setSourceVersion(source.sourceVersion()) + .setOutboxStreamKey(source.outboxStreamKey()) + .setLastCommittedOutboxSequence(source.lastCommittedOutboxSequence()); + source + .sourceEventBytes() + .ifPresent(bytes -> builder.setSourceEvent(ByteString.copyFrom(bytes))); + return builder.build(); + } + + public static AccountIssuerSourceSnapshotEvidence fromWire( + AccountIssuerAuthoritySourceSnapshot wire) { + requireNoUnknownFields(wire, "issuer source snapshot"); + requireSchemaVersion(wire.getSchemaVersion(), "issuer source snapshot"); + Optional sourceEvent = + wire.hasSourceEvent() + ? Optional.of(decodeUtf8(wire.getSourceEvent(), "sourceEvent")) + : Optional.empty(); + return new AccountIssuerSourceSnapshotEvidence( + canonicalNonNilUuid(wire.getReconciliationOperationId(), "reconciliationOperationId"), + wire.getTargetNamespace(), + wire.getCallerWorkload(), + wire.getIssuerId(), + wire.getIssuerAuthGeneration(), + wire.getSourceVersion(), + wire.getOutboxStreamKey(), + wire.getLastCommittedOutboxSequence(), + sourceEvent); + } + + private static void requireResponseBinding( + AccountIssuerSourceSnapshotEvidence source, + ReadRequest request, + String authenticatedCallerWorkload) { + requireRequestBinding(source, request); + requireCaller(source, authenticatedCallerWorkload); + request + .expectedSource() + .ifPresent( + expected -> { + if (!expected.equals(source)) { + throw new IllegalArgumentException( + "current issuer source differs from the exact expected snapshot"); + } + }); + } + + private static void requireRequestBinding( + AccountIssuerSourceSnapshotEvidence source, ReadRequest request) { + requireRequestBinding( + source, request.targetNamespace(), request.reconciliationOperationId(), request.issuerId()); + } + + private static void requireRequestBinding( + AccountIssuerSourceSnapshotEvidence source, + String targetNamespace, + UUID reconciliationOperationId, + String issuerId) { + if (!source.targetNamespace().equals(targetNamespace) + || !source.reconciliationOperationId().equals(reconciliationOperationId) + || !source.issuerId().equals(issuerId)) { + throw new IllegalArgumentException("issuer source snapshot does not match the request scope"); + } + } + + private static void requireCaller( + AccountIssuerSourceSnapshotEvidence source, String authenticatedCallerWorkload) { + if (!source.callerWorkload().equals(authenticatedCallerWorkload)) { + throw new IllegalArgumentException("issuer source snapshot caller workload changed"); + } + } + + private static void requireConfiguredNamespace(ReadRequest request, String configuredNamespace) { + if (!request.targetNamespace().equals(configuredNamespace)) { + throw new IllegalArgumentException( + "issuer source request namespace is not configured namespace"); + } + } + + private static void validateCallContext(String namespace, String callerWorkload) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace must be one canonical DNS label"); + } + AccountIssuerSourceSnapshotEvidence.validateCallerWorkload(namespace, callerWorkload); + } + + private static void requireNoUnknownFields(Message message, String description) { + Objects.requireNonNull(message, description + " is required"); + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(description + " contains unknown protobuf fields"); + } + } + + private static void requireSchemaVersion(int schemaVersion, String description) { + if (schemaVersion != AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException(description + " has an unsupported schema version"); + } + } + + private static UUID canonicalNonNilUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + final UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", malformed); + } + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + private static void requireEventSize(ByteString bytes, String field) { + if (bytes.isEmpty() + || bytes.size() > AccountIssuerSourceSnapshotEvidence.MAX_SOURCE_EVENT_BYTES) { + throw new IllegalArgumentException(field + " must be nonempty and at most 64 KiB"); + } + } + + private static String decodeUtf8(ByteString bytes, String field) { + requireEventSize(bytes, field); + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(bytes.asReadOnlyByteBuffer()) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException(field + " contains malformed UTF-8", malformed); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java new file mode 100644 index 0000000000..ea9476d712 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java @@ -0,0 +1,576 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ExactIssuerAuthorityEventReadback; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.account.v1.ReadExactIssuerAuthorityEventRequest; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical file-backed workload mTLS transport proof against an issuer-owner transport double. */ +class AccountIssuerAuthoritySourceClientMtlsTest { + private static final String NAMESPACE = "firemud"; + private static final String CALLER = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void revalidatesSequenceZeroAndPositiveSourcesExactlyOverFileBackedMtls(@TempDir Path directory) + throws Exception { + var clientTls = writeClientTlsMaterial(directory); + var serverTls = writeServerTlsMaterial(directory, ServerIdentity.ACCOUNT); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + + UUID zeroOperation = UUID.randomUUID(); + var initialZero = client.read(request(zeroOperation, Optional.empty())); + assertThat(initialZero.lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(initialZero.sourceEvent()).isEmpty(); + assertThat(client.read(request(zeroOperation, Optional.of(initialZero)))) + .isEqualTo(initialZero); + + UUID positiveOperation = UUID.randomUUID(); + var positive = source(positiveOperation, "1", "2"); + owner.setCurrentSource(positive); + assertThat(client.read(request(positiveOperation, Optional.of(positive)))) + .isEqualTo(positive); + assertThat(positive.sourceEvent()).isPresent(); + + assertThat(owner.observation.metadataCount()).isEqualTo(3); + assertThat(owner.observation.messageCount()).isEqualTo(3); + assertThat(owner.ownerReadCount()).isEqualTo(3); + } + } + + @Test + void rejectsBadUnknownAndChangedSourceResponsesFailClosed(@TempDir Path directory) + throws Exception { + var clientTls = writeClientTlsMaterial(directory); + var serverTls = writeServerTlsMaterial(directory, ServerIdentity.ACCOUNT); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + UUID operation = UUID.randomUUID(); + var expected = source(operation, "1", "2"); + owner.setCurrentSource(expected); + + owner.setResponseMode(ResponseMode.MISSING_FIELDS); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class); + + owner.setResponseMode(ResponseMode.UNKNOWN_FIELD); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + owner.setResponseMode(ResponseMode.CHANGED_SOURCE); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + + assertThat(owner.observation.metadataCount()).isEqualTo(3); + assertThat(owner.observation.messageCount()).isEqualTo(3); + assertThat(owner.ownerReadCount()).isEqualTo(3); + } + } + + @Test + void readsExactRetainedEventOverFileBackedMtlsAndRejectsSubstitution(@TempDir Path directory) + throws Exception { + var clientTls = writeClientTlsMaterial(directory); + var serverTls = writeServerTlsMaterial(directory, ServerIdentity.ACCOUNT); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + UUID operation = UUID.randomUUID(); + var historical = source(UUID.randomUUID(), "1", "2"); + var event = + (IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify(historical.sourceEvent().orElseThrow()); + var request = + new ExactEventRequest( + request(operation, Optional.empty()), 1L, event.eventId(), event.eventDigest()); + var current = source(operation, "2", "3"); + owner.setCurrentSource(current); + owner.setSelectedEvent(event); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + + var captured = client.readExactEvent(request); + assertThat(captured.currentSnapshot()).isEqualTo(current); + assertThat(captured.selectedEvent()).isEqualTo(event); + + owner.setResponseMode(ResponseMode.CHANGED_SOURCE); + assertThatThrownBy(() -> client.readExactEvent(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected issuer event"); + + assertThat(owner.observation.metadataCount()).isEqualTo(2); + assertThat(owner.observation.messageCount()).isEqualTo(2); + assertThat(owner.ownerReadCount()).isEqualTo(2); + } + } + + @Test + void wrongAccountServiceOrNamespacePeerIsRejectedBeforeAnyRpcMetadataOrOwnerRead( + @TempDir Path directory) throws Exception { + var clientTls = writeClientTlsMaterial(directory); + for (ServerIdentity identity : + new ServerIdentity[] {ServerIdentity.WRONG_SERVICE, ServerIdentity.WRONG_NAMESPACE}) { + Path serverDirectory = Files.createDirectories(directory.resolve(identity.name())); + var serverTls = writeServerTlsMaterial(serverDirectory, identity); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + UUID operation = UUID.randomUUID(); + assertThatThrownBy(() -> client.read(request(operation, Optional.empty()))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + var exact = + new ExactEventRequest( + request(operation, Optional.empty()), + 1L, + "retained-event", + "sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> client.readExactEvent(exact)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + assertThat(owner.observation.metadataCount()).isZero(); + assertThat(owner.observation.messageCount()).isZero(); + assertThat(owner.ownerReadCount()).isZero(); + } + } + } + + static ClientTlsMaterial writeClientTlsMaterial(Path directory) throws IOException { + return writeClientTlsMaterial(directory, false); + } + + static ClientTlsMaterial writeClientTlsMaterial(Path directory, boolean wrongIdentity) + throws IOException { + Files.createDirectories(directory); + Path ca = write(directory.resolve("test-ca.pem"), TEST_CA); + Path clientCertificate = + write( + directory.resolve("client.crt"), + wrongIdentity ? WRONG_NAMESPACE_SERVER_CERTIFICATE : CLIENT_CERTIFICATE); + Path clientPrivateKey = write(directory.resolve("client.key"), CLIENT_PRIVATE_KEY); + return new ClientTlsMaterial(ca, clientCertificate, clientPrivateKey); + } + + private static ServerTlsMaterial writeServerTlsMaterial(Path directory, ServerIdentity identity) + throws IOException { + Files.createDirectories(directory); + Path ca = write(directory.resolve("test-ca.pem"), TEST_CA); + return switch (identity) { + case ACCOUNT -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), ACCOUNT_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), ACCOUNT_SERVER_PRIVATE_KEY)); + case WRONG_SERVICE -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), WRONG_SERVICE_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), WRONG_SERVICE_SERVER_PRIVATE_KEY)); + case WRONG_NAMESPACE -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), WRONG_NAMESPACE_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), WRONG_NAMESPACE_SERVER_PRIVATE_KEY)); + }; + } + + private static TransportServer startServer( + ServerTlsMaterial serverTls, Path trustedClientCa, IssuerOwnerTransportDouble owner) + throws Exception { + var sslContext = + GrpcSslContexts.forServer( + serverTls.serverCertificate().toFile(), serverTls.serverPrivateKey().toFile()) + .trustManager(trustedClientCa.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + Server server = + NettyServerBuilder.forPort(0) + .sslContext(sslContext) + .addService( + ServerInterceptors.intercept( + owner, owner.observation, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server); + } + + private static AccountIssuerAuthoritySourceClient newClient( + int port, ClientTlsMaterial tlsMaterial) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(tlsMaterial.clientCertificate().toString()); + tls.setPrivateKey(tlsMaterial.clientPrivateKey().toString()); + tls.setCaCert(tlsMaterial.caCertificate().toString()); + return new AccountIssuerAuthoritySourceClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence source( + UUID operation, String sequence, String generation) { + Optional event = Optional.empty(); + if (!"0".equals(sequence)) { + event = + Optional.of( + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + operation.toString(), + operation.toString(), + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson()); + } + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, generation, STREAM, sequence, event); + } + + private static Path write(Path path, String contents) throws IOException { + return Files.writeString(path, contents); + } + + record ClientTlsMaterial(Path caCertificate, Path clientCertificate, Path clientPrivateKey) {} + + private record ServerTlsMaterial( + Path caCertificate, Path serverCertificate, Path serverPrivateKey) {} + + private record TransportServer(Server server) implements AutoCloseable { + int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow().awaitTermination(); + } + } + + private enum ServerIdentity { + ACCOUNT, + WRONG_SERVICE, + WRONG_NAMESPACE + } + + private enum ResponseMode { + CURRENT, + MISSING_FIELDS, + UNKNOWN_FIELD, + CHANGED_SOURCE + } + + private static final class TransportObservation implements ServerInterceptor { + private final AtomicInteger metadataCount = new AtomicInteger(); + private final AtomicInteger messageCount = new AtomicInteger(); + + @Override + public io.grpc.ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + metadataCount.incrementAndGet(); + return new SimpleForwardingServerCallListener<>(next.startCall(call, headers)) { + @Override + public void onMessage(RequestT message) { + messageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + int metadataCount() { + return metadataCount.get(); + } + + int messageCount() { + return messageCount.get(); + } + } + + /** Synthetic owner transport fixture; it does not execute or claim Account database semantics. */ + private static final class IssuerOwnerTransportDouble + extends AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceImplBase { + private final TransportObservation observation = new TransportObservation(); + private final AtomicInteger ownerReadCount = new AtomicInteger(); + private volatile AccountIssuerSourceSnapshotEvidence currentSource; + private volatile IssuerEvent selectedEvent; + private volatile ResponseMode responseMode = ResponseMode.CURRENT; + + @Override + public void readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest request, + StreamObserver responseObserver) { + ownerReadCount.incrementAndGet(); + try { + GrpcPeerIdentity caller = GrpcPeerIdentity.current(); + if (caller == null || !CALLER.equals(caller.uri())) { + responseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(request, NAMESPACE, caller.uri()); + AccountIssuerSourceSnapshotEvidence responseSource = currentSource; + if (responseSource == null && parsedRequest.expectedSource().isPresent()) { + responseSource = parsedRequest.expectedSource().orElseThrow(); + } + if (responseSource == null) { + responseSource = source(parsedRequest.reconciliationOperationId(), "0", "1"); + currentSource = responseSource; + } + + AccountIssuerAuthoritySourceSnapshot wireResponse; + switch (responseMode) { + case MISSING_FIELDS -> + wireResponse = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .build(); + case UNKNOWN_FIELD -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire(responseSource).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + case CHANGED_SOURCE -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire( + source(parsedRequest.reconciliationOperationId(), "2", "3")); + case CURRENT -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toResponse( + responseSource, parsedRequest, caller.uri()); + default -> throw new IllegalStateException("unsupported transport-double response mode"); + } + responseObserver.onNext(wireResponse); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onError(Status.INVALID_ARGUMENT.withCause(failure).asRuntimeException()); + } + } + + @Override + public void readExactIssuerAuthorityEvent( + ReadExactIssuerAuthorityEventRequest request, + StreamObserver responseObserver) { + ownerReadCount.incrementAndGet(); + GrpcPeerIdentity caller = GrpcPeerIdentity.current(); + if (caller == null || !CALLER.equals(caller.uri())) { + responseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + try { + var parsed = + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest( + request, NAMESPACE, caller.uri()); + var current = currentSource; + var response = + AccountIssuerSourceSnapshotGrpcCodec.toExactEventResponse( + current, selectedEvent, parsed, caller.uri()); + if (responseMode == ResponseMode.CHANGED_SOURCE) { + response = + response.toBuilder() + .setSelectedEvent(ByteString.copyFromUtf8(current.sourceEvent().orElseThrow())) + .build(); + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onError(Status.INVALID_ARGUMENT.withCause(failure).asRuntimeException()); + } + } + + void setSelectedEvent(IssuerEvent event) { + selectedEvent = event; + } + + int ownerReadCount() { + return ownerReadCount.get(); + } + + void setCurrentSource(AccountIssuerSourceSnapshotEvidence source) { + currentSource = source; + } + + void setResponseMode(ResponseMode mode) { + responseMode = mode; + } + } + + private static final String TEST_CA = + """ + -----BEGIN CERTIFICATE----- + MIIBtTCCAVugAwIBAgIUEVP0Q8L5Ora/p1kDdJlLB272mNMwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAoMSYwJAYDVQQDDB1GaXJlTVVEIGlz + c3Vlci1zb3VyY2UgdGVzdCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAqz + jOqtLuabC4VgS1wSj+BNxfFj5P4sPKJ0JxVw1k0rg2DJlGmCLPPU0cq8ow7DgtU0 + Gmi2BoLCuMOWlW719S+jYzBhMB8GA1UdIwQYMBaAFDcLkswEeTQ+ubifCjqS//hA + nQAAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQ3 + C5LMBHk0Prm4nwo6kv/4QJ0AADAKBggqhkjOPQQDAgNIADBFAiEA+sYWAP6HFISr + qGcbHAXzA9SgrH7nHWVwRX2vgRoA7DMCICnfSOJCWGedTmGbaT2m8xjpDMlgvnrL + Vwi8c/15tJei + -----END CERTIFICATE----- + """; + + private static final String CLIENT_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICBTCCAaugAwIBAgIUIbUYSjzVvJpHUY1Y0zoWfQiI9SIwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAkMSIwIAYDVQQDDBlmaXJlbXVkIGdh + bWUtc2Vzc2lvbiB0ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE95+zYl2Q + C1ply40Sa76hBaIBQ3xGRydNUbOq0aie9RWWlhe7Hdfj1jiWa+TfMvDo4g49tOxb + re8OlicZ4c2QXqOBtjCBszAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIHgDAT + BgNVHSUEDDAKBggrBgEFBQcDAjA+BgNVHREENzA1hjNzcGlmZmU6Ly9maXJlbXVk + L25zL2ZpcmVtdWQvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UwHQYDVR0OBBYEFF+C + ZbOODKc5aG50EuJcDYrMvqG4MB8GA1UdIwQYMBaAFDcLkswEeTQ+ubifCjqS//hA + nQAAMAoGCCqGSM49BAMCA0gAMEUCIQCpKhU72Vr+0J/ecKtssCdwL7ZpW/7/tEKu + TqBG3a212gIgZ/d+bD5cEXnHH2s9FiHtthuiJ5TG/M82vsmhLWUWD+I= + -----END CERTIFICATE----- + """; + + private static final String CLIENT_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL7a8bTP2x/haYtxx + ZmHwnXgNeLo+ok4/oOTcChj5IByhRANCAAT3n7NiXZALWmXLjRJrvqEFogFDfEZH + J01Rs6rRqJ71FZaWF7sd1+PWOJZr5N8y8OjiDj207Fut7w6WJxnhzZBe + -----END PRIVATE KEY----- + """; + + private static final String ACCOUNT_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICBzCCAaygAwIBAgIUM7M4f8TIsmepkFGPEGvzno7AhlAwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAfMR0wGwYDVQQDDBRmaXJlbXVkIGFj + Y291bnQgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJYzdFJrNpJomn8o + vTyLc+w0O6x9ZJH0Ve7DqrpL4151fWjv+QSyunwogecWWDtXyBJg0t1+E1izowFO + Dm/NxKCjgbwwgbkwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0l + BAwwCgYIKwYBBQUHAwEwRAYDVR0RBD0wO4IJbG9jYWxob3N0hi5zcGlmZmU6Ly9m + aXJlbXVkL25zL2ZpcmVtdWQvc2EvYWNjb3VudC1zZXJ2aWNlMB0GA1UdDgQWBBRP + u+0KoAlDJBd9BZIcftifunH/nDAfBgNVHSMEGDAWgBQ3C5LMBHk0Prm4nwo6kv/4 + QJ0AADAKBggqhkjOPQQDAgNJADBGAiEArSG4oVkjw24XI04ckfdefWeX0FAbo4n5 + uKAGNu+vJjYCIQDO0K7fzv/sD76KIAe6lCjO7uWIMqrXgYcxKM87WtZZwA== + -----END CERTIFICATE----- + """; + + private static final String ACCOUNT_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgsF8YPfzEzsLMcFwK + jDNpeuA/UYR01ZJJHggn1GuDGRShRANCAASWM3RSazaSaJp/KL08i3PsNDusfWSR + 9FXuw6q6S+NedX1o7/kEsrp8KIHnFlg7V8gSYNLdfhNYs6MBTg5vzcSg + -----END PRIVATE KEY----- + """; + + private static final String WRONG_SERVICE_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICEDCCAbagAwIBAgIUUoUlbNguY4u1g9cd3CTkLx1ph14wCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAlMSMwIQYDVQQDDBpmaXJlbXVkIHdy + b25nIHNlcnZpY2UgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIfFrRHj + wS3v8/1NseHlHaVgUYBr+qPVgvCNTgOigjT/S/zQ7ObTK0QgjJQkm6qhWhtNNWVb + ViPeGKieLlncC02jgcAwgb0wDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4Aw + EwYDVR0lBAwwCgYIKwYBBQUHAwEwSAYDVR0RBEEwP4IJbG9jYWxob3N0hjJzcGlm + ZmU6Ly9maXJlbXVkL25zL2ZpcmVtdWQvc2EvZ2FtZS1kZXNpZ24tc2VydmljZTAd + BgNVHQ4EFgQUAqO+RBJqRVOb8ivvTyWWpWp5QK0wHwYDVR0jBBgwFoAUNwuSzAR5 + ND65uJ8KOpL/+ECdAAAwCgYIKoZIzj0EAwIDSAAwRQIhAIgMjCy7nTnqcGBNexw4 + hKCu4IvM6sYc/yRmzcQ/pq2GAiBQJZOUStWnGJKz35ODoZHndOCSGE3J/ZMehFrW + 3EF8Rg== + -----END CERTIFICATE----- + """; + + private static final String WRONG_SERVICE_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU/N/DJ4u72eEVy6M + lBc2ZZoa0id2EkrAXbEIzsbjDYKhRANCAASHxa0R48Et7/P9TbHh5R2lYFGAa/qj + 1YLwjU4DooI0/0v80Ozm0ytEIIyUJJuqoVobTTVlW1Yj3hioni5Z3AtN + -----END PRIVATE KEY----- + """; + + private static final String WRONG_NAMESPACE_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICDTCCAbKgAwIBAgIUTXRuwVMIcnUSv5EIbCG1IIInpocwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAnMSUwIwYDVQQDDBxmaXJlbXVkIHdy + b25nIG5hbWVzcGFjZSB0ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqnH+ + OVHMgjnsqHMj2JcGkztSnOzCGrRdMgmqPjQoU6aQKQ6kW6g9QIf+IRuypZqP5gWu + 7P2lpxEiSSwo0tRulKOBujCBtzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIH + gDATBgNVHSUEDDAKBggrBgEFBQcDATBCBgNVHREEOzA5gglsb2NhbGhvc3SGLHNw + aWZmZTovL2ZpcmVtdWQvbnMvb3RoZXIvc2EvYWNjb3VudC1zZXJ2aWNlMB0GA1Ud + DgQWBBTQ0iPp7mEFoUWE6jUas8gHr/t6KjAfBgNVHSMEGDAWgBQ3C5LMBHk0Prm4 + nwo6kv/4QJ0AADAKBggqhkjOPQQDAgNJADBGAiEAnmXME6WMdN0ORDptJ0FE1uTM + Muuiz2Z7DbIBd3YihwgCIQCtEaz1wc3t/ecLLNlgy6311eXLc+XTM1ijnLhxFClj + iA== + -----END CERTIFICATE----- + """; + + private static final String WRONG_NAMESPACE_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg92jz3gfsT5pGQ8+z + Iqw5o8rUe1CwrS3rOs/aEDdK9RShRANCAASqcf45UcyCOeyocyPYlwaTO1Kc7MIa + tF0yCao+NChTppApDqRbqD1Ah/4hG7Klmo/mBa7s/aWnESJJLCjS1G6U + -----END PRIVATE KEY----- + """; +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java new file mode 100644 index 0000000000..84daf39b05 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java @@ -0,0 +1,204 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerAuthoritySourceClientTest { + private static final String NAMESPACE = "firemud"; + private static final String CALLER = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void rejectsInvalidNamespaceAndUninitializedOrClosedLifecycle(@TempDir Path directory) + throws Exception { + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + CommonGrpcClientProperties tls = tlsProperties(material); + assertThatThrownBy(() -> newClient("FireMUD", tls)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + + AccountIssuerAuthoritySourceClient client = newClient(NAMESPACE, tls); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + client.close(); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + } + + @Test + void requiresReadableFileBackedMutualTlsAndExactClientLeafIdentity(@TempDir Path directory) + throws Exception { + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(NAMESPACE, plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires TLS with file-backed client mTLS"); + + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + CommonGrpcClientProperties missingKey = tlsProperties(material); + missingKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy(() -> newClient(NAMESPACE, missingKey)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("privateKey must be a readable regular file"); + + var wrongMaterial = + AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial( + directory.resolve("wrong-identity"), true); + AccountIssuerAuthoritySourceClient wrongIdentityClient = + newClient(NAMESPACE, tlsProperties(wrongMaterial)); + assertThatThrownBy(wrongIdentityClient::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must match the configured Game Session workload"); + } + + @Test + void rejectsAmbientTransactionsAndNamespaceMismatchedRequestsBeforeRpc(@TempDir Path directory) + throws Exception { + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + AccountIssuerAuthoritySourceClient client = newClient(NAMESPACE, tlsProperties(material)); + client.init(); + try { + var request = request(UUID.randomUUID(), Optional.empty(), "other"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request(UUID.randomUUID(), Optional.empty(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request(UUID.randomUUID(), Optional.empty(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + client.close(); + } + } + + @Test + void rejectsMalformedUnknownAndChangedSourceResponses() { + UUID operation = UUID.randomUUID(); + var captured = positiveSource(operation, "1", "2"); + var request = request(operation, Optional.of(captured), NAMESPACE); + + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse( + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .build(), + request, + CALLER)) + .isInstanceOf(IllegalArgumentException.class); + + var unknownResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire(captured).toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse(unknownResponse, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var changedSource = positiveSource(operation, "2", "3"); + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedSource), request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + } + + private static AccountIssuerAuthoritySourceClient newClient( + String namespace, CommonGrpcClientProperties tlsProperties) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + ManagedChannel channel = mock(ManagedChannel.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + try { + when(channelFactory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(channel); + } catch (javax.net.ssl.SSLException impossible) { + throw new AssertionError(impossible); + } + return new AccountIssuerAuthoritySourceClient( + endpoints, tlsProperties, channelFactory, namespace); + } + + private static CommonGrpcClientProperties tlsProperties( + AccountIssuerAuthoritySourceClientMtlsTest.ClientTlsMaterial material) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(material.clientCertificate().toString()); + properties.setPrivateKey(material.clientPrivateKey().toString()); + properties.setCaCert(material.caCertificate().toString()); + return properties; + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected, String namespace) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, namespace, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence positiveSource( + UUID operation, String sequence, String generation) { + String event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + operation.toString(), + operation.toString(), + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + return new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + CALLER, + ISSUER, + generation, + generation, + STREAM, + sequence, + Optional.of(event)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java new file mode 100644 index 0000000000..9ccbf7b9e7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountIssuerSourceSnapshotEvidenceTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void sequenceZeroIsTheOriginalEnrollmentAndHasNoInventedEvent() { + var initial = snapshot(UUID.randomUUID(), "1", "1", "0", Optional.empty()); + + assertThat(initial.sourceEvent()).isEmpty(); + assertThat(initial.sourceEventBytes()).isEmpty(); + assertThatThrownBy( + () -> + snapshot( + initial.reconciliationOperationId(), + "1", + "1", + "0", + event(initial.reconciliationOperationId(), "1", "2"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence-zero"); + assertThatThrownBy( + () -> snapshot(initial.reconciliationOperationId(), "2", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence-zero"); + assertThatThrownBy( + () -> snapshot(initial.reconciliationOperationId(), "2", "2", "1", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires sourceEvent"); + } + + @Test + void positiveCheckpointRequiresTheExactClosedIssuerEventAndRetainsItsBytes() { + UUID operation = UUID.randomUUID(); + String wireEvent = sealedIssuerEvent(operation, "1", "2"); + var evidence = snapshot(operation, "2", "2", "1", Optional.of(wireEvent)); + + assertThat(evidence.sourceEvent()).contains(wireEvent); + byte[] first = evidence.sourceEventBytes().orElseThrow(); + first[0] = 0; + assertThat(evidence.sourceEventBytes().orElseThrow()) + .isEqualTo(wireEvent.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(AccountAuthoritySourceEventV1Codec.verify(evidence.sourceEvent().orElseThrow())) + .isInstanceOf(AccountAuthoritySourceEventV1Codec.IssuerEvent.class); + } + + @Test + void acceptsHistoricalEventIdentityIndependentFromReconciliationOperation() { + UUID operation = UUID.randomUUID(); + String historicalEventId = "retained-source-event-17"; + String wireEvent = sealedIssuerEvent(historicalEventId, historicalEventId, "1", "2"); + + var evidence = snapshot(operation, "2", "2", "1", Optional.of(wireEvent)); + + assertThat(evidence.reconciliationOperationId().toString()).isNotEqualTo(historicalEventId); + var issuerEvent = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify(evidence.sourceEvent().orElseThrow()); + assertThat(issuerEvent.eventId()).isEqualTo(historicalEventId); + assertThat(issuerEvent.requestId()).isEqualTo(historicalEventId); + } + + @Test + void rejectsEventIdentityIssuerCheckpointAndSchemaDrift() { + UUID operation = UUID.randomUUID(); + String mismatchedEventIdentity = + sealedIssuerEvent("retained-source-event-17", "different-request-17", "1", "2"); + String wrongCheckpointEvent = sealedIssuerEvent(operation, "2", "3"); + String accountEvent = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountAuthoritySourceEventV1Codec.AccountPreimage( + operation.toString(), + operation.toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + "11111111-1111-4111-8111-111111111111", + "1", + "11111111-1111-4111-8111-111111111111", + "2", + "2", + "2", + "2", + java.util.List.of("PASSWORD_RESET"), + new AccountAuthoritySourceEventV1Codec.AccountState( + true, java.util.List.of("PASSWORD"), "player", "ACTIVE"))) + .canonicalJson(); + + assertThatThrownBy( + () -> snapshot(operation, "2", "2", "1", Optional.of(mismatchedEventIdentity))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventId must equal requestId"); + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(wrongCheckpointEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly match"); + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(accountEvent))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNoncanonicalDuplicateUnknownAndTrailingEventFields() { + UUID operation = UUID.randomUUID(); + String canonical = sealedIssuerEvent(operation, "1", "2"); + String unknown = canonical.substring(0, canonical.length() - 1) + ",\"z\":true}"; + String duplicate = canonical.replaceFirst("\\{", "{\"eventId\":\"duplicate\","); + String noncanonical = " " + canonical; + String trailing = canonical + " {}"; + + for (String malformed : java.util.List.of(unknown, duplicate, noncanonical, trailing)) { + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(malformed))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(noncanonical))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire JSON is not the exact canonical encoding"); + } + + @Test + void comparesLargeCanonicalCountersWithoutFloatingPointOrLongCoercion() { + UUID operation = UUID.randomUUID(); + String sequence = "9007199254740992"; + String generation = new BigInteger(sequence).add(BigInteger.ONE).toString(); + String wireEvent = sealedIssuerEvent(operation, sequence, generation); + + var evidence = snapshot(operation, generation, generation, sequence, Optional.of(wireEvent)); + + assertThat(evidence.lastCommittedOutboxSequence()).isEqualTo("9007199254740992"); + assertThat(evidence.issuerAuthGeneration()).isEqualTo("9007199254740993"); + } + + @Test + void rejectsNoncanonicalCountersWrongCallerNamespaceIssuerAndNilOperation() { + UUID operation = UUID.randomUUID(); + assertThatThrownBy(() -> snapshot(operation, "01", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy(() -> snapshot(operation, "1", "1", "00", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy( + () -> + new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + "spiffe://firemud/ns/other/sa/game-session-service", + ISSUER, + "1", + "1", + STREAM, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + CALLER, + "other-issuer", + "1", + "1", + STREAM, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported Account issuer"); + assertThatThrownBy(() -> snapshot(new UUID(0L, 0L), "1", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil"); + } + + private static AccountIssuerSourceSnapshotEvidence snapshot( + UUID operation, String generation, String version, String sequence, Optional event) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, version, STREAM, sequence, event); + } + + private static Optional event(UUID operation, String sequence, String generation) { + return Optional.of(sealedIssuerEvent(operation, sequence, generation)); + } + + private static String sealedIssuerEvent(UUID operation, String sequence, String generation) { + return sealedIssuerEvent(operation.toString(), operation.toString(), sequence, generation); + } + + private static String sealedIssuerEvent( + String eventId, String requestId, String sequence, String generation) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, + requestId, + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java new file mode 100644 index 0000000000..c3b2a32214 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java @@ -0,0 +1,424 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.math.BigInteger; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ExactEventRequest; +import org.junit.jupiter.api.Test; + +class AccountIssuerSourceSnapshotGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void initialRequestAndZeroCheckpointResponseRoundTripWithoutEventPresence() { + UUID operation = UUID.randomUUID(); + var request = request(operation, Optional.empty()); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(wireRequest, NAMESPACE, CALLER); + var source = snapshot(operation, "1", "1", "0", Optional.empty()); + var wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toResponse(source, parsedRequest, CALLER); + var parsedResponse = + AccountIssuerSourceSnapshotGrpcCodec.fromResponse(wireResponse, parsedRequest, CALLER); + + assertThat(parsedRequest).isEqualTo(request); + assertThat(wireResponse.hasSourceEvent()).isFalse(); + assertThat(parsedResponse).isEqualTo(source); + } + + @Test + void expectedSourceRevalidationAcceptsOnlyTheWholeExactCarrier() { + UUID operation = UUID.randomUUID(); + var captured = advanced(operation, "1", "2"); + var request = request(operation, Optional.of(captured)); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(wireRequest, NAMESPACE, CALLER); + + assertThat(parsedRequest.expectedSource()).contains(captured); + assertThat( + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toResponse(captured, parsedRequest, CALLER), + parsedRequest, + CALLER)) + .isEqualTo(captured); + + var changedCheckpoint = advanced(operation, "2", "3"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedCheckpoint), + parsedRequest, + CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + + var changedEvent = + snapshot( + operation, + "2", + "2", + "1", + Optional.of( + sealedIssuerEvent( + "different-retained-event", "different-retained-event", "1", "2"))); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedEvent), + parsedRequest, + CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + } + + @Test + void rejectsOperationCallerNamespaceAndExpectedSnapshotScopeChanges() { + UUID operation = UUID.randomUUID(); + var initial = snapshot(operation, "1", "1", "0", Optional.empty()); + var request = request(operation, Optional.empty()); + var otherOperation = request(UUID.randomUUID(), Optional.empty()); + var wireInitial = AccountIssuerSourceSnapshotGrpcCodec.toWire(initial); + + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireInitial, otherOperation, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the request scope"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireInitial, request, "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.toRequest( + request, "other", "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + assertThatThrownBy( + () -> + request( + operation, + Optional.of(snapshot(UUID.randomUUID(), "1", "1", "0", Optional.empty())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the request scope"); + } + + @Test + void rejectsUnknownFieldsAtRequestSnapshotAndNestedExpectedSnapshotBoundaries() { + UUID operation = UUID.randomUUID(); + var request = request(operation, Optional.empty()); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var unknownRequest = wireRequest.toBuilder().setUnknownFields(oneUnknownField()).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(unknownRequest, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var source = snapshot(operation, "1", "1", "0", Optional.empty()); + var wireSource = AccountIssuerSourceSnapshotGrpcCodec.toWire(source); + var unknownSnapshot = wireSource.toBuilder().setUnknownFields(oneUnknownField()).build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(unknownSnapshot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var expectedRequest = request(operation, Optional.of(source)); + var nestedUnknown = wireSource.toBuilder().setUnknownFields(oneUnknownField()).build(); + var outerWithNestedUnknown = + AccountIssuerSourceSnapshotGrpcCodec.toRequest(expectedRequest, NAMESPACE, CALLER) + .toBuilder() + .setExpectedSource(nestedUnknown) + .build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromRequest( + outerWithNestedUnknown, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + } + + @Test + void rejectsMalformedUtf8UnknownEventFieldsAndOversizedSourcePayload() { + UUID operation = UUID.randomUUID(); + var malformedUtf8 = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed UTF-8"); + + String event = sealedIssuerEvent(operation, "1", "2"); + String unknownJson = event.substring(0, event.length() - 1) + ",\"z\":true}"; + var unknownEvent = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFromUtf8(unknownJson)) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(unknownEvent)) + .isInstanceOf(IllegalArgumentException.class); + + var oversized = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFrom(new byte[64 * 1024 + 1])) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("64 KiB"); + } + + @Test + void roundTripsLargeCountersAsExactDecimalStrings() { + UUID operation = UUID.randomUUID(); + String sequence = "9007199254740992"; + String generation = new BigInteger(sequence).add(BigInteger.ONE).toString(); + var source = advanced(operation, sequence, generation); + + assertThat( + AccountIssuerSourceSnapshotGrpcCodec.fromWire( + AccountIssuerSourceSnapshotGrpcCodec.toWire(source))) + .isEqualTo(source); + } + + @Test + void rejectsAbsentOrChangedSourceOnPositiveSequenceAndCounterDrift() { + UUID operation = UUID.randomUUID(); + var valid = advanced(operation, "1", "2"); + var absent = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCallerWorkload(CALLER) + .setReconciliationOperationId(operation.toString()) + .setIssuerId(ISSUER) + .setIssuerAuthGeneration("2") + .setSourceVersion("2") + .setOutboxStreamKey(STREAM) + .setLastCommittedOutboxSequence("1") + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(absent)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires sourceEvent"); + + var wrongSequence = + AccountIssuerSourceSnapshotGrpcCodec.toWire(valid).toBuilder() + .setLastCommittedOutboxSequence("2") + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(wrongSequence)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactReadPreservesHistoricalEventWhenCurrentCheckpointAdvances() { + UUID operation = UUID.randomUUID(); + var selected = selectedEvent("retained-event", "1", "2"); + var request = exactRequest(operation, selected); + var wire = AccountIssuerSourceSnapshotGrpcCodec.toExactEventRequest(request, NAMESPACE, CALLER); + assertThat(AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest(wire, NAMESPACE, CALLER)) + .isEqualTo(request); + var original = snapshot(operation, "2", "2", "1", Optional.of(selected.canonicalJson())); + var advanced = advanced(operation, "2", "3"); + for (var current : List.of(original, advanced)) { + var response = + AccountIssuerSourceSnapshotGrpcCodec.toExactEventResponse( + current, selected, request, CALLER); + assertThat(response.getSelectedEvent()) + .isEqualTo(ByteString.copyFromUtf8(selected.canonicalJson())); + var decoded = + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse(response, request, CALLER); + assertThat(decoded.currentSnapshot()).isEqualTo(current); + assertThat(decoded.selectedEvent()).isEqualTo(selected); + } + } + + @Test + void exactReadRejectsNoncanonicalSelectorsAndAcceptsLargestOwnerSequence() { + UUID operation = UUID.randomUUID(); + var selected = selectedEvent("retained-event", "1", "2"); + var request = exactRequest(operation, selected); + var wire = AccountIssuerSourceSnapshotGrpcCodec.toExactEventRequest(request, NAMESPACE, CALLER); + for (String sequence : + List.of("0", "01", "+1", "-1", "1 ", "9223372036854775807", "9223372036854775808")) { + var malformed = wire.toBuilder().setOutboxSequence(sequence).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest( + malformed, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class); + } + var largest = wire.toBuilder().setOutboxSequence(Long.toString(Long.MAX_VALUE - 1L)).build(); + assertThat( + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest(largest, NAMESPACE, CALLER) + .outboxSequence()) + .isEqualTo(Long.MAX_VALUE - 1L); + + for (var malformed : + List.of( + wire.toBuilder().setExpectedEventId("retained-event ").build(), + wire.toBuilder().setExpectedEventId("a".repeat(513)).build(), + wire.toBuilder().setExpectedEventDigest("sha256:" + "A".repeat(64)).build(), + wire.toBuilder().setExpectedEventDigest("sha256:" + "a".repeat(63)).build(), + wire.toBuilder().setUnknownFields(oneUnknownField()).build())) { + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventRequest( + malformed, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class); + } + var scopeWithExpected = request(operation, Optional.of(advanced(operation, "1", "2"))); + assertThatThrownBy( + () -> + new ExactEventRequest( + scopeWithExpected, 1L, selected.eventId(), selected.eventDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot carry an expected snapshot"); + } + + @Test + void exactReadRejectsMalformedOrSubstitutedSelectedEvidenceAndCurrentSnapshot() { + UUID operation = UUID.randomUUID(); + var selected = selectedEvent("retained-event", "1", "2"); + var request = exactRequest(operation, selected); + var current = advanced(operation, "2", "3"); + var response = + AccountIssuerSourceSnapshotGrpcCodec.toExactEventResponse( + current, selected, request, CALLER); + var alternateHead = advanced(operation, "1", "2"); + var baseline = snapshot(operation, "1", "1", "0", Optional.empty()); + var otherScope = advanced(UUID.randomUUID(), "2", "3"); + var unknownSnapshot = + response.getCurrentSnapshot().toBuilder().setUnknownFields(oneUnknownField()).build(); + for (var invalidCurrent : + List.of( + unknownSnapshot, + AccountIssuerSourceSnapshotGrpcCodec.toWire(otherScope), + AccountIssuerSourceSnapshotGrpcCodec.toWire(baseline), + AccountIssuerSourceSnapshotGrpcCodec.toWire(alternateHead))) { + var malformed = response.toBuilder().setCurrentSnapshot(invalidCurrent).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + malformed, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class); + } + + for (var invalidEvent : + List.of( + ByteString.EMPTY, + ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28}), + ByteString.copyFrom(new byte[64 * 1024 + 1]), + ByteString.copyFromUtf8(" " + selected.canonicalJson()), + ByteString.copyFromUtf8(sealedIssuerEvent("replacement", "replacement", "1", "2")), + ByteString.copyFromUtf8( + sealedIssuerEvent("retained-event", "retained-event", "2", "3")))) { + var malformed = response.toBuilder().setSelectedEvent(invalidEvent).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + malformed, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class); + } + + var missingCurrent = response.toBuilder().clearCurrentSnapshot().build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + missingCurrent, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("currentSnapshot"); + var unknown = response.toBuilder().setUnknownFields(oneUnknownField()).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + unknown, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + var wrongDigest = + new ExactEventRequest(request.scope(), 1L, selected.eventId(), "sha256:" + "0".repeat(64)); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromExactEventResponse( + response, wrongDigest, CALLER)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static ExactEventRequest exactRequest(UUID operation, IssuerEvent selected) { + return new ExactEventRequest( + request(operation, Optional.empty()), + Long.parseLong(selected.outboxSequence()), + selected.eventId(), + selected.eventDigest()); + } + + private static IssuerEvent selectedEvent(String eventId, String sequence, String generation) { + return (IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify( + sealedIssuerEvent(eventId, eventId, sequence, generation)); + } + + private static UnknownFieldSet oneUnknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence snapshot( + UUID operation, String generation, String version, String sequence, Optional event) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, version, STREAM, sequence, event); + } + + private static AccountIssuerSourceSnapshotEvidence advanced( + UUID operation, String sequence, String generation) { + return snapshot( + operation, + generation, + generation, + sequence, + Optional.of(sealedIssuerEvent(operation, sequence, generation))); + } + + private static AccountIssuerAuthoritySourceSnapshot advancedWire(UUID operation) { + return AccountIssuerSourceSnapshotGrpcCodec.toWire(advanced(operation, "1", "2")); + } + + private static String sealedIssuerEvent(UUID operation, String sequence, String generation) { + return sealedIssuerEvent(operation.toString(), operation.toString(), sequence, generation); + } + + private static String sealedIssuerEvent( + String eventId, String requestId, String sequence, String generation) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, + requestId, + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java index 17584d3171..219f07ef18 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -818,8 +818,8 @@ public record AccountAuthoritySnapshot( || issuanceFenceSourceVersion <= 0L || issuerGeneration != issuerSourceVersion || accountGeneration != accountSourceVersion - || accountGeneration != issuanceFence - || accountGeneration != issuanceFenceSourceVersion) { + || accountGeneration > issuanceFence + || issuanceFence != issuanceFenceSourceVersion) { throw invalid("Durable Account authority snapshot is malformed"); } String expectedStream = "account:auth-authority:v1:account/" + accountId; diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java index 075f9731d5..c6c4b2095f 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java @@ -98,6 +98,68 @@ void buildsStrictPendingRecordForTheMinimalCredentialLoginProfile() throws Excep .containsEntry("tokenHash", sha256(compact)); } + @Test + void roundTripsMembershipAdvancedCompositeFenceWithoutInventingSecurityEvents() throws Exception { + for (long generation : new long[] {1L, 11L}) { + long fence = generation + 1L; + var cutoff = + generation == 1L + ? Optional.empty() + : Optional.of(cutoff(generation, generation - 1L)); + var snapshot = + new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), 7L, 7L, generation, generation, fence, fence, cutoff); + Map claims = new LinkedHashMap<>(claims()); + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple(7L, generation, cutoff)); + claims.put("issuanceFence", Long.toString(fence)); + var decoded = + GameSessionAccountDelegationRegistryRecord.decode( + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact(claims), + "5", + binding(), + snapshot, + bundleReference(), + NOW, + MAX_RECORD_BYTES) + .toCanonicalJsonBytes(MAX_RECORD_BYTES), + MAX_RECORD_BYTES); + assertThat(decoded.issuanceFence()).isEqualTo(fence); + Map tuple = (Map) decoded.fields().get("authorityTuple"); + assertThat(tuple.get("accountAuthorityGeneration")).isEqualTo(Long.toString(generation)); + assertThat(tuple.containsKey("accountSecurityCutoff")).isEqualTo(generation != 1L); + Map versions = (Map) decoded.fields().get("authoritySourceVersions"); + assertThat(versions.get("accountSourceVersion")).isEqualTo(Long.toString(generation)); + assertThat(versions.get("issuanceFenceSourceVersion")).isEqualTo(Long.toString(fence)); + assertThatThrownBy( + () -> + new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), + 7L, + 7L, + generation, + generation, + fence, + fence + 1L, + cutoff)) + .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); + } + assertThatThrownBy( + () -> + new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), + 7L, + 7L, + 11L, + 11L, + 10L, + 10L, + Optional.of(cutoff(11L, 10L)))) + .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); + } + @Test void roundTripsSmallAndLargestOwnerLongAuthorityCountersAsDecimalStrings() throws Exception { long large = Long.MAX_VALUE; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java index f830b5594c..87add6cac9 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java @@ -465,10 +465,12 @@ private static Map> retainedRows(DSLContext dsl) { } private static Map> retainedRows(DSLContext dsl, boolean includeXmin) { + // Compare per-row digests: full row images of every table, held across several + // snapshots, exhausted the shared test JVM heap. Equality semantics are unchanged. String rowImage = includeXmin - ? "retained.xmin::text || ':' || to_jsonb(retained)::text" - : "to_jsonb(retained)::text"; + ? "md5(retained.xmin::text || ':' || to_jsonb(retained)::text)" + : "md5(to_jsonb(retained)::text)"; Map> rows = new LinkedHashMap<>(); for (String table : dsl.fetch( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java index cc92e60dae..f1ac488d81 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java @@ -76,11 +76,89 @@ public GatewayProperties canonicalGatewayProperties(Environment environment) { "/api/design/**", 2), route( - "account-auth", + "account-auth-login", environment.getProperty( "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), - "/api/account/auth/**", - 2), + "/api/account/auth/login", + 2, + "POST"), + route( + "account-auth-player-bootstrap", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/player-bootstrap", + 2, + "POST"), + route( + "account-auth-bootstrap-worlds", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds", + 2, + "GET"), + route( + "account-auth-bootstrap-realms", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds/{worldSlug}/realms", + 2, + "GET"), + route( + "account-auth-bootstrap-characters", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters", + 2, + "GET"), + route( + "account-auth-bootstrap-join", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/join", + 2, + "POST"), + route( + "account-auth-connect-token", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/connect-token", + 2, + "POST"), + route( + "account-auth-request-password-reset", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/request-password-reset", + 2, + "POST"), + route( + "account-auth-complete-password-reset", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/complete-password-reset", + 2, + "POST"), + route( + "account-auth-request-email-verification", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/request-email-verification", + 2, + "POST"), + route( + "account-auth-verify-email", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/verify-email", + 2, + "POST"), + route( + "account-auth-recover-username", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/recover-username", + 2, + "POST"), route( "account-accounts", environment.getProperty( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java index d732e10aef..a6544fc5c8 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java @@ -9,14 +9,12 @@ import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** Canonical low-cardinality key resolution for gateway-wide request rate limiting. */ @Configuration public class GatewayRateLimiterConfig { - private static final String X_FORWARDED_FOR = "X-Forwarded-For"; private static final String UNKNOWN_CLIENT_KEY = "unknown-client"; private static final String RATE_LIMITER_FILTER = "RequestRateLimiter"; private static final String REPLENISH_RATE = "redis-rate-limiter.replenishRate"; @@ -83,28 +81,10 @@ private String resolveClientKey(ServerWebExchange exchange) { return clientIp.trim(); } - clientIp = firstForwardedFor(exchange.getRequest().getHeaders()); - if (clientIp != null) { - return clientIp; - } - InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress(); if (remoteAddress != null && remoteAddress.getAddress() != null) { return remoteAddress.getAddress().getHostAddress(); } return UNKNOWN_CLIENT_KEY; } - - private String firstForwardedFor(HttpHeaders headers) { - String xff = headers.getFirst(X_FORWARDED_FOR); - if (xff == null || xff.isBlank()) { - return null; - } - String[] segments = xff.split(","); - if (segments.length == 0) { - return null; - } - String candidate = segments[0].trim(); - return candidate.isEmpty() ? null : candidate; - } } diff --git a/services/spring-cloud-gateway/src/main/resources/application.yml b/services/spring-cloud-gateway/src/main/resources/application.yml index 42aaef600d..8fa3fc5fcc 100644 --- a/services/spring-cloud-gateway/src/main/resources/application.yml +++ b/services/spring-cloud-gateway/src/main/resources/application.yml @@ -31,7 +31,9 @@ spring: retries: 3 statuses: BAD_GATEWAY,GATEWAY_TIMEOUT series: SERVER_ERROR - methods: GET,POST + # One-use Account recovery and verification POSTs have no replay receipt. + # An ambiguous upstream response must not trigger an automatic second claim. + methods: GET backoff: firstBackoff: 50ms maxBackoff: 500ms diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayAuthRoutesTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayAuthRoutesTest.java new file mode 100644 index 0000000000..3764b72451 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayAuthRoutesTest.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.*; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.handler.predicate.MethodRoutePredicateFactory; +import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory; +import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.http.HttpMethod; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; + +class GatewayAuthRoutesTest { + private record Endpoint(String id, String path, HttpMethod method) {} + + private static final List ENDPOINTS = + List.of( + new Endpoint("login", "login", HttpMethod.POST), + new Endpoint("player-bootstrap", "player-bootstrap", HttpMethod.POST), + new Endpoint("bootstrap-worlds", "bootstrap/worlds", HttpMethod.GET), + new Endpoint("bootstrap-realms", "bootstrap/worlds/{worldSlug}/realms", HttpMethod.GET), + new Endpoint( + "bootstrap-characters", + "bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters", + HttpMethod.GET), + new Endpoint("bootstrap-join", "bootstrap/join", HttpMethod.POST), + new Endpoint("connect-token", "connect-token", HttpMethod.POST), + new Endpoint("request-password-reset", "request-password-reset", HttpMethod.POST), + new Endpoint("complete-password-reset", "complete-password-reset", HttpMethod.POST), + new Endpoint("request-email-verification", "request-email-verification", HttpMethod.POST), + new Endpoint("verify-email", "verify-email", HttpMethod.POST), + new Endpoint("recover-username", "recover-username", HttpMethod.POST)); + + static void assertCatalog(GatewayProperties properties) { + properties.getRoutes().forEach(route -> assertThat(route.getId()).isNotNull()); + assertThat( + properties.getRoutes().stream() + .filter( + r -> java.util.Objects.requireNonNull(r.getId()).startsWith("account-auth"))) + .hasSize(ENDPOINTS.size()); + assertNoConfiguredPath(properties, "/api/account/auth/**"); + assertNoConfiguredPathStartsWith(properties, "/verify-email"); + assertNoConfiguredPathStartsWith(properties, "/reset-password"); + for (Endpoint endpoint : ENDPOINTS) { + String id = "account-auth-" + endpoint.id(); + assertHasPath(properties, id, "/api/account/auth/" + endpoint.path()); + assertHasMethod(properties, id, endpoint.method().name()); + assertHasStripPrefixTwo(properties, id); + assertThat(route(properties, id).getUri().toString()) + .isEqualTo("http://account-service:8080"); + } + } + + @Test + void actualPredicatesAdmitOnlyDeclaredAccountAuthMethodsAndPaths() { + GatewayProperties properties = + new CanonicalGatewayRoutesConfiguration().canonicalGatewayProperties(new MockEnvironment()); + assertCatalog(properties); + for (Endpoint endpoint : ENDPOINTS) { + String path = + "/api/account/auth/" + + endpoint.path().replace("{worldSlug}", "world").replace("{realmSlug}", "realm"); + for (HttpMethod method : HttpMethod.values()) { + assertThat(matches(properties, path, method)) + .as("%s %s", method, path) + .isEqualTo(method.equals(endpoint.method())); + } + assertThat(matches(properties, path + "/extra", endpoint.method())).isFalse(); + } + for (String path : + List.of( + "/api/account/auth/internal/runtime", + "/api/account/auth/unknown", + "/api/account/auth", + "/verify-email", + "/reset-password")) { + for (HttpMethod method : HttpMethod.values()) { + assertThat(matches(properties, path, method)).as("%s %s", method, path).isFalse(); + } + } + } + + private boolean matches(GatewayProperties properties, String path, HttpMethod method) { + for (RouteDefinition route : properties.getRoutes()) { + var exchange = MockServerWebExchange.from(MockServerHttpRequest.method(method, path).build()); + boolean matches = + route.getPredicates().stream() + .allMatch( + predicate -> { + if ("Path".equals(predicate.getName())) { + var config = new PathRoutePredicateFactory.Config(); + config.setPatterns(List.copyOf(predicate.getArgs().values())); + return new PathRoutePredicateFactory( + new org.springframework.boot.webflux.autoconfigure + .WebFluxProperties()) + .apply(config) + .test(exchange); + } + if ("Method".equals(predicate.getName())) { + var config = new MethodRoutePredicateFactory.Config(); + config.setMethods( + predicate.getArgs().values().stream() + .map(HttpMethod::valueOf) + .toArray(HttpMethod[]::new)); + return new MethodRoutePredicateFactory().apply(config).test(exchange); + } + throw new AssertionError("Unexpected predicate " + predicate.getName()); + }); + if (matches) return true; + } + return false; + } +} diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayDefaultRetryConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayDefaultRetryConfigurationTest.java new file mode 100644 index 0000000000..236fb74262 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayDefaultRetryConfigurationTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +class GatewayDefaultRetryConfigurationTest { + @Test + void defaultRetriesCannotReplayOneUseAccountMutations() throws IOException { + var environment = new StandardEnvironment(); + for (var source : + new YamlPropertySourceLoader() + .load( + "gateway-defaults", new FileSystemResource("src/main/resources/application.yml"))) { + environment.getPropertySources().addFirst(source); + } + var properties = + new CanonicalGatewayRoutesConfiguration().canonicalGatewayProperties(environment); + var retryFilters = + properties.getDefaultFilters().stream() + .filter(filter -> "Retry".equals(filter.getName())) + .toList(); + assertThat(retryFilters).hasSize(1); + assertThat(retryFilters.getFirst().getArgs()).containsEntry("methods", "GET"); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java index 38e63fb9a4..9b27336c46 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java @@ -48,7 +48,18 @@ class GatewayRoutesConfigurationProdTest { "admin-sagas", "admin-tick-remediation", "design", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -121,12 +132,12 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); assertHasPath(gatewayProperties, "design", "/api/design/**"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + GatewayAuthRoutesTest.assertCatalog(gatewayProperties); assertHasStripPrefixTwo(gatewayProperties, "admin-ping"); assertHasStripPrefixTwo(gatewayProperties, "admin-admission-pointers"); assertHasStripPrefixTwo(gatewayProperties, "admin-remote-followups"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); assertHasStripPrefixTwo(gatewayProperties, "design"); - assertHasStripPrefixTwo(gatewayProperties, "account-auth"); + assertHasStripPrefixTwo(gatewayProperties, "account-auth-login"); } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java index a15d8e7c9b..ec9c68b5e0 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java @@ -47,7 +47,18 @@ class GatewayRoutesConfigurationTest { "admin-sagas", "admin-tick-remediation", "design", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -133,13 +144,13 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasPath(gatewayProperties, "design", "/api/design/**"); assertHasStripPrefixTwo(gatewayProperties, "design"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + GatewayAuthRoutesTest.assertCatalog(gatewayProperties); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); assertHasPath(gatewayProperties, "account-profiles", "/api/account/profiles/**"); assertHasPath(gatewayProperties, "account-ping", "/api/account/ping"); assertHasPath(gatewayProperties, "account-jwks", "/api/account/.well-known/jwks.json"); - assertHasStripPrefixTwo(gatewayProperties, "account-auth"); + assertHasStripPrefixTwo(gatewayProperties, "account-auth-login"); assertHasStripPrefixTwo(gatewayProperties, "account-accounts"); assertHasStripPrefixTwo(gatewayProperties, "account-profiles"); assertHasStripPrefixTwo(gatewayProperties, "account-ping"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java index 84656b3137..5347df4cba 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java @@ -47,7 +47,18 @@ class GatewayRoutesConfigurationTestProfileTest { "admin-sagas", "admin-tick-remediation", "design", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -115,7 +126,7 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasPath(gatewayProperties, "session-ping", "/api/session/ping"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + GatewayAuthRoutesTest.assertCatalog(gatewayProperties); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); assertHasPath(gatewayProperties, "account-profiles", "/api/account/profiles/**"); assertHasPath(gatewayProperties, "account-ping", "/api/account/ping"); @@ -134,7 +145,7 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasStripPrefix(gatewayProperties, "admin-sagas", "2"); assertHasStripPrefix(gatewayProperties, "admin-tick-remediation", "2"); assertHasStripPrefix(gatewayProperties, "design", "2"); - assertHasStripPrefix(gatewayProperties, "account-auth", "2"); + assertHasStripPrefix(gatewayProperties, "account-auth-login", "2"); assertHasStripPrefix(gatewayProperties, "account-accounts", "2"); assertHasStripPrefix(gatewayProperties, "account-profiles", "2"); assertHasStripPrefix(gatewayProperties, "account-ping", "2"); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java index 21fc50d757..cceb8961aa 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java @@ -31,17 +31,29 @@ void prefersGatewayOwnedClientIpHeader() { } @Test - void fallsBackToForwardedForWhenGatewayOwnedHeaderMissing() { + void ignoresUncanonicalizedForwardedForWhenGatewayOwnedHeaderMissing() { KeyResolver resolver = new GatewayRateLimiterConfig().gatewayClientIpKeyResolver(); MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("/api/account/auth/player-bootstrap") .header(X_FORWARDED_FOR, "203.0.113.77, 10.0.0.1") + .remoteAddress(new java.net.InetSocketAddress("192.0.2.44", 0)) .build()); String key = resolver.resolve(exchange).block(); - assertThat(key).isEqualTo("203.0.113.77"); + assertThat(key).isEqualTo("192.0.2.44"); + } + + @Test + void ignoresForwardedHeaderWithoutTransportAddress() { + KeyResolver resolver = new GatewayRateLimiterConfig().gatewayClientIpKeyResolver(); + var exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/api/account/auth/verify-email") + .header(X_FORWARDED_FOR, "203.0.113.77") + .build()); + assertThat(resolver.resolve(exchange).block()).isEqualTo("unknown-client"); } @Test diff --git a/settings.gradle.kts b/settings.gradle.kts index c8a0d7284e..662bdda068 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -74,3 +74,7 @@ if (includeLoadTesting) { include("load-testing") project(":load-testing").projectDir = File("dev-tools/load-testing") } + +// Source-only one-shot custodian; no runtime or deployment enrollment. +include("account-jwt-materializer") +project(":account-jwt-materializer").projectDir = file("k8s/account-jwt-materializer") diff --git a/web-client/.dockerignore b/web-client/.dockerignore new file mode 100644 index 0000000000..7bfeeef467 --- /dev/null +++ b/web-client/.dockerignore @@ -0,0 +1,21 @@ +# Dependencies and generated output are installed or produced inside the image. +node_modules +dist +dist-ssr + +# Local-only configuration, logs, and editor state. +logs +*.log +*.local +.env +.env.* +.vscode +.idea +.DS_Store + +# Package-manager debug output. +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* diff --git a/web-client/Dockerfile b/web-client/Dockerfile new file mode 100644 index 0000000000..086056fe5f --- /dev/null +++ b/web-client/Dockerfile @@ -0,0 +1,19 @@ +# Build from the repository root: docker build -f web-client/Dockerfile . +# Dockerfile.dockerignore admits only frontend inputs and their shared TS config. +FROM node:24.21.0-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1 AS build + +WORKDIR /app/web-client +COPY web-client/package.json web-client/package-lock.json ./ +RUN npm ci +COPY config/ts/tsconfig.base.json /app/config/ts/tsconfig.base.json +COPY web-client/ ./ +# Vite also resolves the shared TS config; type checking runs in the frontend CI lane. +RUN npm exec -- vite build + +FROM ghcr.io/nginx/nginx-unprivileged:1.30.5-alpine3.24@sha256:daa17b944bac2b578e962da4c61ad72a59233b3c63abea17113acaf4e6b9aea4 + +COPY web-client/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/web-client/dist/ /usr/share/nginx/html/ + +USER 101 +EXPOSE 8080 diff --git a/web-client/Dockerfile.dockerignore b/web-client/Dockerfile.dockerignore new file mode 100644 index 0000000000..29ad42c2e1 --- /dev/null +++ b/web-client/Dockerfile.dockerignore @@ -0,0 +1,17 @@ +# Isolated repository-root context for the frontend image only. +** +!web-client/ +!web-client/** +!config/ +!config/ts/ +!config/ts/tsconfig.base.json +web-client/node_modules +web-client/dist +web-client/dist-ssr +web-client/.gradle +web-client/.env +web-client/.env.* +web-client/*.local +web-client/*.log +web-client/.vscode +web-client/.idea diff --git a/web-client/README.md b/web-client/README.md index 53f3b5b7bc..d0f5308b7c 100644 --- a/web-client/README.md +++ b/web-client/README.md @@ -22,7 +22,7 @@ See: - [Frontend Architecture](../design/architecture/system-architecture-frontend.md) - [Player Experience, Commands, and Communication implementation tracker](../design/project-management/implementation-tracking/player-experience-commands-and-communication.md) -The Vite production build writes compiled assets to `dist/frontend-assets/`, so generated compiled JavaScript/CSS references use `/frontend-assets/**`. The prefix is reserved for first-party compiled files, does not SPA-fallback, and is not a Gateway route. The static host/Ingress, origin separation, and full browser proof remain target-state work under [ADR 0144](../design/architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). +The Vite production build writes compiled assets to `dist/frontend-assets/`, so generated compiled JavaScript/CSS references use `/frontend-assets/**`. The prefix is reserved for first-party compiled files, does not SPA-fallback, and is not a Gateway route. The disabled static-host/Ingress source preparation is described below; independent publication, origin qualification and full browser proof remain open under [ADR 0144](../design/architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). ## Local Development @@ -50,3 +50,22 @@ The accessibility audit depends on Google Chrome. See [Developer Setup](../DEVEL - Treat this module as FireMUD application code, not a generic Vite template. - Keep browser auth/session handling aligned with the canonical architecture docs. - When frontend architecture changes, update both this README and the high-level docs in `design/architecture/`. + +## Account email links + +`/verify-email#token=…` and `/reset-password#token=…` capture and scrub the fragment before mounting. A user must explicitly submit the verification or new password; loading the document never dispatches a mutation. Completion uses the public Account POSTs via `/api/account/auth/`, with local Vite forwarding `/api` to Gateway on port 8080. Existing `/account/` hosting checkout routes remain separate. Run `npm run test:email-link` for the focused token, request and uncertain-result tests. + +The owning [Account contract](../design/architecture/microservices/account-service/api-contracts.md) defines the behavior. Hosted static delivery and browser/SMTP proof are separate from these unit tests. + +### Disabled static-host preparation + +Build the static image from the repository root with +`docker build -f web-client/Dockerfile -t firemud-frontend:local .`. +The Dockerfile-specific ignore file includes frontend sources and the shared +TypeScript configuration without broadening service-image contexts. A +`web-client/`-only context cannot resolve that shared configuration during Vite's +build. + +The recovered unprivileged static image and Helm host remain default-off behind both `previewStack.enabled` and `previewStack.frontend.enabled`. Only an explicit frontend enablement selects the SPA/API/WebSocket split; existing Gateway ingress is unchanged by default. Image publication and fresh browser/edge qualification remain prerequisites to activation. Nginx logs the path without query strings, emits no-referrer, refuses reserved API/asset/WebSocket paths and uses immutable content-hash caching. + +The CSP permits only Stripe.js script/frame origins and its API connection needed by the existing next-action checkout adapter, following the [Stripe integration security guide](https://docs.stripe.com/security/guide#content-security-policy). It does not enable Link, Maps, Checkout-hosted or unrelated third-party scripts. These headers are prepared configuration, not deployed CSP/browser proof. diff --git a/web-client/index.html b/web-client/index.html index 04e161d1d3..53d0537182 100644 --- a/web-client/index.html +++ b/web-client/index.html @@ -2,6 +2,7 @@ + FireMUD diff --git a/web-client/nginx.conf b/web-client/nginx.conf new file mode 100644 index 0000000000..57fdd26201 --- /dev/null +++ b/web-client/nginx.conf @@ -0,0 +1,94 @@ +# Stripe.js next-action origins follow https://docs.stripe.com/security/guide#content-security-policy. +log_format firemud_safe '$remote_addr [$time_local] "$request_method $uri $server_protocol" $status $body_bytes_sent "$http_user_agent"'; + +server { + listen 8080 default_server; + server_name _; + + root /usr/share/nginx/html; + index index.html; + server_tokens off; + + include /etc/nginx/mime.types; + default_type application/octet-stream; + + access_log /dev/stdout firemud_safe; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml; + + add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; connect-src 'self' wss: https://api.stripe.com; font-src 'self' data:; form-action 'self'; frame-ancestors 'none'; img-src 'self' data: blob: https:; object-src 'none'; script-src 'self' https://js.stripe.com https://*.js.stripe.com; frame-src https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com; style-src 'self' 'unsafe-inline'; upgrade-insecure-requests" always; + add_header Referrer-Policy "no-referrer" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + location = /healthz { + access_log off; + default_type text/plain; + return 200 "ok\n"; + } + + location = /frontend-assets { + return 404; + } + + location ^~ /frontend-assets/ { + if ($request_method !~ ^(GET|HEAD)$) { + return 405; + } + + try_files $uri =404; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; connect-src 'self' wss: https://api.stripe.com; font-src 'self' data:; form-action 'self'; frame-ancestors 'none'; img-src 'self' data: blob: https:; object-src 'none'; script-src 'self' https://js.stripe.com https://*.js.stripe.com; frame-src https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com; style-src 'self' 'unsafe-inline'; upgrade-insecure-requests" always; + add_header Referrer-Policy "no-referrer" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + } + + location = /assets { + return 404; + } + + location ^~ /assets/ { + return 404; + } + + location = /auth { + return 404; + } + + location ^~ /auth/ { + return 404; + } + + location = /api { + return 404; + } + + location ^~ /api/ { + return 404; + } + + location = /ws/game { + return 404; + } + + location ^~ /ws/game/ { + return 404; + } + + location / { + if ($request_method !~ ^(GET|HEAD)$) { + return 405; + } + + expires -1; + try_files $uri $uri/ /index.html; + } +} diff --git a/web-client/package.json b/web-client/package.json index ef4bc038f7..1d0c53a399 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -8,10 +8,11 @@ "build": "tsc -b && vite build", "lint": "node ./node_modules/eslint/bin/eslint.js .", "preview": "vite preview", - "format": "prettier --check \"src/**/*.{ts,tsx}\"", - "format:fix": "prettier --write \"src/**/*.{ts,tsx}\"", + "format": "prettier --check \"src/**/*.{ts,tsx}\" \"tests/**/*.mjs\"", + "format:fix": "prettier --write \"src/**/*.{ts,tsx}\" \"tests/**/*.mjs\"", "accessibility": "npm run build && npx serve dist -l 5000 & npx wait-on http://localhost:5000/index.html && npx axe http://localhost:5000/index.html --chrome-options=\"--no-sandbox\" --exit", - "test:checkout": "vitest run src/billing/HostingFirstInvoiceCheckout.test.tsx src/api/hostingFirstInvoice.test.ts src/api/accountControlUi.test.ts src/account/controlUiSession.test.ts src/account/AccountCheckoutRoute.test.tsx" + "test:checkout": "vitest run src/billing/HostingFirstInvoiceCheckout.test.tsx src/api/hostingFirstInvoice.test.ts src/api/accountControlUi.test.ts src/account/controlUiSession.test.ts src/account/AccountCheckoutRoute.test.tsx", + "test:email-link": "node --experimental-strip-types --test tests/email-link.test.mjs && vitest run src/EmailLinkLanding.test.tsx" }, "dependencies": { "@emotion/react": "^11.14.0", diff --git a/web-client/src/App.css b/web-client/src/App.css index f4b43e332a..b4d0574415 100644 --- a/web-client/src/App.css +++ b/web-client/src/App.css @@ -46,3 +46,75 @@ color: #ccc; } } + +.email-link-page { + box-sizing: border-box; + display: grid; + min-height: 100vh; + place-items: center; + padding: 1.5rem; + text-align: left; +} + +.email-link-panel { + width: min(100%, 32rem); + padding: clamp(1.5rem, 5vw, 2.5rem); + border: 1px solid #d7dce2; + border-radius: 0.75rem; + background: #fff; + color: #18212b; + box-shadow: 0 1rem 3rem rgb(20 32 44 / 10%); +} + +.email-link-panel h1 { + margin-top: 0; + font-size: clamp(1.75rem, 5vw, 2.25rem); + line-height: 1.2; +} + +.email-link-panel p { + line-height: 1.6; +} + +.email-link-panel form { + display: grid; + gap: 1rem; + margin-top: 1.5rem; +} + +.email-link-field { + display: grid; + gap: 0.5rem; + font-weight: 600; +} + +.email-link-field input { + box-sizing: border-box; + width: 100%; + min-height: 2.75rem; + padding: 0.65rem 0.75rem; + border: 1px solid #778391; + border-radius: 0.35rem; + color: #18212b; + font: inherit; +} + +.email-link-panel button { + min-height: 2.75rem; + border: 0; + border-radius: 0.35rem; + background: #184f80; + color: #fff; + font: inherit; + font-weight: 650; +} + +.email-link-panel button:disabled { + cursor: wait; + opacity: 0.7; +} + +.email-link-panel :focus-visible { + outline: 3px solid #e59a22; + outline-offset: 3px; +} diff --git a/web-client/src/App.tsx b/web-client/src/App.tsx index 9a5dbef7ab..22beac6373 100644 --- a/web-client/src/App.tsx +++ b/web-client/src/App.tsx @@ -1,6 +1,8 @@ import { useEffect, useState } from 'react'; import Button from '@mui/material/Button'; import GameEditor from './GameEditor'; +import EmailLinkLanding from './EmailLinkLanding'; +import { emailLinkLanding } from './emailLinkLanding'; import ScriptEditor from './ScriptEditor'; import AccountCheckoutRoute, { type AccountCheckoutRouteProps, @@ -24,6 +26,10 @@ function App({ accountCheckoutRouteProps }: AppProps = {}) { return () => window.removeEventListener('popstate', updatePathname); }, []); + if (emailLinkLanding) { + return ; + } + if (pathname.startsWith('/account/')) { return ( { + cleanup(); + document.head.querySelector('meta[name="referrer"]')?.remove(); + window.history.replaceState(null, '', '/'); + vi.unstubAllGlobals(); +}); + +async function openLanding(href: string) { + vi.resetModules(); + const request = vi + .fn() + .mockResolvedValue(new Response(null, { status: 204 })); + vi.stubGlobal('fetch', request); + window.history.replaceState(null, '', href); + const { default: App } = await import('./App'); + render(); + return request; +} + +it('mounts the verification link without sending anything until the user submits', async () => { + const request = await openLanding( + '/verify-email?ignored=1#token=synthetic-verification' + ); + screen.getByRole('heading', { name: 'Verify your email' }); + expect(window.location.search + window.location.hash).toBe(''); + expect(request).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Verify email' })); + expect((await screen.findByRole('status')).textContent).toContain( + 'Your email address is verified.' + ); + expect(request).toHaveBeenCalledExactlyOnceWith( + '/api/account/auth/verify-email', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'synthetic-verification' }), + } + ); +}); + +it('mounts the reset form and sends the typed password only on explicit submission', async () => { + const request = await openLanding('/reset-password#token=synthetic-reset'); + screen.getByRole('heading', { name: 'Choose a new password' }); + const input = screen.getByLabelText('New password'); + expect(window.location.hash).toBe(''); + expect(request).not.toHaveBeenCalled(); + fireEvent.change(input, { target: { value: 'test-password' } }); + expect(request).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Update password' })); + expect((await screen.findByRole('status')).textContent).toContain( + 'Your password has been updated.' + ); + expect(request).toHaveBeenCalledExactlyOnceWith( + '/api/account/auth/complete-password-reset', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + token: 'synthetic-reset', + newPassword: 'test-password', + }), + } + ); +}); diff --git a/web-client/src/EmailLinkLanding.tsx b/web-client/src/EmailLinkLanding.tsx new file mode 100644 index 0000000000..f572a7baeb --- /dev/null +++ b/web-client/src/EmailLinkLanding.tsx @@ -0,0 +1,114 @@ +import { useEffect, useState, type FormEvent } from 'react'; +import { + completeEmailLink, + emailLinkFailureMessage, + EmailLinkCompletionError, + type EmailLinkLandingRoute, +} from './emailLinkLanding'; + +interface EmailLinkLandingProps { + route: Exclude; +} + +function installNoReferrerPolicy(): void { + let policy = document.head.querySelector( + 'meta[name="referrer"]' + ); + if (!policy) { + policy = document.createElement('meta'); + policy.name = 'referrer'; + document.head.append(policy); + } + policy.content = 'no-referrer'; +} + +export default function EmailLinkLanding({ route }: EmailLinkLandingProps) { + const [password, setPassword] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [complete, setComplete] = useState(false); + const [failure, setFailure] = useState(null); + + useEffect(() => { + installNoReferrerPolicy(); + }, []); + + const token = route.token; + const isVerification = route.kind === 'verify-email'; + const title = isVerification ? 'Verify your email' : 'Choose a new password'; + + async function submit(event: FormEvent) { + event.preventDefault(); + if (!token || submitting || complete) return; + + setSubmitting(true); + setFailure(null); + try { + await completeEmailLink(route, isVerification ? undefined : password); + setComplete(true); + setPassword(''); + } catch (error) { + setFailure( + error instanceof EmailLinkCompletionError + ? error + : new EmailLinkCompletionError('network', null) + ); + } finally { + setSubmitting(false); + } + } + + return ( +

+
+

{title}

+ {complete ? ( +

+ {isVerification + ? 'Your email address is verified.' + : 'Your password has been updated.'} +

+ ) : !token ? ( +

+ This link is invalid or has expired. Request a new email and try + again. +

+ ) : ( + <> +

+ {isVerification + ? 'Select the button below to verify this email address.' + : 'Enter a new password, then select the button to finish resetting it.'} +

+
+ {!isVerification && ( + + )} + +
+ {failure && ( +

{emailLinkFailureMessage(route.kind, failure)}

+ )} + + )} +
+
+ ); +} diff --git a/web-client/src/emailLinkLanding.ts b/web-client/src/emailLinkLanding.ts new file mode 100644 index 0000000000..f597b28f63 --- /dev/null +++ b/web-client/src/emailLinkLanding.ts @@ -0,0 +1,120 @@ +export type EmailLinkLandingRoute = + | { kind: 'verify-email'; token: string | null } + | { kind: 'reset-password'; token: string | null } + | null; + +export type EmailLinkCompletionFailureKind = + 'missing-token' | 'http' | 'network'; + +export class EmailLinkCompletionError extends Error { + readonly kind: EmailLinkCompletionFailureKind; + readonly status: number | null; + + constructor( + kind: EmailLinkCompletionFailureKind, + status: number | null, + message = 'The request could not be completed.' + ) { + super(message); + this.name = 'EmailLinkCompletionError'; + this.kind = kind; + this.status = status; + } +} + +function tokenFromFragment(hash: string): string | null { + const values = new URLSearchParams( + hash.startsWith('#') ? hash.slice(1) : hash + ); + const token = values.get('token'); + return token && token.trim().length > 0 ? token : null; +} + +export function captureEmailLinkLanding( + location: Location, + history: History +): EmailLinkLandingRoute { + const path = location.pathname.replace(/\/$/, '') || '/'; + if (path !== '/verify-email' && path !== '/reset-password') { + return null; + } + + const token = tokenFromFragment(location.hash); + // The token is consumed from memory only. Replacing the address also keeps + // it out of copied URLs and any subsequent same-page navigation metadata. + history.replaceState(null, '', location.pathname); + + return path === '/verify-email' + ? { kind: 'verify-email', token } + : { kind: 'reset-password', token }; +} + +export async function completeEmailLink( + route: Exclude, + newPassword?: string, + request: typeof fetch = fetch +): Promise { + if (!route.token) { + throw new EmailLinkCompletionError( + 'missing-token', + null, + 'The link is invalid.' + ); + } + const verification = route.kind === 'verify-email'; + try { + const response = await request( + verification + ? '/api/account/auth/verify-email' + : '/api/account/auth/complete-password-reset', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify( + verification + ? { token: route.token } + : { token: route.token, newPassword } + ), + } + ); + if (!response.ok) { + throw new EmailLinkCompletionError('http', response.status ?? null); + } + } catch (error) { + if (error instanceof EmailLinkCompletionError) { + throw error; + } + throw new EmailLinkCompletionError('network', null); + } +} + +export function emailLinkFailureMessage( + routeKind: Exclude['kind'], + failure: Pick +): string { + if (failure.kind === 'missing-token') { + return 'This link is invalid or has expired. Request a new email and try again.'; + } + + if (failure.kind === 'http' && failure.status === 400) { + return 'We could not accept this request. Check the submitted details and request a new email if needed.'; + } + + if ( + failure.kind === 'network' || + (failure.kind === 'http' && + (failure.status === 429 || (failure.status ?? 0) >= 500)) + ) { + return routeKind === 'reset-password' + ? 'We could not confirm whether the password reset completed. Try signing in with your intended new password before requesting another reset email.' + : 'We could not confirm whether email verification completed. Check your account after signing in before requesting another verification email.'; + } + + return 'We could not accept this request. Check the submitted details and try again.'; +} + +// Capture and scrub before React mounts or any route can issue a request. +export const emailLinkLanding = + typeof window === 'undefined' + ? null + : captureEmailLinkLanding(window.location, window.history); diff --git a/web-client/tests/email-link.test.mjs b/web-client/tests/email-link.test.mjs new file mode 100644 index 0000000000..e688449add --- /dev/null +++ b/web-client/tests/email-link.test.mjs @@ -0,0 +1,275 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import { + captureEmailLinkLanding, + completeEmailLink, + emailLinkFailureMessage, + EmailLinkCompletionError, +} from '../src/emailLinkLanding.ts'; + +test('format check and fix cover the same source and test globs', async () => { + const { scripts } = JSON.parse( + await readFile(new URL('../package.json', import.meta.url), 'utf8') + ); + const getGlobs = (command) => + Array.from(command.matchAll(/"([^"]+)"/g), (match) => match[1]); + const expectedGlobs = ['src/**/*.{ts,tsx}', 'tests/**/*.mjs']; + + assert.deepEqual(getGlobs(scripts.format), expectedGlobs); + assert.deepEqual(getGlobs(scripts['format:fix']), expectedGlobs); +}); + +test('reset form and API schema retain the Account password bounds', async () => { + const form = await readFile( + new URL('../src/EmailLinkLanding.tsx', import.meta.url), + 'utf8' + ); + const dto = await readFile( + new URL( + '../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CompletePasswordResetRequest.java', + import.meta.url + ), + 'utf8' + ); + const schema = await readFile( + new URL( + '../../services/account-service/src/main/resources/openapi.yaml', + import.meta.url + ), + 'utf8' + ); + assert.match(dto, /@Size\(min = 6, max = 100\) String newPassword/); + assert.match( + form, + /]*maxLength=\{100\}[^>]*minLength=\{6\}[^>]*name="newPassword"/ + ); + const resetSchema = schema + .split(' CompletePasswordResetRequest:')[1] + ?.split(' UsernameRecoveryRequest:')[0]; + assert.ok(resetSchema, 'CompletePasswordResetRequest must exist'); + assert.match( + resetSchema, + /newPassword:\s+type: string\s+minLength: 6\s+maxLength: 100/ + ); +}); + +test('verification GET captures a fragment token without dispatching an API mutation', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/verify-email', + search: '', + hash: '#token=verification%2Dtoken', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { + kind: 'verify-email', + token: 'verification-token', + }); + assert.deepEqual(changes, [[null, '', '/verify-email']]); +}); + +test('reset GET captures a fragment token and never sends it in the landing URL', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/reset-password', + search: '', + hash: '#token=reset-token', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { kind: 'reset-password', token: 'reset-token' }); + assert.deepEqual(changes, [[null, '', '/reset-password']]); +}); + +test('landing removes query parameters without accepting them as a token', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/verify-email', + search: '?token=legacy-query-secret', + hash: '', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { kind: 'verify-email', token: null }); + assert.deepEqual(changes, [[null, '', '/verify-email']]); +}); + +test('only explicit verification completion sends a public POST', async () => { + const calls = []; + await completeEmailLink( + { kind: 'verify-email', token: 'verification-token' }, + undefined, + async (...args) => { + calls.push(args); + return { ok: true }; + } + ); + + assert.deepEqual(calls, [ + [ + '/api/account/auth/verify-email', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'verification-token' }), + }, + ], + ]); +}); + +test('reset completion submits the new password only in the POST body', async () => { + const calls = []; + await completeEmailLink( + { kind: 'reset-password', token: 'reset-token' }, + 'new-secret', + async (...args) => { + calls.push(args); + return { ok: true }; + } + ); + + assert.deepEqual(calls, [ + [ + '/api/account/auth/complete-password-reset', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + token: 'reset-token', + newPassword: 'new-secret', + }), + }, + ], + ]); +}); + +test('missing token and failed completion never report success', async () => { + let calls = 0; + const request = async () => { + calls += 1; + return { ok: false }; + }; + + await assert.rejects( + completeEmailLink({ kind: 'verify-email', token: null }, undefined, request) + ); + assert.equal(calls, 0); + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'bad-token' }, + undefined, + request + ) + ); + assert.equal(calls, 1); +}); + +test('completion preserves HTTP failure categories without exposing the token', async () => { + for (const status of [400, 429, 503]) { + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'secret-token' }, + undefined, + async () => ({ ok: false, status }) + ), + (error) => { + assert.ok(error instanceof EmailLinkCompletionError); + assert.equal(error.kind, 'http'); + assert.equal(error.status, status); + assert.doesNotMatch(error.message, /secret-token/); + return true; + } + ); + } +}); + +test('completion preserves network failures without retrying the POST', async () => { + let calls = 0; + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'secret-token' }, + undefined, + async () => { + calls += 1; + throw new Error('offline'); + } + ), + (error) => { + assert.ok(error instanceof EmailLinkCompletionError); + assert.equal(error.kind, 'network'); + assert.equal(error.status, null); + assert.doesNotMatch(error.message, /secret-token|offline/); + return true; + } + ); + assert.equal(calls, 1); +}); + +test('failure messages distinguish rejected input from uncertain completion', () => { + const rejected = emailLinkFailureMessage( + 'verify-email', + new EmailLinkCompletionError('http', 400) + ); + assert.match(rejected, /could not accept this request/i); + assert.doesNotMatch(rejected, /invalid|expired/i); + + for (const failure of [ + new EmailLinkCompletionError('http', 429), + new EmailLinkCompletionError('http', 503), + new EmailLinkCompletionError('network', null), + ]) { + const verification = emailLinkFailureMessage('verify-email', failure); + assert.match(verification, /could not confirm/i); + assert.match(verification, /check your account after signing in/i); + + const reset = emailLinkFailureMessage('reset-password', failure); + assert.match(reset, /could not confirm/i); + assert.match(reset, /try signing in with your intended new password/i); + assert.doesNotMatch(reset, /invalid|expired/i); + } + + assert.match( + emailLinkFailureMessage( + 'verify-email', + new EmailLinkCompletionError('missing-token', null) + ), + /invalid or has expired/i + ); +}); + +test('static host keeps token-safe logging and current Stripe next-action origins', async () => { + const config = await readFile( + new URL('../nginx.conf', import.meta.url), + 'utf8' + ); + assert.match(config, /\$request_method \$uri \$server_protocol/); + assert.doesNotMatch(config, /\$(?:request_uri|args)\b/); + assert.match(config, /Referrer-Policy "no-referrer" always/); + const policies = Array.from( + config.matchAll(/Content-Security-Policy "([^"]+)"/g), + (match) => match[1] + ); + assert.equal(policies.length, 2); + assert.equal(policies[0], policies[1]); + assert.match( + policies[0], + /script-src 'self' https:\/\/js\.stripe\.com https:\/\/\*\.js\.stripe\.com;/ + ); + assert.match( + policies[0], + /frame-src https:\/\/js\.stripe\.com https:\/\/\*\.js\.stripe\.com https:\/\/hooks\.stripe\.com;/ + ); + assert.match( + policies[0], + /connect-src 'self' wss: https:\/\/api\.stripe\.com;/ + ); + assert.doesNotMatch(policies[0], /unsafe-eval|script-src[^;]*unsafe-inline/); +}); diff --git a/web-client/vite.config.ts b/web-client/vite.config.ts index d3c32aaf22..d459658c1d 100644 --- a/web-client/vite.config.ts +++ b/web-client/vite.config.ts @@ -4,6 +4,11 @@ import react from '@vitejs/plugin-react' // https://vite.dev/config/ export default defineConfig({ plugins: [react()], + server: { + proxy: { + '/api': 'http://localhost:8080', + }, + }, build: { assetsDir: 'frontend-assets', },