diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab913ed618..9b8ada9794 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -643,6 +642,9 @@ jobs: - name: 🧪 Validate rendered Helm manifests run: bash ./dev-tools/validation/validate-helm.sh render + - name: 🧪 Validate opt-in tenant migration Jobs + run: bash ./dev-tools/tests/helm-tenant-association-migration-contract.sh + - name: 🧪 Validate hosted Telnet TLS contract run: bash ./dev-tools/tests/hosted-telnet-tls-contract.sh @@ -1013,7 +1015,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fece21cedd..f8021ffce5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -64,10 +64,14 @@ The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `Ver `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Account runtime membership, entitlement, and grant handlers intentionally deny before data access until typed caller/target binding is available. Game Session text `PLAY` retains lifecycle, authority-generation, membership-version, and evaluation-time validation; `JOIN_REQUIRED` is limited to confirmed eligible public-production membership that is missing or `INACTIVE` after fresh entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. This status does not claim a successful public `PLAY` or first-party browser `JOIN`, whose Gateway route remains denied and target-only. Account connect-token issuance still lacks replay-cache revalidation and the independent membership-version/authority-generation issuance reread; full grant/entitlement admission, PostgreSQL/recovery, and end-to-end proof remain open. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the target browser connect-token body and OpenAPI response are metadata-only with raw token delivery only in the HttpOnly cookie. The current response still exposes internal `jti`, so that field remains implementation drift. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Account runtime membership, entitlement, and grant handlers intentionally deny before data access until typed caller/target binding is available. Game Session text `PLAY` retains lifecycle, authority-generation, membership-version, and evaluation-time validation; `JOIN_REQUIRED` is limited to confirmed eligible public-production membership that is missing or `INACTIVE` after fresh entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. This status does not claim a successful public `PLAY` or first-party browser `JOIN`, whose Gateway route remains denied and target-only. Account connect-token issuance still lacks replay-cache revalidation and the independent membership-version/authority-generation issuance reread; full grant/entitlement admission, PostgreSQL/recovery, and end-to-end proof remain open. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the target browser connect-token body and OpenAPI response are metadata-only with raw token delivery only in the HttpOnly cookie. The current `ConnectTokenResponse` is metadata-only and exposes neither internal `jti` nor the raw token. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. For `GetTenantMembershipForRuntime`, the current proto represents `membershipAuthorityGeneration` as `uint64`, and Game Session text `PLAY` requires a positive value for an existing member. This numeric representation and positivity check are implementation drift from the target opaque, equality-only generation semantics owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the current check does not implement the target generation comparison contract. +### Current JOIN Readback Behavior + +The bounded Account-owned worker terminalizes `JOINED` only when exact operation, scope, membership, provisional transition receipt, and matching committed audit delivery with version-1 receipt/projection evidence prove that request performed the transition. It terminalizes `ALREADY_ACTIVE` only when current membership and matching retained receipt history prove the membership was already active; this outcome has no request-specific transition receipt or audit event. Missing, contradictory, or uncertain evidence leaves the intent pending with diagnostics and backoff; expiry or exhausted automatic attempts never terminalize it. + ### Current vs Target Export Lifecycle The current `GET /accounts/{accountId}/export` route is a synchronous Account/profile-local read. Direct account-ID `ExportAccount` gRPC and the legacy account-targeted tenant-export REST/service and gRPC entries deny before data access. The local Account read has no cross-service required-owner fan-in and does not satisfy ADR 0050; none of these current surfaces may be described as a complete portable-data or tenant-admin export. @@ -196,7 +200,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only 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, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. 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`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response including missing/`INACTIVE` and non-admitting lifecycle classification, but without the complete authority-generation/version issuance reread, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **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/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, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. 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`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response including missing/`INACTIVE` and non-admitting lifecycle classification, but without the complete authority-generation/version issuance reread, and public `allowPublicJoin`, fresh and cached-success non-public issuance return `REALM_ACCESS_DENIED` because retained four-field grant rows cannot prove the required lifecycle and state generation. No private issuance path is enabled until the complete lifecycle-qualified grant-and-entitlement authority is implemented. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither internal `jti` nor any raw token. **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` | **Local Account controller and operation; production proof incomplete.** `JoinPublicProductionMembership` is the explicit caller-bound JOIN writer using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent intent and `PENDING` operation, then evaluates entitlement authority; only an available result binds the versioned policy digest, `allowPublicJoin`, and entitlement version. An unavailable attempt remains `PENDING` without fabricated policy evidence. For a retained `PENDING` operation, an expired scope yields retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; it is readback-only and may terminalize only from exact positive prior-commit evidence, never expiry, absence, or an attempt limit. Account revalidates the exact policy digest at the membership commit gate; the request accepts no caller-selected storage scope or independently supplied runtime target. Changed identity/scope/intent/policy cannot retarget a JOIN; an `ACTIVE` retry is event-free. The bounded Account worker retains uncertain operations for diagnostics/retry. The Account HTTP controller and Game Session text `JOIN` dispatch are implemented locally, but the Gateway blocks external route exposure and first-party `Join & Play` remains unavailable. Exact-final-head PostgreSQL lost-acknowledgement/concurrency, direct text-client end-to-end, and membership-generation snapshot proof remain open. The canonical JOIN contract is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); local tracking is in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). | | `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 | @@ -208,7 +212,7 @@ Current verification routing/auth status: both HTTP configurations allowlist `PO Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. -The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. **Current implementation drift:** `ConnectTokenResponse` currently includes `jti` in the body, despite this target metadata-only contract. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. An exact retry with the same `(accountId, connectScopeId, requestId)` and digest replays the stored result; after the response envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. No gRPC `IssueConnectToken` transport exists. +The current `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. The target issuance contract makes an exact retry with the same `(accountId, connectScopeId, requestId)` and digest replay the stored result; after the response-envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. That durable replay behavior is not yet implemented. No gRPC `IssueConnectToken` transport exists. For the bootstrap-character and connect-token REST routes, authenticated gameplay-admission denials (`CONNECT_TOKEN_REJECTED`, `NON_PUBLIC_ENROLLMENT_REQUIRED`, `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `JOIN_REQUIRED`, and `TENANT_BILLING_BLOCKED`) map to HTTP 403; invalid bootstrap credentials remain 401 and unavailable authority remains 503. diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index e484529124..3a7fea7392 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -64,6 +64,22 @@ JOIN account_tenant_membership AS membership ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.membership_id; ``` +### Legacy tenant association import + +**Current implementation status:** V30 and the opt-in `LegacyTenantAssociationImportJobRunner` provide an Account-owned read of retained V26 tenant, membership, and profile source rows, a versioned SHA-256 evidence digest, and guarded import from Game Design's exact tenant-migrator-only owner read. The Account import compares that digest, deployment namespace, source key, UUID, operation and approval evidence before immutable one-to-one storage and exact readback. It does not auto-map rows or enable membership admission. A focused malformed-owner-response unit test and the dedicated-identity guard tests executed locally; the PostgreSQL import/readback case executed but failed at fixture setup on the preceding CI head and its correction awaits exact-head CI. No live manifest or cross-service migration has run. + +An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the dedicated `account-tenant-migrator` certificate and service account. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact migrator mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. Ordinary Account service identity cannot call this import read; the migrator cannot call the separate former-key read. An exact retry is event-free; changed owner or Account evidence is a conflict. + +Deploy and independently verify the required Account schema through the normal reviewed deployment boundary, never through this Job: `evidence` needs its retained V26 source tables, and `import` additionally needs V30 association storage. Neither mode runs Flyway; the rendered Job explicitly disables it for every mode, and one-shot startup requires the effective `spring.flyway.enabled` property to be explicitly `false` before refreshing the Spring context. Missing, true, or invalid values refuse startup before bean initialization; ordinary service startup retains its normal Flyway behavior. Missing required tables or evidence fail the affected operation rather than triggering automatic schema repair. + +Each mode requires its own fixed database Secret and authenticated PostgreSQL role: `evidence` uses `firemud-account-tenant-evidence-db` as `firemud_account_tenant_evidence`, and `import` uses `firemud-account-tenant-import-db` as `firemud_account_tenant_import`. Both roles may connect only to the selected database and use `account_service`; the evidence role receives only `SELECT` on the queried columns of `account_legacy_tenant_sources`, `account_legacy_membership_sources`, and `account_legacy_profile_sources`. The import role receives those same source reads plus only the required `SELECT` and `INSERT` on queried association columns in `account_approved_legacy_tenant_associations`. Neither mode needs `UPDATE`, `DELETE`, sequence, DDL, or lock-function privileges. These credentials are separately provisioned operator inputs, not shared bootstrap, application, or baseline credentials; a missing mode Secret must fail closed, with no optional fallback or chart-created credential. This follows the [Secret Delivery Boundary](../../system-architecture-security.md#secret-delivery-boundary) and [per-service migration ownership](../../system-architecture-database-migrations.md#per-service-organization). + +Before enabling the ordinary-disabled Job, the trusted database operator must provision each role without `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION`, or `BYPASSRLS`, ensure it is not `INHERIT` and has no inherited role memberships, and grant no application-object ownership or unrelated-schema access. Independently read back effective memberships, required grants and prohibited grants, and verify that each Secret-authenticated connection is the exact expected role. Retire the scoped role and Secret after the operation and its recovery window. A rendered Job, Helm check, or role-name assertion is not live grant, Secret-authentication, or PostgreSQL readback proof. + +When this Job is enabled, Account's scheduling configuration is absent so audit delivery, JOIN reconciliation, and credential cleanup cannot run in the migration process. The runner also fails before owner evidence or import if a `ScheduledAnnotationBeanPostProcessor` is present. + +The chart's `previewStack.tenantAssociationMigration.account` values are disabled by default. From a trusted operator revision, supply the exact namespace, a reviewed immutable Account image digest, mode (`evidence` or `import`), positive numeric key, and stable run ID; do not leave the Job enabled for ordinary upgrades. The dedicated `firemud-grpc-account-tenant-migrator` Secret must be issued and verified explicitly using `ensure-standalone-transport-certificates.sh --account-tenant-migrator` and `--verify-account-tenant-migrator` before enabling the Job. The Secret is stable and reused, not requested on every deployment; the Job has no Kubernetes API token, no ingress, and only DNS/Postgres egress plus Game Design gRPC for `import`. A rendered Job or successful completion alone is not database or served-mTLS proof. Retain the operation/readback evidence privately, disable the Job after use, and retire the exact certificate and Secret through the trusted operator boundary. Live Job, PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. + ## 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 delivery method remains directly callable for offline fixture proof but is no longer automatically scheduled. The live Logging & Admin `CreateLogEvent` RPC returns non-OK `UNAVAILABLE` after exact Account workload authentication and before storage, so new and outstanding Account outbox rows remain `PENDING` in the production path while retention/cleanup proof is open. The composed Logging & Admin child provides the typed receipt receiver, durable persistence/deduplication, exact payload-digest validation, bounded projection, and readback at its own service boundary; positive behavior remains offline fixture proof, and live `CreateLogEvent` writes are gated pending retention/cleanup implementation and proof. 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). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index ebf246331e..220ac6d239 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,6 +10,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn JOIN reconciliation also requires explicit version-1 COMMITTED receipt/projection evidence and nonblank receiver identities on the exact locked JOIN outbox row. A pending JOIN whose retained COMMITTED outbox row lacks that marker remains pending with retry diagnostics; the historical row is not upgraded or inferred as current projection proof. Deploying the receiver child alone does not promote these historical rows: current exact receipt/projection readback and a guarded evidence-recording path must be proved before they can enable recovery. An unavailable, minimized, or unsupported receiver response cannot enable recovery. +Membership-transition receipt tables are introduced by Account V40, after the published V28 audit-delivery migration and the child V39/V39.1 migration history; the published V28 definition remains unchanged. No live migration inventory establishes whether any target applied the earlier child-only V28 receipt description/checksum. Before an affected deployment, Account must read back the exact Flyway history and inventory any existing receipt heads/rows, then record a verified no-data boundary or explicit retained-row disposition/mapping. Do not repair migration history, apply this migration out of order, infer receipt provenance, discard existing evidence, or reinterpret it. PostgreSQL migration execution remains gated until focused Docker-backed proof is available. + Live Account-to-Logging writes are disabled: `AccountAuditDeliveryJob` is no longer automatically scheduled, and Logging & Admin's exact-account-authenticated `CreateLogEvent` returns non-OK `UNAVAILABLE` before storage. New and outstanding Account audit outbox rows therefore remain `PENDING` in the production path. Direct service, repository, and job invocations remain offline fixture proof; `ReadLogEventReceipt` remains available, and no readback upgrades historical rows with unknown projection provenance. The retention and cleanup gate is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Credential-bearing gameplay authentication accepts the account's configured password or verified-email OTP modes. The gameplay `Authenticate` and challenge protos are tenant-less: authentication establishes global Account identity without requiring membership, and Game Session retains any bootstrap tenant only as local routing context. The current private delegation token still uses the legacy account-scoped session record; this is implementation status, not the target token-registry contract. @@ -22,9 +24,11 @@ Account V22/V23 rewrite retained email values to canonical form and validate a c Account V25 enforces the live tenant-scoped profile identity `(tenantId, accountId)`. Before adding the unique constraint, the migration fails closed with the named `profiles_tenant_account_identity_collision` preflight constraint when retained duplicates exist; it does not select, merge, delete, or rewrite those rows. Focused PostgreSQL proof covers legal profiles for one global account in different tenants, same-tenant duplicate rejection, and retained-duplicate migration failure without row loss, but those cases compile and are skipped when Docker is unavailable. This current-schema correction does not resolve the separate global-registration, explicit-membership, retained tenant-default, or mixed-binary obligations. +Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. This is an Account persistence bridge only: REST/gRPC DTOs, JWT identities, and external callers remain numeric, and this migration does not create or infer tenant UUID mappings. The focused repository/migration integration class compiled successfully, but all 13 cases were skipped because Docker was unavailable; V29 PostgreSQL migration and immutability behavior therefore remains unexecuted runtime proof. + Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation, scope, membership and audit evidence, and records capped diagnostics with a reason and backoff when evidence is incomplete. It terminalizes only a positively proved prior transition; unresolved rows remain visible and caller-retryable, and due readbacks continue after the configured diagnostic threshold. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation and scope, membership, exact JOIN transition receipt, and matching version-1 COMMITTED audit receipt/projection evidence, and records capped diagnostics with a reason and backoff when evidence is incomplete. It terminalizes JOINED only from that exact prior-transition evidence, or ALREADY_ACTIVE only from matching positive retained receipt history with no new event; unresolved rows remain visible and caller-retryable, and due readbacks continue after the configured diagnostic threshold. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. @@ -159,9 +163,10 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. The target creates public-game membership only through explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` require existing membership and the selected target's grants, entitlements, and admission checks. Current Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for missing membership on an eligible public-production target; an existing non-admitting membership is rejected. These paths do not create or restore membership. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only fresh `MISSING`/`INACTIVE` membership can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account runtime readers still fail closed before reads, so this local classification does not prove a composed outcome; canonical eligibility and remaining outcome mapping belong to [Authentication](../../system-architecture-authentication.md). World and realm discovery remain available before membership. The Account JOIN writer/controller and direct text `JOIN` dispatch exist locally, but the Gateway guard blocks external route exposure and first-party `Join & Play` remains unavailable. Durable recovery after an unknown database commit outcome remains open. Non-public targets remain subject to their realm-access and grant checks rather than public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. The target creates public-game membership only through explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` require existing membership and the selected target's grants, entitlements, and admission checks. Current Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for missing or explicit `INACTIVE` membership on an eligible public-production target; an existing non-admitting membership is rejected. These paths do not create or restore membership. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only fresh `MISSING`/`INACTIVE` membership can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account runtime readers still fail closed before reads, so this local classification does not prove a composed outcome; canonical eligibility and remaining outcome mapping belong to [Authentication](../../system-architecture-authentication.md). World and realm discovery remain available before membership. The Account JOIN writer/controller and direct text `JOIN` dispatch exist locally, but the Gateway guard blocks external route exposure and first-party `Join & Play` remains unavailable. Durable recovery after an unknown database commit outcome remains open. Non-public targets remain subject to their realm-access and grant checks rather than public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish that proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. @@ -186,8 +191,11 @@ Billing-safe mutation authority contract: Membership freshness evidence contract: +`GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and `membershipAuthorityGeneration`. Game Session validates lifecycle consistency, membership version, positive authority generation, identity, freshness, admission, and evaluation time on supplied-authority paths. The target authority tuple and outbox checkpoints remain absent, and the live Account RPC still rejects before data access, so these consumer checks do not establish a fresh atomic target snapshot or composed admission proof. Detailed status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + - Account reads the membership state, `membershipVersion`, the complete applicable `authorityTuple` (including the Account-owned membership authority generation), `evaluatedAt`, and the applicable committed `outboxCheckpoints` set from one authoritative snapshot/transaction or equivalent Account-owned fence. It returns those values together, or returns Account-authenticated evidence over exactly those values; callers must not assemble them from separate membership, generation, projection, or event reads. - The target membership response minimum therefore includes `accountId`, `tenantId`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`. The checkpoint set uses `{outboxStreamKey, outboxSequence, sourceEventId, sourceEventDigest}` for every positive sequence and must contain the exact entry for `account:auth-authority:v1:membership//` that covers the returned membership and tuple snapshot. `membershipAuthorityGeneration` is the explicit membership member of that tuple; any separately carried value must authenticate the same value and is not an independent authority. +- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero carries neither `sourceEventId` nor `sourceEventDigest` and cannot authorize admission. The first committed `JOIN` is sequence one, and a previously joined or left stream retains its positive sequence history even if no current membership row exists. - `evaluatedAt` is the UTC evaluation time of that complete authoritative snapshot and is not restamped when an older projection or cached row is read. A response is invalid when any required field or checkpoint is absent, when the checkpoint does not cover the tuple and membership version, or when the values cannot be proven to come from the same snapshot. Reachable contradictory, stale, regressed, or mismatched evidence is denied; an unavailable or timed-out Account evidence dependency remains retryable `AUTH_UNAVAILABLE`. A distinct authorization outcome may be defined only by the owning API contract for a different operation, not as an alternative code for this runtime membership dependency. Runtime caller contract: @@ -215,7 +223,7 @@ Runtime caller contract: - For a selected target confirmed as public production, fresh Account entitlement (`allowPublicJoin`) and fresh selected-target catalog/pointer/public-production evidence are separate required gates. `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when that selected public-production joining policy denies entry. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; and failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. `JOIN_REQUIRED` is returned only when both gates pass but the fresh membership snapshot is missing or `INACTIVE`. - 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. **Current implementation drift:** `ConnectTokenResponse` currently exposes `jti` in the HTTP response body, and the current `ConnectTokenResult`/`AccountServiceImpl` issuance path does not carry or return `playtestLifecycleId` or `playtestStateGeneration`; the live body is therefore not conformant to the target metadata-only/no-internal-jti target or the required non-public-target identity metadata. + - 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. **Current implementation drift:** `ConnectTokenResponse` omits the internal `jti` and raw token, but the current `ConnectTokenResult`/`AccountServiceImpl` issuance path does not carry or return `playtestLifecycleId` or `playtestStateGeneration`; the live body therefore still lacks the required non-public-target identity metadata. - Account delivers the current connect token only as `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is never returned in the response body or a response-header fallback. Browser/mobile clients and first-party non-browser clients with a protected cookie jar retain and use the cookie normally. 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. @@ -288,15 +296,15 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel ### Runtime Implementation Status and Drift -Account-first bootstrap 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 Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. It does not yet enforce the emitted lifecycle/authority-generation baseline or the full private/playtest target, and a replay-cache hit returns before fresh authority reads. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. +Account-first bootstrap 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 Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; eligible public-production missing or explicit `INACTIVE` membership may produce `JOIN_REQUIRED`, while an existing non-admitting membership is rejected. It does not enforce the issuance membership-version/authority-generation baseline, and public cached-success replay returns before fresh authority reads. Fresh and cached-success private issuance return `REALM_ACCESS_DENIED`; retained legacy four-field grant rows are not read as REST authority because they cannot establish the lifecycle and playtest state generation. Missing private membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`; present non-admitting private membership is `CONNECT_TOKEN_REJECTED`. Character discovery performs local membership/admission checks after entitlement and target checks; non-public discovery, character listing, and issuance fail closed when lifecycle-qualified grant authority is missing. -Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only fresh `MISSING`/`INACTIVE` membership can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Account's live membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding. Text `PLAY` maps that in-band membership outcome to `WORLD_ACCESS_DENIED`; AccountClient separately maps transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. These local consumer checks do not establish a composed live outcome. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md); runtime-reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Logging receipt behavior is locally implemented, but the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. +The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but Gateway blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE`, cannot be reissued, and never terminalize by expiry or attempt threshold. JOINED requires exact transition receipt plus matching version-1 COMMITTED audit receipt/projection evidence; exact prior-history ALREADY_ACTIVE is event-free. PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end, target membership-generation reread, and logging-retention activation proof also remain open. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows; focused cardinality/retry proof does not establish the full snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. -Every current Account deletion entry fails closed unconditionally with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation; no retained-operation check currently enables or blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation remain unimplemented retention follow-through. Account's retention/deletion workflow owns that work 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), including safe disposition of retained terminal JOIN receipts and unknown outcomes tracked in #2848. No universal retention duration is implied. +Every current Account deletion entry fails closed unconditionally with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation. Provider/transfer clearance, retained-data workflow, and safe disposition of retained JOIN receipts remain prerequisites; bounded JOIN receipt cleanup/minimization and deletion reconciliation are unimplemented. This retention gate follows [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), with detailed tracking in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index aa85e79c5d..a2dc9b1acb 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -6,6 +6,14 @@ The protobuf service definitions under [../../../../protos/game-design/v1](../.. For REST endpoints, the authoritative request/response schema source is [openapi.yaml](../../../../services/game-design-service/src/main/resources/openapi.yaml). Design-doc examples should be updated to match when those schemas evolve. +## Tenant Identity Source and Selector + +Game Design is the canonical issuer of opaque UUID `tenantId` values and the owner of stable `tenantSlug` selectors under [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). A retained Game Design game row may receive a UUID with exact owner-local provenance naming its row and former `game.tenant_id`; that binding is immutable and read back exactly. A newly created tenant receives a fresh persisted UUID rather than a numeric-key conversion. Selector assignment is explicit and unique; a game name, row key, former tenant string, or guessed slug is not a selector. Resolving a selector requires the current authoritative binding and does not authorize the caller by itself. + +The separate `TenantIdentityService.ResolveLegacyGameTenantIdentity` read is limited to the verified Account workload peer. It accepts only an exact former Game Design tenant key and returns the persisted UUID, source key, source game row, and provenance kind together. A missing source returns `NOT_FOUND`; malformed input, missing peer, changed provenance, and ambiguous owner data fail closed before returning content. This read does **not** attest that an Account-retained numeric tenant key has the same identity as a numerically similar Game Design key. The separate `ResolveLegacyAccountTenantAssociation` read returns that cross-owner association only when a signed, owner-approved migration manifest has been applied and its exact source tuple still reads back. It is limited to the verified, same-namespace `account-tenant-migrator` workload identity; ordinary Account and other service peers are denied. It returns the immutable operation, approval, signature, digest, and retained-source evidence with the mapping, and denies absent or contradictory rows. Account's own retained-row verification and mapping readback are still required before it may use the UUID, and neither read itself grants membership admission. The [multi-tenancy identity bridge](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge) owns the target contract; [Game Design operations](./operations.md#legacy-tenant-association-migration) records the controlled migration sequence and current proof limits. + +**Implementation status:** Current Game Design data does not include a stable tenant slug or a proved cross-owner Account legacy-key association, and no current player-facing selector resolution is claimed. The owner-local UUID source/read is being introduced as a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. + ## Official Hosted Creator Mutation Gate For official hosted deployments, every creator-intent content-bearing mutation enters the Game Design boundary only after the Account-owned currentness/evidence authority in [Account Service API Contracts](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) has been evaluated for the tenant's Creator Party, identified operator, and hosted-terms scope under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). This applies before the first persisted Draft and before later authoring/revision, asset, template, plugin, and publication writes. The acting account's current tenant authorization is a separate conjunct; Gateway/UI checks are advisory. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index a48b8f3729..63de588fa5 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -28,6 +28,26 @@ The target publication boundary treats object-store export as a durable candidat ## Local Development Notes +### One-shot migration startup prerequisites + +The Entity baseline and legacy tenant-association Jobs are mutually exclusive one-shot modes. Set only the intended `FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED` or `FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED` flag. Each Job requires the effective `spring.flyway.enabled` property to be explicitly `false`; startup rejects a missing, true, or invalid value before the Spring context is refreshed. Ordinary Game Design service startup retains its normal Flyway behavior. + +Before deploying a Game Design image that includes the canonical tenant identity migration, the Game Design operator must inventory and read back Flyway history for any previously applied draft canonical-identity V30. The identity migration now runs as V30.1 after the retained V30 baseline-lock migration and before V31 associations. A history row whose version or checksum conflicts with the reviewed migration remains blocked pending an explicit database recovery decision; do not rewrite Flyway history, enable out-of-order or baseline repair, infer data, or bypass migration validation automatically. + +### Legacy tenant association migration + +**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30.1 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace, dedicated `game-design-tenant-migrator` service account and certificate, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC/identity and startup-mode tests execute, and the Docker-free V30/V30.1/V31 uniqueness/order test passes against the service migration resources. The V31 PostgreSQL test executed and passed in hosted CI on a preceding head, but the newly composed migration sequence has not executed against PostgreSQL locally. No real signed manifest, Job deployment, retained-row set, or live readback has been proved. + +For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30.1 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. + +Separately deploy the reviewed V31 schema migration and independently verify its readback before `apply`; missing required storage fails application rather than triggering automatic schema repair. Neither `preflight` nor `apply` runs Flyway; the rendered Job explicitly disables it for every mode. A successful signature-and-namespace-only `preflight` does not verify database schema readiness or replace that separate readback prerequisite. + +Each mode requires its own fixed database Secret and authenticated PostgreSQL role: `preflight` uses `firemud-game-design-tenant-preflight-db` as `firemud_game_design_tenant_preflight`, and `apply` uses `firemud-game-design-tenant-apply-db` as `firemud_game_design_tenant_apply`. Both roles may connect only to the selected database; only `apply` may use `game_design_service`. `preflight` verifies the signature and exact namespace only; it performs no owner-table SQL and must not receive schema or table grants. `apply` receives only `SELECT` on the required identity/provenance columns of the Game Design `game` source table and `SELECT`/`INSERT` on the required operation and association fields in `legacy_account_tenant_association_operations` and `legacy_account_tenant_associations`. Neither mode needs `UPDATE`, `DELETE`, sequence, DDL, or lock-function privileges. These credentials are separately provisioned operator inputs, not shared bootstrap, application, or baseline credentials; a missing mode Secret must fail closed, with no optional fallback or chart-created credential. This follows the [Secret Delivery Boundary](../../system-architecture-security.md#secret-delivery-boundary) and [per-service migration ownership](../../system-architecture-database-migrations.md#per-service-organization). + +Before enabling the ordinary-disabled Job, the trusted database operator must provision each role without `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION`, or `BYPASSRLS`, ensure it is not `INHERIT` and has no inherited role memberships, and grant no application-object ownership or unrelated-schema access. Independently read back effective memberships, required grants and prohibited grants, and verify that each Secret-authenticated connection is the exact expected role. Retire the scoped role and Secret after the operation and its recovery window. A rendered Job, Helm check, or role-name assertion is not live grant, Secret-authentication, or PostgreSQL readback proof. + +The chart's `previewStack.tenantAssociationMigration.gameDesign` values are disabled by default. A trusted operator supplies an immutable Game Design image digest, exact namespace, stable run ID, mode, signed-manifest Secret and trusted-key Secret. Explicitly issue and verify the stable `firemud-grpc-game-design-tenant-migrator` identity using `ensure-standalone-transport-certificates.sh --game-design-tenant-migrator` and `--verify-game-design-tenant-migrator` before enabling the Job; the ordinary Game Design certificate is not a fallback. This dedicated certificate is a workload attestation guard, not an outbound owner-read credential. The Job has no Kubernetes API token or ingress and only DNS/Postgres egress; no ordinary Helm release creates it. Disable the Job after use and retire its exact certificate and Secret through the trusted operator boundary. A rendered Job is not executed migration proof: the live certificate, trusted Secrets, actual manifest, PostgreSQL readback and Account import still require deployment proof. Do not describe this path as an applied data migration until those checks execute. + ### Historical Entity digest baseline migration Enumeration reports retained Entity full-version v1 baselines that resolve to a script-only Version as `BLOCKED_SCRIPT_ONLY`, not as migratable full versions. Exact preflight and migration continue to reject those scopes with `VERSION_SCOPE_MISMATCH`; enumeration neither repairs the anomalous row nor changes its provenance. @@ -40,7 +60,7 @@ Before invoking a Job, verify the exact Kubernetes context and namespace, the au The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest, captures the non-DRAFT Version's state epoch, then locks the Version row and requires both non-DRAFT state and the same epoch in the transaction that performs the guarded baseline update and audit insertion. A lifecycle transition during the external digest read therefore fails closed before either write, even if the Version returns to Published. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. -Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and both V29 and V30 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. +Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and V29, V30, and V30.1 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 7eb6075e4c..969bf1d6a8 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -48,7 +48,7 @@ The following contract decisions are mandatory and resolve cross-document ambigu - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. - **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; each retained entry includes `eventId`, the canonical event digest, `sourceScope`, the complete applicable `authorityTuple`/`issuanceFence`, and the relevant event payload evidence. When a duplicate at or below the watermark falls outside that window, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)` and compare the supplied evidence for exact equality. Matching evidence is accepted as a no-op; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed; reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. -- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. The matching checkpoint is `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. +- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: , sourceEventId, sourceEventDigest}`. Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint omits event ID and digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. - **Membership event continuity** – Membership changes use only `account:auth-authority:v1:membership//`. Each event names `outboxStreamKey`, `sourceScope` (`membership//`), `outboxSequence`, `eventId`, the complete applicable `authorityTuple`/`issuanceFence`, and the Account snapshot's `accountId`, `tenantId`, `membershipVersion`, membership payload, admission flag, and `callerBoundAuthorityInvalidated` result. `sourceScope` must decode to `outboxStreamKey`; each consumer stores a `watermark` and event identity/digest per exact stream and marks delivery `contiguous` only when the next sequence is `watermark + 1` (with first-stream initialization from the Account checkpoint). A duplicate at or below the watermark is valid only when all evidence matches; a same-sequence conflict quarantines the affected scope. A higher sequence is a gap only within that same stream; unrelated streams do not advance or gap this watermark. Conflicts, non-contiguous delivery, missing or mismatched tuple/checkpoint evidence, or an unresolved membership-version/generation pair stop affected admission and reconnect/validation until exact Account reconciliation proves coverage; unavailable reconciliation returns retryable `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence is denied/revoked. - **Authority validation outcomes** – A registry, lease, gameplay binding, token-identity fence, Account authority source, or authority-projection freshness fence that cannot be reached or times out is a retryable `AUTH_UNAVAILABLE` / HTTP 503 condition; this includes runtime membership-authority reads. It does not revoke the client's authentication and no cached authority may authorize the failed operation. Reachable missing, malformed, expired, revoked, stale, regressed, or mismatched evidence is an authentication failure (`AUTH_SESSION_REVOKED` or the specific invalid-token outcome) and requires reauthentication. Registry presence or absence never overrides this classification; membership-authority failures use these same availability-versus-denial rules and do not introduce a second canonical error. - **Tenant authority-generation scope** – `session:auth:generation:tenant:` applies by default to tenant-scoped regular and gameplay-affecting operations. Only the closed route-class allowlist in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#explicit-route-class-generation-allowlist) may omit the target tenant generation. The `billing_safe_tenant` class intentionally omits that target-tenant generation only under this closed exception; it still requires issuer/account and caller-bound membership generations plus a live `tenantAdmin` check. `cross_tenant_support_safe` requires issuer/account generations, a live `support` role without elevation or an explicitly allowed `platformAdmin` role with `privileged_control` backed by independent TOTP, and global token scope; and `cross_tenant_billing_safe` requires issuer/account generations, a live `billingAdmin` or explicitly allowed `platformAdmin` role, global token scope, and `privileged_control`. None of these routes may use cached authorization, and no newly named route class inherits the allowlist. @@ -57,6 +57,7 @@ The following contract decisions are mandatory and resolve cross-document ambigu - **JWT claim contract** – Services must validate a strict JWT claim profile (required claims and audience per token profile), not only signature plus ad-hoc fields. Registry-backed profiles carry the complete `authorityTuple` and positive `issuanceFence` with the exact nested names above. A field marked `Absent` by its profile is omitted, not encoded as an empty string, null, map, or list; an empty map/list is valid only when that profile declares the field present and its value is empty. `control-ui` must include `scopedRoles` as `{}` when empty; omission is rejected. Its `tenantAuthorityGeneration` keys equal the non-empty scoped-role tenant keys whose allowed routes require target-tenant authority, while its independent `membershipAuthorityGeneration` and `membershipVersion` keys equal the caller-membership tenants needed by the token's allowed route classifications, including a `billing_safe_tenant` key that deliberately has no target-tenant authority entry. Explicitly unscoped profiles use empty maps/lists only where their profile declares those fields present, never absent or fabricated scope values. - **Authority tuple comparison** – Every applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, exact tenant and membership map entry, private-realm `grantVersion`, `accountSecurityCutoff`, and `tenantBillingCutoff` is compared as part of one tuple. `membershipVersion` is a separate current/stored membership projection check and is never substituted for `membershipAuthorityGeneration`; a tuple, cutoff, fence, or membership mismatch fails closed. - **Internal gameplay delegation boundary** – Gameplay services authenticate the concrete mTLS workload identity, enforce an exact method-level caller allowlist, and validate a typed `PlayerExecutionContext` against request and domain scope. +- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; an exact retry recovers the same bounded exchange result, while changed binding or fence evidence fails closed. - **No universal player attestation** – Routine gameplay delegation does not use signed per-action player attestations or a replay cache. Mutation replay is controlled by the owning command/effect/request idempotency contract. - **Route classification governance** – Protected routes must be classified in the shared route matrix document and enforced through middleware annotations/interceptors; behavior must not rely on per-service ad-hoc interpretation. - **Gameplay session ownership** – Game Session owns gameplay binding records, the atomic monotonic binding CAS, and bounded secondary indexes that map gameplay bindings by the target uniqueness key `{tenantId, playableStateNamespaceId, characterId}`, account/tenant scope, and tenant scope so takeover, reconnect, and revocation do not require scans. Server-derived `playableStateScope` and binding values/evidence retain `{sessionId, gameInstanceId, bindingGeneration}` as locally appropriate. Account owns the admission decision and exact-binding lease only; Account finalization commits lease/decision evidence and never creates, deletes, or mutates Game Session bindings or indexes. Orphan evidence from Account reconciliation becomes a durable cleanup request that Gateway and Game Session consume under their respective edge and gameplay fences. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b506679096..f8e04c767c 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -258,10 +258,10 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `DeleteAccount` (`DELETE /accounts/{accountId}`) | `account_scoped` | Current REST and direct service entries deny with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before mutation, after the route's subject or explicit platform-admin check. The target route additionally requires complete billing/provider/transfer clearance and the ADR 0043/`DATA-01` pending-deletion and retention workflow; it is not enabled by the old subscription-only precondition. | | Account Service | `ExportAccount` (`GET /accounts/{accountId}/export`) | `account_scoped` | **Status: `current_openapi_operator_surface`; synchronous Account/profile-local REST read only, not a second target operation.** The legacy account-ID gRPC export denies before data access. Target RPC semantics are protocol-equivalent to the sole canonical `POST /accounts/{accountId}/exports` route. The current local response and legacy `platformAdmin` override are known drift; the target canonical path is caller-subject-only. | | Account Service | `LinkExternalAccount` (`POST /accounts/{accountId}/external`) | `account_scoped` | **Target-only; currently unavailable.** Do not expose or advertise the current tenant-scoped caller-asserted scaffold. The target is the globally bound flow defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), and requires server-verified provider authorization plus recent ordinary reauthentication before it becomes routable. | -| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and private/playtest grant and entitlement enforcement are not complete. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | +| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and lifecycle-qualified grant authority is unavailable. Fresh and cached-success private/playtest issuance remain denied until that grant authority exists; a retained four-field grant row does not authorize these targets. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | -| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | +| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus current Account-issued `game-session-account-delegation` authority with audience `account-service` and validated typed player/target context. Credential-bearing `LOGIN` obtains that private token from Account authentication; bare first-party `LOGIN` requires the separate Account-owned one-use exchange over proved committed connect issuance and verified signed context. Gateway context or a connect-token `jti` alone does not authorize the read, and Game Session never passes an end-user token as a substitute. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); the RPCs remain denied until the producer and consumer proof is complete. | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index d284008ad4..c919b08e8a 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -28,6 +28,7 @@ Current Game Session bootstrap/reconnect context remains on the implementation-l - **Hosted creator party (`creatorPartyId`)** – An Account-owned party reference for official hosted creator content and terms acceptance. It is not a login identity, JWT role, billing wallet, tenant, or platform determination of copyright ownership; community self-hosting does not use this official-hosted party model. - **Tenant (`tenantId`)** – A hosted game world or project. Each tenant represents one game created on the platform and may have one or more running game instances. Game Design owns tenant content and `tenantId`-scoped workflows, while Account owns the tenant's current Creator Party association, party-transfer authority, referenced party, and acceptance authority for official hosting. A party change follows the explicit Account-owned transfer boundary in ADR 0180 and is not inferred from membership, display name, or billing owner. - **Tenant slug (`tenantSlug`)** – A stable, human-friendly identifier owned by the Game Design Service. It selects the tenant in the player-facing lobby flow (`WORLDS` / `REALMS` / `CHARS` / `PLAY`) and is resolved server-side to `tenantId`; an authored-world selection additionally uses the tenant-scoped `worldSlug` under that resolved tenant. Slugs are selectors, not authority: services and persistence models continue to use `tenantId` as the authoritative tenant identifier, and any direct slug is re-resolved and reauthorized against current catalog/pointer authority at use time. See [ADR 0168: Snapshot-Bound Lobby Selectors and Stable Realm Identity](./decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md) for the current selector and slug-stability authority; [ADR 0005](./decisions/adr-0005-tenant-identifiers-in-gameplay-protocol.md) records the superseded historical decision. + - **World slug (`worldSlug`)** – A stable tenant-scoped selector for one authored world inside the tenant/game. It is resolved only together with `tenantId` and is paired with `realmSlug` by the realm catalog and admission-pointer contract. It is not an alias for `tenantSlug`, does not identify a tenant across the platform, and must not be inferred from display metadata, `realmSlug`, or `gameInstanceId`. - **Realm identity (`realmId`)** – Every durable realm has an opaque UUID `realmId`; its stable `realmSlug` is unique within the tenant and resolves to that identity. Selectors remain direct stable `tenantSlug`/`worldSlug` values, while `realmId` is the durable identity used by the catalog and admission pointer after selector resolution. - **Game instance (`gameInstanceId`)** – A specific running instance of a tenant’s world, keyed as described in [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md#version-activation--rollback). Runtime APIs and disposable instance-data keys include `gameInstanceId` explicitly; durable playable state that survives replacement additionally carries the stable `playableStateNamespaceId` and active-instance authorization. @@ -42,6 +43,16 @@ Current Game Session bootstrap/reconnect context remains on the implementation-l - **Target auth token session** – A short-lived issued-token registry record (`session:auth:token:`) backing a revocable JWT for meta/control or admission APIs, as described in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md). Current Account credential-login sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key instead. - **Control-plane browser session** – A front-end admin/creator UI session that holds short-lived JWTs in memory; target server-side revocation relies on auth token sessions, while current Account authentication retains the legacy session keys above. These are distinct from gameplay sessions and are described in the Frontend Architecture and Authentication designs. +### Canonical Identity and Retained-Key Bridge + +Game Design issues and persists the canonical opaque UUID `tenantId` and owns its stable `tenantSlug` selector. Issuance is a durable owner transaction, not a conversion of a numeric key, an interpretation of UUID bits, or a slug-derived value. An exact owner read must return the same persisted UUID and the source/selector provenance; absence, ambiguity, or changed source binding is not a tenant identity. A retained Game Design game row can be assigned a UUID with provenance naming that exact row and its former Game Design tenant key. That assignment by itself does not prove that a numerically similar Account tenant key denotes the same tenant. + +Account issues and persists a separate canonical UUID `accountId` for each global account while retaining private numeric row keys. Its retained account mapping is one-to-one and records the exact Account row and assignment provenance. For retained membership, JOIN, receipt, and audit rows, Account preserves the original numeric evidence and adds a separate one-to-one bridge to the Game Design-issued tenant UUID only after an authenticated Game Design owner assertion establishes the exact legacy Account tenant-key association and its provenance. Neither a matching decimal string, a game row ID, a default tenant value, nor a guessed slug is that assertion. The owner assertion and Account bridge must be durably readable back and must reject duplicate UUID claims, one legacy key mapped to multiple UUIDs, one UUID mapped to multiple legacy keys, and evidence changes on retry. Unmapped or ambiguous retained rows remain non-admitting and may not be resolved by selecting an arbitrary candidate. + +For retained rows without another authoritative association source, that owner assertion is an explicit, one-time, audited migration manifest. Game Design's tenant owner signs a versioned, length-framed manifest binding the exact deployment namespace, stable operation identity, owner approval/reference, former Game Design tenant key, Game Design source row, issued UUID, Account numeric tenant key, and Account's retained-source evidence digest. Game Design verifies the trusted signer and exact former-key-to-UUID source before storing an immutable, one-to-one assertion; Account obtains it only from the authenticated Game Design workload read, recomputes its own retained-row evidence, then stores and reads back its immutable local mapping. Exact retries must return the same evidence, while missing, conflicting, duplicate, changed, or ambiguous pairs fail closed. Manifest approval establishes identity association only: it does not activate a legacy membership, create an authority stream, grant admission, or relax the disabled runtime membership RPC. + +At an Account-to-Game Session membership read, both logical IDs must resolve through these owner mappings and be bound to the verified caller, selected target, authority generation, stream checkpoint, and returned membership state in one fenced snapshot. Mapping presence alone neither activates retained membership nor proves a never-committed sequence-zero stream. The runtime membership RPC remains denied until the owner read and consumer exact-binding proof are complete. + ### Authority Generations Across Tenant States Account Service owns the issuer, account, tenant, and caller-bound membership authority generations and their projections. The exact global-role branches, route-class exceptions, target-tenant generation predicates, and assurance requirements are canonical in the [Authorization Route Matrix](./system-architecture-authz-route-matrix.md#classification-rules). Multi-tenancy's local consequence is that no role or route may use cached authorization, infer tenant access from a global role, or let a new route class inherit an exception implicitly. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 4cbd9c433f..fc50fb9212 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -59,11 +59,25 @@ Entry format: - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. +- `2026-09-26`: Review status refused a shared private allocation record + - Context: during #2873 implementation, `dev-tools/pr-review status --pr 2873` returned `review allocation contains fields outside the private schema` before review intake. + - Observation: the shared `2818` review allocation contains historical `stop_*` and retained-ambiguity fields that this worktree's `ReviewAllocation.from_dict` does not recognize. The controller could not report current review state; no review was requested or allocation edited. This is a cross-worktree private-state/schema mismatch, not evidence that #2873 has a review allocation. + - Expected pattern: reconcile the shared record against the controller version that wrote it with the owning operator before CodeRabbit intake; do not bypass the controller, delete private evidence, or infer review eligibility from GitHub's visible state alone. + - `2026-09-26`: One-shot certificate issuance and readback require separate proof - Context: the Entity baseline migrator needs a short-lived dedicated client identity without giving its certificate writer general Secret-read or deletion privileges. - Observation: a leaf verifying against the CA bundled in the same Secret is only self-consistent; it does not show that the namespace trusts that CA, and static issuance tests do not show the live Entity server accepts the identity. - Expected pattern: keep issuance opt-in and narrowly admitted, verify the projected leaf and chain against the namespace's independent trust projection under a separately authorized reader, then report live served-mTLS acceptance and later identity retirement as distinct proof. +- `2026-09-26`: PostgreSQL identity migrations need separate jOOQ and runtime proof + - Context: Account and Game Design added UUID identity-source migrations while preserving numeric retained rows. The configured community jOOQ DDL parser rejected `GENERATED ALWAYS AS` and some grouped `ALTER COLUMN`/PostgreSQL function syntax, even though those are database constructs. + - Observation: replacing Account's generated source column with a trigger-bound immutable column and isolating Game Design's PostgreSQL-only DDL behind the existing jOOQ-ignore markers let schema generation proceed. Local Testcontainers cases compiled but skipped without Docker, so parser success is not PostgreSQL migration execution. + - Expected pattern: run jOOQ generation, Flyway numbering, and focused Java tests locally; keep a separate exact-head PostgreSQL migration/readback gate on a runner with Docker, and report any skipped integration case as unproved rather than green runtime evidence. + +- `2026-09-26`: Standalone Flyway migration fixtures must reproduce JDBC and placeholder configuration + - Context: #2873's Account tenant-association PostgreSQL test passed local compilation but skipped without Docker. Its first hosted run could not find an inserted table because a new `?currentSchema=` was appended to a Testcontainers JDBC URL that already carried a query string. After preserving the existing separator, the next run reached the later saga migration and failed because the standalone Flyway invocation omitted `${serviceSchema}`. + - Expected pattern: preserve existing JDBC URL parameters when adding a schema selector, and supply the same Flyway placeholders for both target-version setup and subsequent full migration. Treat each hosted failure as fixture evidence until the exact database case executes and passes; local compilation is not that proof. + - `2026-09-26`: Necessary procedural migration preflights may use jOOQ ignore markers - Context: Account V25's duplicate-detection preflight requires a PostgreSQL `DO` block and wraps it in `-- [jooq ignore start]` and `-- [jooq ignore stop]` markers. - Observation: this qualifies the 2026-09-20 expected pattern: declarative constraints remain preferred when sufficient, but a necessary procedural preflight can be excluded from jOOQ parsing while retaining separate PostgreSQL migration proof. @@ -222,3 +236,8 @@ Entry format: - Observation: an active watcher does not guarantee prompt adjudication. Its reassuring handoff wording cannot replace checking the attributable result and raw findings. - Expected pattern: consume terminal review evidence, adjudicate it, and publish the canonical checkpoint before returning to integration work. Keep CI repair independent rather than postponing completed review reporting. - Outcome: review `5398994837` was recorded as 5 found / 4 accepted / 1 routed before implementing its accepted batch; the inherited Account observation has a canonical target route. + +- `2026-09-30`: Verify a PR's remote head branch before publishing from an isolated worktree + - Context: #2873 was reconciled in a local preparation branch whose name differed from the PR head branch; an initial push mistakenly named #2880's branch as its destination. + - Observation: Git rejected that push as non-fast-forward, so no remote branch changed. The local commit was then pushed to #2873's verified `headRefName`. + - Expected pattern: read the live PR `headRefName` and exact remote head immediately before each push from an isolated branch; use the verified destination, and treat a non-fast-forward rejection as a stop-and-recheck signal rather than forcing it. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 3507b9b6db..ab338d4b7b 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30.1 assigns each retained `game` row a unique UUID with immutable row/former-key provenance after the V30 baseline-lock migration, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on a preceding head. The Docker-free V30/V30.1/V31 uniqueness/order and startup-mode regressions pass, and the combined local Account/Game Design service checks and boot-JAR packaging pass with cached/up-to-date results disclosed. Local PostgreSQL tests skip without Docker, so the newly composed database sequence and live consumer boundary remain unproved. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. + +The opt-in migration Jobs require separately provisioned, mode-specific database Secrets and least-privilege PostgreSQL identities as described in [Account operations](../../architecture/microservices/account-service/operations.md#legacy-tenant-association-import) and [Game Design operations](../../architecture/microservices/game-design-service/operations.md#legacy-tenant-association-migration). Existing Helm, role-name, certificate, and focused startup proof does not establish live effective grants or the role authenticated through each Secret; operator readback and deployed operation evidence remain outstanding. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. 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 fb84ad8fdf..6d534ed630 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,8 +22,16 @@ Reconnect/context persistence is partial: private retained-context replay is cur Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. +The current Unit 1B draft adds Account-owned provisional JOIN/reactivation transition receipts, separate from the canonical authority outbox. A `JOINED` recovery readback requires the matching operation, membership, receipt, and audit evidence; event-free `ALREADY_ACTIVE` requires matching positive prior receipt history. Legacy active/inactive rows without that receipt, and absent rows with retained history, fail closed rather than restart at sequence one. Forward V41 guards receipt updates/deletes while preserving legitimate inserts and stream-head advancement; V40 remains unchanged. The receipt is not a complete authority tuple, fenced runtime snapshot, or sequence-zero absence proof. All 12 focused PostgreSQL integration cases skipped locally without Docker, including the immutability/append and retained minimized-audit negatives; their database behavior and lost-acknowledgement/concurrency remain unproved until executed. + Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. Local focused manifest, gRPC, certificate/admission, Helm-render and Account negative tests executed; Game Design's new V31 PostgreSQL case executed and passed in hosted CI, while Account's new V30 import case has reached Flyway fixture setup but lacks a passing hosted database run after its latest correction. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. + +The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and records missing non-public grant internally as `REALM_ACCESS_DENIED`; hidden/non-public definitive denials remain externally projected to generic selection guidance rather than revealing the target. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. + +The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact canonical authority stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; the provisional transition receipt does not prove that condition, and no current response or consumer provides it. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. + Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. The Unit 1B child removes `PLAY`'s synthetic account/name/hash fallback and requires a persisted account-roster actor after admission checks, with focused foreign-owner, malformed-row, absent/ambiguous roster, and no-mutation negatives. That Entity list is not yet namespace/policy-qualified, and Account's runtime reads still deny before data access; `CHARS` now returns unavailable before Entity access. These are safety corrections, not a working complete actor-entry path. Typed Account caller/target authority, stable namespace and policy snapshot, descriptor/template resolution, zero/one/many entry behavior, and fork-local copy proof remain ordered pre-v1 work and do not upgrade AA-2.1 status. @@ -62,7 +70,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | -| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | The current correction rechecks public target eligibility, membership lifecycle/admission and entitlement before returning the exact cached token; private cached replay remains denied, and no retry remints or extends a token. This is not a durable immutable issuance baseline, membership-version/generation/fence comparison, complete same-snapshot authority proof or ambiguous-ack protocol. Current Game Session runtime-read denial separately prevents replay alone from admitting gameplay. Prove those remaining issuer and consumer boundaries before admission activation; pointer-cutover retry expectations alone are not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | | Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | @@ -80,7 +88,7 @@ These links add decision provenance only; they do not upgrade player-access or s | 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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.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); [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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.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) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Local producer proof covers minimizing payload after a verified terminal receiver receipt while retaining audit identity and digest; live `CreateLogEvent` currently returns `UNAVAILABLE` and Account delivery is unscheduled, so this is not live delivery proof and new/outstanding rows remain `PENDING`. Historical rows with unknown projection provenance are not promoted, and safe-watermark, hold, reference, finite-retention, PostgreSQL runtime, and retained-row disposition/readback proof remain open. 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 establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | +| `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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.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); [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); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Local producer proof covers minimizing payload after a verified terminal receiver receipt while retaining audit identity and digest; live `CreateLogEvent` currently returns `UNAVAILABLE` and Account delivery is unscheduled, so this is not live delivery proof and new/outstanding rows remain `PENDING`. Historical rows with unknown projection provenance are not promoted, and safe-watermark, hold, reference, finite-retention, PostgreSQL runtime, and retained-row disposition/readback proof remain open. 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 establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. V29 adds immutable account UUIDs while retaining numeric primary keys and explicit migration/repository provenance; its 13 PostgreSQL migration/immutability cases compiled but were all skipped because Docker was unavailable, and it neither changes numeric external identity nor maps tenant UUIDs. Lifecycle-state retention is 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); [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) | [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) | [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. Fresh connect-token issuance revalidates pointer/visibility/membership inputs, but a cached-success replay can return before fresh entitlement, membership, or pointer reads; current-authority and postcondition revalidation remain unproved. The explicit JOIN operation validates a server-issued scope and caller, rereads Game Session routing/catalog/pointer evidence before its Account transaction, and binds a version-1 digest to caller/scope and policy evidence; membership, stored outcome, and tenant audit outbox row persist atomically, but exact target/catalog/pointer validity is not guaranteed through commit and the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks the subscription row but not its joined billing-owner Account; JOIN locks the caller Account and operation row. Terminal replay's remote scope/target/entitlement reads occur outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting stored outcome, while the PostgreSQL row-lock regression was Docker-skipped. Global-only registration creates no admitting membership. Expired unreferenced connect scopes are swept, and V27's restrictive FK preserves scopes referenced by PENDING or terminal JOIN records and fences racing intent inserts. The bounded worker is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence; an expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, and the worker does not resubmit the bearer-bound request or terminalize from expiry, attempt limit, absent evidence, or uncertainty. Exact replay remains fenced to caller, target, intent, and retained policy digest. New/outstanding audit rows remain `PENDING` because live `CreateLogEvent` is `UNAVAILABLE` and delivery scheduling is disabled; positive delivery/receipt handling is offline fixture proof, and historical unknown provenance is not promoted. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Runtime membership authority-generation evidence, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec remain incomplete. Game Session omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); fresh caller-bound prior snapshots for the exact current private target receive retryable `AUTH_UNAVAILABLE`, while unbound selectors remain hidden. Account's runtime membership, entitlement, and grant handlers fail closed before reads; text `PLAY` and namespace-qualified `CHARS` remain unavailable, not positive admission proof. Other transactional outboxes, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | @@ -110,8 +118,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established, and valid-route text `PLAY` translates that unavailable RPC into retryable `AUTH_UNAVAILABLE`. -On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`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. Non-public REST realm discovery, character listing, and connect-token issuance fail closed when a legacy four-field grant cannot prove the current lifecycle and state generation; fresh and cached-success private issuance return `REALM_ACCESS_DENIED` without treating a retained four-field row as REST authority. The target lifecycle-qualified, expiring grant authority, atomic membership-generation reread, and cached-success freshness remain unimplemented. Runtime gRPC grant reads fail before Account reads, so text `PLAY` cannot consume a grant result. 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. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). @@ -195,7 +202,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. First-party proofs cover fresh-token enforcement, bare verified-identity login, `PLAY` scope binding, replay/expiry/context/scope failures, screen-buffer restore, and fresh redraw. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, current membership, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and contained export/deletion/recovery boundaries. Every current `DeleteAccount` entry denies before account or financial-row mutation; provider/transfer clearance and retained-data workflow remain successor requirements. Explicit JOIN and its bounded worker are local: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency, direct text-client proof, connect-token membership-version/authority-generation baseline reread, and canonical tenant-role/lifecycle/generation follow-through remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public grant handling, cross-tenant membership enforcement, and contained export/deletion/recovery boundaries. Every current `DeleteAccount` entry denies before account or financial-row mutation; provider/transfer clearance and retained-data handling remain successor requirements. Explicit JOIN and its bounded readback worker are local: `JOINED` requires exact transition receipt and matching version-1 COMMITTED audit receipt/projection evidence; exact prior-history `ALREADY_ACTIVE` is event-free. Expired or uncertain `PENDING` intents remain retryable and nonterminal despite the diagnostic threshold. PostgreSQL lost-acknowledgement/concurrency, direct text-client proof, connect-token membership-version/authority-generation baseline reread, lifecycle-qualified grant authority, and canonical tenant-role/lifecycle/generation follow-through remain partial or unproved. - **Validation record:** The earlier documentation-only gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Current Unit 1B work changes Account/Game Session runtime behavior and tests, so its focused validation and runtime-proof limits are recorded with the owning PRs; Docker-backed and live paths must not be inferred from earlier documentation checks. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 7aa7a22189..3d8fe03599 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -103,7 +103,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` classifies as `WORLD_ACCESS_DENIED`; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` classifies as `WORLD_ACCESS_DENIED`; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity access; complete authenticated snapshot/target/fence evidence and its current containment are tracked in [Player Access and Session](./player-access-and-session.md). - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 823602a7f0..c151b57d71 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for shared runtime, service contr The implementation record below summarizes the shared runtime, service-contract, orchestration, persistence, and workflow boundaries represented by this tracker. It distinguishes live implementation from bounded follow-up work; it does not claim that every future service, runtime consumer, or workflow family has already adopted these conventions. +Account V29 now persists one immutable canonical UUID per Account while preserving the numeric local primary key, with explicit migration/insertion provenance and source-row evidence. The Account repository returns and resolves that UUID using exact source-row readback, while external Account carriers and consumers remain numeric; this does not establish a tenant UUID mapping. `:account-service:spotlessJavaCheck` and the focused `AccountLoginAuthModesTest` executed successfully; the focused `AccountRepositoryIntegrationTest` compiled but all 13 cases, including the V29 retained-row, JOIN-operation, and membership-receipt no-loss proof, were skipped because Docker was unavailable. PostgreSQL runtime behavior is therefore not yet verified. The broader `SF-1.2` capability remains partial and its cross-service UUID convergence is still unproved. + Account V25, Game Session V2, and Automation V2 schema activation now has a bounded quiescence slice: base/hosted workloads use non-rolling replacement, the trusted dev-demo path recognizes migration-bearing pushes, preserves that runtime database, stops the three Account, Game Session, and Automation writer Deployments, and verifies their Pods are absent; ordinary pushes retain the established clean namespace reset. Redispatch classification uses the exact namespace-manager deployed-head annotation and fails before mutation if the head or Git ancestry is unproven. The Game Session and Automation V2 migrations check their known V1 indexes plus service-specific active-claim/data prerequisites before changing indexes; this status does not claim equivalent migration validation for Account V25. Focused PostgreSQL failure-path tests are added but remain unverified until Docker-backed service tests run. Candidate PR previews that change Flyway migrations fail before namespace recreation because their scoped runtime path cannot prove Postgres PVC provenance or query migration history; trusted post-merge deployment is the activation path. Recovery is roll-forward only. This does not complete the separate retained-row identity and cross-instance PostgreSQL proof recorded below. ### Script-transition cross-service handoff diff --git a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh index c0bcd94b32..0146d3019d 100755 --- a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh +++ b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh @@ -27,11 +27,29 @@ elif [[ $# -eq 2 && "$1" == --migrator ]]; then elif [[ $# -eq 2 && "$1" == --verify-migrator ]]; then transport_operation='verify-migrator' namespace="$2" +elif [[ $# -eq 2 && "$1" == --account-tenant-migrator ]]; then + transport_operation='write-migrator' + migrator_identity='account-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-account-tenant-migrator ]]; then + transport_operation='verify-migrator' + migrator_identity='account-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --game-design-tenant-migrator ]]; then + transport_operation='write-migrator' + migrator_identity='game-design-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-game-design-tenant-migrator ]]; then + transport_operation='verify-migrator' + migrator_identity='game-design-tenant-migrator' + namespace="$2" else - echo "usage: $0 [--wait|--migrator|--verify-migrator] " >&2 + echo "usage: $0 [--wait|--migrator|--verify-migrator|--account-tenant-migrator|--verify-account-tenant-migrator|--game-design-tenant-migrator|--verify-game-design-tenant-migrator] " >&2 exit 2 fi +migrator_identity="${migrator_identity:-game-design-baseline-migrator}" + if [[ "$transport_operation" == write || "$transport_operation" == wait ]] && [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then echo "runtime namespace must be canonical pr-N: ${namespace}" >&2 @@ -49,9 +67,14 @@ bridge_certificate="${namespace}-tcp-proxy-bridge" public_hostname="${namespace}.${PREVIEW_DOMAIN}" gateway_dns_name="spring-cloud-gateway-mtls.${namespace}.svc.cluster.local" bridge_uri_san="spiffe://firemud/ns/${namespace}/sa/tcp-proxy-service" -migrator_certificate="${namespace}-grpc-game-design-baseline-migrator" -migrator_secret='firemud-grpc-game-design-baseline-migrator' -migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/game-design-baseline-migrator" +migrator_certificate="${namespace}-grpc-${migrator_identity}" +migrator_secret="firemud-grpc-${migrator_identity}" +migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/${migrator_identity}" +migrator_role="grpc-${migrator_identity}" +migrator_managed_by='entity-baseline-migration' +if [[ "$migrator_identity" == account-tenant-migrator || "$migrator_identity" == game-design-tenant-migrator ]]; then + migrator_managed_by='tenant-association-migration' +fi deadline=$((SECONDS + certificate_wait_timeout_seconds)) write_certificates() { @@ -148,8 +171,8 @@ spec: secretTemplate: metadata: labels: - firemud.dev/managed-by: entity-baseline-migration - firemud.dev/role: grpc-game-design-baseline-migrator + firemud.dev/managed-by: ${migrator_managed_by} + firemud.dev/role: ${migrator_role} firemud.dev/retention: ephemeral annotations: firemud.dev/provenance: cert-manager diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/helm-tenant-association-migration-contract.sh b/dev-tools/tests/helm-tenant-association-migration-contract.sh new file mode 100644 index 0000000000..36bbac8f71 --- /dev/null +++ b/dev-tools/tests/helm-tenant-association-migration-contract.sh @@ -0,0 +1,206 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 - "$ROOT_DIR" <<'PY' +import copy +import pathlib +import subprocess +import sys +import tempfile + +import yaml + +root = pathlib.Path(sys.argv[1]) +chart = root / "k8s/helm/firemud" +sha = "a" * 64 + + +def documents(output): + return [document for document in yaml.safe_load_all(output) if isinstance(document, dict)] + + +with tempfile.TemporaryDirectory() as directory: + temporary = pathlib.Path(directory) + values = temporary / "preview-values.yaml" + subprocess.run( + [ + "python3", + str(root / "dev-tools/hosted/preview/render-preview-values.py"), + str(chart / "values-hosted-shared.example.yaml"), + str(values), + "123", + "pr-123", + "pr-123", + "pr-123.preview.firedevops.net", + "pr-123-deadbeef", + "32000", + ], + check=True, + ) + + def render(name, migration=None): + args = ["helm", "template", name, str(chart), "--namespace", "pr-123", "-f", str(values)] + if migration is not None: + override = temporary / f"{name}.yaml" + override.write_text(yaml.safe_dump(migration), encoding="utf-8") + args += ["-f", str(override)] + return subprocess.run(args, capture_output=True, text=True, check=False) + + def require_failure(name, migration, fragment): + result = render(name, migration) + if result.returncode == 0 or fragment not in result.stderr: + raise SystemExit(f"{name} did not fail closed with {fragment}: {result.stderr}") + + def require_flyway_disabled(args, workload): + expected = "--spring.flyway.enabled=false" + flyway_args = [arg for arg in args if arg.startswith("--spring.flyway.enabled=")] + if flyway_args != [expected]: + raise SystemExit(f"{workload} Job must disable Flyway explicitly, found {flyway_args}") + + def require_flyway_guard_negative_proof(args, workload): + for invalid_args in ( + [arg for arg in args if arg != "--spring.flyway.enabled=false"], + ["--spring.flyway.enabled=true" if arg == "--spring.flyway.enabled=false" else arg for arg in args], + ): + try: + require_flyway_disabled(invalid_args, workload) + except SystemExit: + continue + raise SystemExit(f"{workload} Flyway check accepted a missing or enabled property") + + database_secrets = { + ("account", "evidence"): "firemud-account-tenant-evidence-db", + ("account", "import"): "firemud-account-tenant-import-db", + ("game-design", "preflight"): "firemud-game-design-tenant-preflight-db", + ("game-design", "apply"): "firemud-game-design-tenant-apply-db", + } + + def require_database_credentials(container, service, mode): + if container.get("envFrom"): + raise SystemExit("migration must not import an unrestricted credential bundle") + expected_secret = database_secrets[(service, mode)] + for key in ("FIREMUD_POSTGRES_USER", "FIREMUD_POSTGRES_PASSWORD"): + entries = [entry for entry in container["env"] if entry["name"] == key] + expected = { + "name": key, + "valueFrom": { + "secretKeyRef": {"name": expected_secret, "key": key, "optional": False}, + }, + } + if entries != [expected]: + raise SystemExit(f"{service}/{mode} must require its dedicated {key} Secret key") + + def require_database_guard_negative_proof(container, service, mode): + for replacement in ( + {"name": "firemud-secret", "key": "FIREMUD_POSTGRES_USER", "optional": False}, + {"name": "firemud-game-design-baseline-writer-db", "key": "FIREMUD_POSTGRES_USER", "optional": False}, + {"name": database_secrets[(service, mode)], "key": "PASSWORD", "optional": False}, + {"name": database_secrets[(service, mode)], "key": "FIREMUD_POSTGRES_USER", "optional": True}, + {"name": database_secrets[(service, mode)], "key": "FIREMUD_POSTGRES_USER"}, + None, + ): + invalid = copy.deepcopy(container) + credential = next(entry for entry in invalid["env"] if entry["name"] == "FIREMUD_POSTGRES_USER") + credential["valueFrom"]["secretKeyRef"] = replacement + try: + require_database_credentials(invalid, service, mode) + except SystemExit: + continue + raise SystemExit(f"{service}/{mode} credential guard accepted {replacement}") + + disabled = render("tenant-migration-disabled") + if disabled.returncode: + raise SystemExit(disabled.stderr) + forbidden_names = {"game-design-tenant-migrator", "account-tenant-migrator"} + if any( + item.get("metadata", {}).get("name") in forbidden_names + or item.get("metadata", {}).get("name", "").startswith(("game-design-tenant-", "account-tenant-")) + for item in documents(disabled.stdout) + ): + raise SystemExit("ordinary release rendered tenant-migration resources") + + def migration_for(game_design_mode, account_mode): + return { + "previewStack": { + "tenantAssociationMigration": { + "gameDesign": { + "enabled": True, + "mode": game_design_mode, + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/game-design-service@sha256:{sha}", + "signedManifestSecretName": "tenant-manifest-approved-42", + "trustedKeysSecretName": "tenant-owner-public-keys", + }, + "account": { + "enabled": True, + "mode": account_mode, + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/account-service@sha256:{sha}", + "legacyTenantId": "41", + }, + }, + } + } + + def validate_rendered_jobs(name, migration, modes): + result = render(name, migration) + if result.returncode: + raise SystemExit(result.stderr) + by_kind_name = { + (item.get("kind"), item.get("metadata", {}).get("name")): item + for item in documents(result.stdout) + } + for service, mode in modes: + workload = f"{service}-tenant-migrator" + job = by_kind_name[("Job", f"{service}-tenant-{mode}-approved-42")] + pod = job["spec"]["template"]["spec"] + if pod["serviceAccountName"] != workload or pod["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} Job did not bind the dedicated tokenless service account") + if by_kind_name[("ServiceAccount", workload)]["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} service account mounts an API token") + secret = next(volume["secret"]["secretName"] for volume in pod["volumes"] if volume["name"] == "grpc-identity") + if secret != f"firemud-grpc-{workload}": + raise SystemExit(f"{workload} reused an ordinary service certificate") + require_flyway_disabled(pod["containers"][0]["args"], workload) + require_flyway_guard_negative_proof(pod["containers"][0]["args"], workload) + require_database_credentials(pod["containers"][0], service, mode) + require_database_guard_negative_proof(pod["containers"][0], service, mode) + policy = by_kind_name[("NetworkPolicy", workload)]["spec"] + if policy["ingress"] != [] or set(policy["policyTypes"]) != {"Ingress", "Egress"}: + raise SystemExit(f"{workload} has an unexpected ingress allowance") + destination_apps = { + selector["podSelector"]["matchLabels"]["app"] + for rule in policy["egress"] + for selector in rule["to"] + if "podSelector" in selector and "app" in selector["podSelector"].get("matchLabels", {}) + } + expected = {"postgres"} | ({"game-design-service"} if service == "account" and mode == "import" else set()) + if destination_apps != expected: + raise SystemExit(f"{workload} egress targets differ: {destination_apps}") + + validate_rendered_jobs( + "tenant-migration-read-only", + migration_for("preflight", "evidence"), + (("game-design", "preflight"), ("account", "evidence")), + ) + migration = migration_for("apply", "import") + validate_rendered_jobs( + "tenant-migration-writing", + migration, + (("game-design", "apply"), ("account", "import")), + ) + + wrong_namespace = copy.deepcopy(migration) + wrong_namespace["previewStack"]["tenantAssociationMigration"]["account"]["targetNamespace"] = "pr-999" + require_failure("wrong-namespace", wrong_namespace, "targetNamespace must match") + mutable_image = copy.deepcopy(migration) + mutable_image["previewStack"]["tenantAssociationMigration"]["gameDesign"]["image"] = "game-design:latest" + require_failure("mutable-image", mutable_image, "image must end in @sha256") + no_policy = copy.deepcopy(migration) + no_policy["previewStack"]["networkPolicies"] = {"enabled": False} + require_failure("missing-policy", no_policy, "networkPolicies.enabled=true") + print("tenant association Helm Job render contract passed") +PY diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 9cdc3f7e15..2252ac169b 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1622,6 +1622,8 @@ for workload in publication_workloads: f"object.metadata.name == 'firemud-grpc-{workload}' && " f"object.metadata.labels['firemud.dev/role'] == 'grpc-publication-{workload}'" ) in controller_grants +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert f"firemud-grpc-{migrator_identity}" not in controller_grants def publication_projection_is_allowed(operation, namespace, name, role=None): @@ -1685,6 +1687,10 @@ assert "object.metadata.name == 'dev-grpc-social-groups-service'" in cert_manage assert cert_manager_expression.count( "request.name == 'firemud-grpc-game-design-baseline-migrator'" ) == 2, "migrator Secret must retain only its exact operator-retirement and namespace-controller branches" +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert cert_manager_expression.count( + f"request.name == 'firemud-grpc-{migrator_identity}'" + ) == 1, f"{migrator_identity} Secret admission match must be a single exact branch" for migration_secret_gate in ( "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", @@ -1696,6 +1702,34 @@ for migration_secret_gate in ( "ref.name == request.namespace + '-grpc-game-design-baseline-migrator'", ): assert migration_secret_gate in cert_manager_expression, migration_secret_gate +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + for migration_secret_gate in ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}'", + "object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration'", + f"object.metadata.labels['firemud.dev/role'] == 'grpc-{migrator_identity}'", + "object.metadata.labels['firemud.dev/retention'] == 'ephemeral'", + f"object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-{migrator_identity}'", + "object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer'", + f"ref.name == request.namespace + '-grpc-{migrator_identity}'", + ): + assert migration_secret_gate in cert_manager_expression, migration_secret_gate + assert cert_manager_expression.count( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}'" + ) == 1 + other_identity = ( + "account-tenant-migrator" + if migrator_identity == "game-design-tenant-migrator" + else "game-design-tenant-migrator" + ) + assert ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}' && " + f"object.spec.secretName == 'firemud-grpc-{other_identity}'" + ) not in cert_manager_expression + assert ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}' && " + "object.metadata.annotations['cert-manager.io/certificate-name'] == " + f"request.namespace + '-grpc-{other_identity}'" + ) not in cert_manager_expression assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" not in ( cert_manager_expression.split( "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", 1 @@ -1732,6 +1766,10 @@ assert "request.operation == 'DELETE'" in certificate_namespace_match assert "request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "request.name.startsWith(" in certificate_namespace_match assert "request.name == request.namespace + '-grpc-game-design-baseline-migrator'" in certificate_namespace_match +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert ( + f"request.name == request.namespace + '-grpc-{migrator_identity}'" + ) in certificate_namespace_match assert "request.operation != 'DELETE'" in certificate_namespace_match assert "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "object.metadata.name.startsWith(" in certificate_namespace_match @@ -1769,6 +1807,10 @@ assert "grpc-game-session-service" in certificate_match assert "grpc-social-groups-service" in certificate_match assert "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer" in certificate_match assert "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'" in certificate_match +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert ( + f"object.spec.secretName == 'firemud-grpc-{migrator_identity}'" + ) in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ @@ -1785,6 +1827,8 @@ assert "firemud-grpc-tls" not in controller_non_delete_expression assert "'grpc'" not in controller_non_delete_expression assert "grpc-publication-" in controller_non_delete_expression assert "grpc-account-service" in controller_non_delete_expression +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert f"{migrator_identity}" not in controller_certificate_expression assert "has(object.spec.isCA)" in controller_non_delete_expression assert "object.spec.isCA == false" in controller_non_delete_expression assert "(!has(object.spec.commonName) || object.spec.commonName == '')" in controller_non_delete_expression diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh index daa7e69cd4..3843c2cee2 100755 --- a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh +++ b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh @@ -57,7 +57,7 @@ case " $* " in pr-42-tcp-proxy-bridge) printf '%s' '{"metadata":{"name":"pr-42-tcp-proxy-bridge"},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; - firemud-grpc-game-design-baseline-migrator) + firemud-grpc-game-design-baseline-migrator|firemud-grpc-account-tenant-migrator|firemud-grpc-game-design-tenant-migrator) if [[ -z "${FAKE_KUBECTL_SECRET_JSON:-}" ]]; then echo "migrator Secret fixture is required" >&2 exit 2 @@ -230,6 +230,68 @@ grep -Fq 'did not become key-complete' "$TEMP_DIR/incomplete.err" || { exit 1 } +for migrator_identity in account-tenant-migrator game-design-tenant-migrator; do + runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" + PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" "--$migrator_identity" dev >"$TEMP_DIR/$migrator_identity-issued.out" + runtime_calls="$(tail -n +$((runtime_calls_start + 1)) "$STATE_DIR/calls")" + if grep -Fq 'get secret' <<<"$runtime_calls"; then + echo "$migrator_identity certificate writer read a Secret" >&2 + exit 1 + fi + cp "$STATE_DIR/applied.yaml" "$TEMP_DIR/$migrator_identity-certificate.yaml" +done +python3 - "$TEMP_DIR" <<'PY' +import sys +from pathlib import Path + +import yaml + +root = Path(sys.argv[1]) +for identity in ("account-tenant-migrator", "game-design-tenant-migrator"): + document = yaml.safe_load((root / f"{identity}-certificate.yaml").read_text(encoding="utf-8")) + if document.get("kind") != "Certificate": + raise SystemExit(f"{identity} opt-in did not apply one Certificate") + namespace = document["metadata"].get("namespace") + if namespace != "dev" or document["metadata"].get("name") != f"{namespace}-grpc-{identity}": + raise SystemExit(f"{identity} Certificate name is not stable and namespace-bound") + spec = document["spec"] + if spec.get("secretName") != f"firemud-grpc-{identity}": + raise SystemExit(f"{identity} Certificate does not use its dedicated Secret") + if spec.get("uris") != [f"spiffe://firemud/ns/{namespace}/sa/{identity}"]: + raise SystemExit(f"{identity} Certificate URI SAN is not exact") + if "dnsNames" in spec or spec.get("usages") != ["digital signature", "key encipherment", "client auth"]: + raise SystemExit(f"{identity} Certificate is not URI-only clientAuth") + if spec.get("issuerRef") != { + "name": "firemud-ca-issuer", + "kind": "ClusterIssuer", + "group": "cert-manager.io", + }: + raise SystemExit(f"{identity} Certificate must use the internal ClusterIssuer") + if spec.get("secretTemplate", {}).get("metadata", {}).get("labels") != { + "firemud.dev/managed-by": "tenant-association-migration", + "firemud.dev/role": f"grpc-{identity}", + "firemud.dev/retention": "ephemeral", + }: + raise SystemExit(f"{identity} Secret labels do not match the tenant-migration profile") +PY + +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" --account-tenant-migrator dev >"$TEMP_DIR/account-tenant-migrator-repeat.out" +python3 - "$TEMP_DIR/account-tenant-migrator-certificate.yaml" "$STATE_DIR/applied.yaml" <<'PY' +import sys +from pathlib import Path + +import yaml + +first = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +second = yaml.safe_load(Path(sys.argv[2]).read_text(encoding="utf-8")) +if first["metadata"]["name"] != second["metadata"]["name"]: + raise SystemExit("tenant migrator Certificate name changed on repeat issuance") +if first["spec"] != second["spec"]: + raise SystemExit("tenant migrator Certificate spec changed on repeat issuance") +PY + runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ "$SCRIPT" --migrator dev >"$TEMP_DIR/migrator-issued.out" @@ -299,6 +361,32 @@ if grep -Fq 'tls.key' "$TEMP_DIR/migrator-verified.out"; then exit 1 fi +for migrator_identity in account-tenant-migrator game-design-tenant-migrator; do + openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/$migrator_identity.key" \ + -out "$TEMP_DIR/$migrator_identity.csr" -subj "/CN=$migrator_identity" \ + -addext "subjectAltName=URI:spiffe://firemud/ns/dev/sa/$migrator_identity" \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 + openssl x509 -req -in "$TEMP_DIR/$migrator_identity.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/$migrator_identity.crt" >/dev/null 2>&1 + jq -n \ + --arg name "firemud-grpc-$migrator_identity" \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/$migrator_identity.crt")" \ + --arg key "$(base64 -w0 "$TEMP_DIR/$migrator_identity.key")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":$key,"ca.crt":$ca}}' \ + >"$TEMP_DIR/$migrator_identity-secret.json" + PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/$migrator_identity-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" "--verify-$migrator_identity" dev >"$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq "uri-san=spiffe://firemud/ns/dev/sa/$migrator_identity" \ + "$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq 'namespace-trust-match=true' "$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq 'client-auth-only=true' "$TEMP_DIR/$migrator_identity-verified.out" +done + openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-leaf.key" \ -out "$TEMP_DIR/wrong-leaf.csr" -subj '/CN=wrong migrator' \ -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-service' \ @@ -343,6 +431,25 @@ fi grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ "$TEMP_DIR/wrong-migrator.err" +jq -n \ + --arg name firemud-grpc-account-tenant-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/wrong-leaf.crt")" \ + --arg key "$(base64 -w0 "$TEMP_DIR/wrong-leaf.key")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":$key,"ca.crt":$ca}}' \ + >"$TEMP_DIR/wrong-account-tenant-migrator-secret.json" +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-account-tenant-migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-account-tenant-migrator dev \ + >"$TEMP_DIR/wrong-account-tenant-migrator.out" \ + 2>"$TEMP_DIR/wrong-account-tenant-migrator.err"; then + echo "Account tenant migrator verifier accepted another workload identity" >&2 + exit 1 +fi +grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ + "$TEMP_DIR/wrong-account-tenant-migrator.err" + openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-ca.key" \ -out "$TEMP_DIR/wrong-ca.crt" -subj '/CN=Untrusted test CA' -days 1 >/dev/null 2>&1 if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index 9245b90e3c..a3b566a2c8 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -119,6 +119,16 @@ def check_contract(items: list[dict]) -> None: "object.spec == oldObject.spec", ): require(request, needle, "CertificateRequest boundary") + for identity in ( + "game-design-baseline-migrator", + "game-design-tenant-migrator", + "account-tenant-migrator", + ): + require( + request, + f"owner.name == request.namespace + '-grpc-{identity}'", + f"CertificateRequest {identity} ownership", + ) owner_validation = actual_policies["firemud-trust-bootstrap-certificaterequest"]["spec"][ "validations" ][1]["expression"].rstrip() @@ -134,6 +144,16 @@ def check_contract(items: list[dict]) -> None: "owner.kind == 'Certificate'", ): require(request_subresources, needle, "CertificateRequest subresource boundary") + for identity in ( + "game-design-baseline-migrator", + "game-design-tenant-migrator", + "account-tenant-migrator", + ): + require( + request_subresources, + f"owner.name == request.namespace + '-grpc-{identity}'", + f"CertificateRequest subresource {identity} ownership", + ) subresource_rules = actual_policies["firemud-trust-bootstrap-certificaterequest-subresources"][ "spec" ]["matchConstraints"]["resourceRules"] @@ -167,7 +187,7 @@ def check_contract(items: list[dict]) -> None: )[1].split("(request.operation == 'CREATE' &&", 1)[0] for needle in ( "oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(", - "game-design-baseline-migrator)$')", + "game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$')", "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", ): require(delete_match_branch, needle, "runtime migrator Certificate DELETE match condition") @@ -254,7 +274,7 @@ def check_contract(items: list[dict]) -> None: fail("Certificate status denial message does not describe the allowed callers") require( certificate_validation, - "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator))$", + "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$", "standalone Certificate validation", ) for needle in ( @@ -297,6 +317,42 @@ def check_contract(items: list[dict]) -> None: "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer", "standalone Certificate validation", ) + for identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + require( + certificate_validation, + f"object.metadata.name.endsWith('-grpc-{identity}')", + f"standalone {identity} Certificate name", + ) + require( + certificate_validation, + f"object.spec.secretName == 'firemud-grpc-{identity}'", + f"standalone {identity} Certificate Secret", + ) + require( + certificate_validation, + "object.spec.issuerRef.name == 'firemud-ca-issuer'", + f"standalone {identity} Certificate issuer", + ) + require( + certificate_validation, + f"'firemud.dev/managed-by': 'tenant-association-migration'", + f"standalone {identity} Secret manager", + ) + require( + certificate_validation, + f"'firemud.dev/role': 'grpc-{identity}'", + f"standalone {identity} Secret role", + ) + require( + certificate_validation, + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{identity}']", + f"standalone {identity} Certificate URI", + ) + require( + certificate_validation, + "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", + f"standalone {identity} Certificate usages", + ) issuer = expressions(actual_policies["firemud-trust-bootstrap-ca-issuers"]) issuer_match = actual_policies["firemud-trust-bootstrap-ca-issuers"]["spec"][ @@ -380,5 +436,49 @@ except AssertionError: else: fail("negative mutation changing the CA issuer binding from Deny was accepted") +for identity, other_identity in ( + ("game-design-tenant-migrator", "account-tenant-migrator"), + ("account-tenant-migrator", "game-design-tenant-migrator"), +): + mutation = copy.deepcopy(documents) + mutation_policy = next( + item + for item in mutation + if item.get("metadata", {}).get("name") == "firemud-trust-bootstrap-certificate" + ) + mutation_policy["spec"]["validations"][0]["expression"] = mutation_policy["spec"][ + "validations" + ][0]["expression"].replace( + f"object.spec.secretName == 'firemud-grpc-{identity}'", + f"object.spec.secretName == 'firemud-grpc-{other_identity}'", + 1, + ) + try: + check_contract(mutation) + except AssertionError: + pass + else: + fail(f"negative mutation swapping the {identity} Secret was accepted") + + mutation = copy.deepcopy(documents) + mutation_policy = next( + item + for item in mutation + if item.get("metadata", {}).get("name") == "firemud-trust-bootstrap-certificate" + ) + mutation_policy["spec"]["validations"][0]["expression"] = mutation_policy["spec"][ + "validations" + ][0]["expression"].replace( + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{identity}']", + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{other_identity}']", + 1, + ) + try: + check_contract(mutation) + except AssertionError: + pass + else: + fail(f"negative mutation swapping the {identity} URI was accepted") + print(f"trust-bootstrap issuance contract: {len(documents)} documents, fail-closed bindings verified") PY diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index 86328be330..062cad71f6 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -27,6 +27,9 @@ {{- $gatewayWsTlsTargetPort = required "previewStack.gatewayWsTls.targetPort is required when Gateway WebSocket TLS is enabled" $gatewayWsTls.targetPort }} {{- end }} {{- $entityDigestBaselineMigration := .Values.previewStack.entityDigestBaselineMigration | default (dict) }} +{{- $tenantAssociationMigration := .Values.previewStack.tenantAssociationMigration | default (dict) }} +{{- $gameDesignTenantMigration := $tenantAssociationMigration.gameDesign | default (dict) }} +{{- $accountTenantMigration := $tenantAssociationMigration.account | default (dict) }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -432,4 +435,89 @@ spec: - protocol: TCP port: 6565 {{- end }} +{{- if $gameDesignTenantMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: game-design-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: game-design-tenant-migrator + firemud.dev/workload: game-design-tenant-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 +{{- end }} +{{- if $accountTenantMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: account-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: account-tenant-migrator + firemud.dev/workload: account-tenant-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 + {{- if eq $accountTenantMigration.mode "import" }} + - to: + - podSelector: + matchLabels: + app: game-design-service + ports: + - protocol: TCP + port: 6565 + {{- end }} +{{- end }} {{- end }} diff --git a/k8s/helm/firemud/templates/tenant-association-account-job.yaml b/k8s/helm/firemud/templates/tenant-association-account-job.yaml new file mode 100644 index 0000000000..2d73326b7e --- /dev/null +++ b/k8s/helm/firemud/templates/tenant-association-account-job.yaml @@ -0,0 +1,192 @@ +{{- $migration := .Values.previewStack.tenantAssociationMigration | default (dict) -}} +{{- $job := $migration.account | default (dict) -}} +{{- if ($job.enabled | default false) -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "Account tenant association import requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "Account tenant association import requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $namespace := required "Account tenant association import requires targetNamespace" $job.targetNamespace -}} +{{- if ne $namespace .Release.Namespace -}} +{{- fail "Account tenant association targetNamespace must match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "Account tenant association import requires mode" $job.mode -}} +{{- if not (has $mode (list "evidence" "import")) -}} +{{- fail "Account tenant association mode must be evidence or import" -}} +{{- end -}} +{{- $postgresCredentialSecretName := "firemud-account-tenant-evidence-db" -}} +{{- if eq $mode "import" -}} +{{- $postgresCredentialSecretName = "firemud-account-tenant-import-db" -}} +{{- end -}} +{{- $runId := required "Account tenant association import requires runId" $job.runId -}} +{{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} +{{- fail "Account tenant association runId must be a DNS label of at most 32 characters" -}} +{{- end -}} +{{- $image := required "Account tenant association import requires an immutable image" $job.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "Account tenant association image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $tenantId := required "Account tenant association import requires legacyTenantId" $job.legacyTenantId | toString -}} +{{- if not (regexMatch "^[1-9][0-9]*$" $tenantId) -}} +{{- fail "Account tenant association legacyTenantId must be canonical positive decimal" -}} +{{- end -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: account-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ printf "account-tenant-%s-%s" $mode $runId | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-run-id: {{ $runId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: account-tenant-migrator + firemud.dev/workload: account-tenant-migrator + spec: + serviceAccountName: account-tenant-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + 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: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: [java] + args: + - -jar + - /app/app.jar + - --spring.flyway.enabled=false + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.account-tenant-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_account_service + - name: SERVICE_SCHEMA + value: account_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: {{ $postgresCredentialSecretName | quote }} + key: FIREMUD_POSTGRES_USER + optional: false + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ $postgresCredentialSecretName | quote }} + key: FIREMUD_POSTGRES_PASSWORD + optional: false + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_LEGACY_TENANT_ID + value: {{ $tenantId | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_TARGET_NAMESPACE + value: {{ $namespace | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: migration-tmp + mountPath: /tmp + volumes: + - name: grpc-identity + secret: + secretName: firemud-grpc-account-tenant-migrator + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi +{{- end -}} diff --git a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml new file mode 100644 index 0000000000..f90e318826 --- /dev/null +++ b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml @@ -0,0 +1,217 @@ +{{- $migration := .Values.previewStack.tenantAssociationMigration | default (dict) -}} +{{- $job := $migration.gameDesign | default (dict) -}} +{{- if ($job.enabled | default false) -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "Game Design tenant association migration requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "Game Design tenant association migration requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $namespace := required "Game Design tenant association migration requires targetNamespace" $job.targetNamespace -}} +{{- if ne $namespace .Release.Namespace -}} +{{- fail "Game Design tenant association targetNamespace must match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "Game Design tenant association migration requires mode" $job.mode -}} +{{- if not (has $mode (list "preflight" "apply")) -}} +{{- fail "Game Design tenant association mode must be preflight or apply" -}} +{{- end -}} +{{- $postgresCredentialSecretName := "firemud-game-design-tenant-preflight-db" -}} +{{- if eq $mode "apply" -}} +{{- $postgresCredentialSecretName = "firemud-game-design-tenant-apply-db" -}} +{{- end -}} +{{- $runId := required "Game Design tenant association migration requires runId" $job.runId -}} +{{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} +{{- fail "Game Design tenant association runId must be a DNS label of at most 32 characters" -}} +{{- end -}} +{{- $image := required "Game Design tenant association migration requires an immutable image" $job.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "Game Design tenant association image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $manifestSecret := required "Game Design tenant association migration requires signedManifestSecretName" $job.signedManifestSecretName -}} +{{- $keysSecret := required "Game Design tenant association migration requires trustedKeysSecretName" $job.trustedKeysSecretName -}} +{{- if or (not (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $manifestSecret)) (not (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $keysSecret)) -}} +{{- fail "Game Design tenant association evidence Secret names must be DNS names" -}} +{{- end -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: game-design-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ printf "game-design-tenant-%s-%s" $mode $runId | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-run-id: {{ $runId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: game-design-tenant-migrator + firemud.dev/workload: game-design-tenant-migrator + spec: + serviceAccountName: game-design-tenant-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + 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: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: [java] + args: + - -jar + - /app/app.jar + - --spring.flyway.enabled=false + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.tenant-association-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_game_design_service + - name: SERVICE_SCHEMA + value: game_design_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: {{ $postgresCredentialSecretName | quote }} + key: FIREMUD_POSTGRES_USER + optional: false + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ $postgresCredentialSecretName | quote }} + key: FIREMUD_POSTGRES_PASSWORD + optional: false + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_WORKERS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_TARGET_NAMESPACE + value: {{ $namespace | quote }} + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_SIGNED_MANIFEST_PATH + value: /migration/manifest.json + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_OWNER_PUBLIC_KEYS_PATH + value: /migration-keys/owner-public-keys.json + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: signed-manifest + mountPath: /migration + readOnly: true + - name: trusted-keys + mountPath: /migration-keys + readOnly: true + - name: migration-tmp + mountPath: /tmp + volumes: + - name: grpc-identity + secret: + secretName: firemud-grpc-game-design-tenant-migrator + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: signed-manifest + secret: + secretName: {{ $manifestSecret | quote }} + items: + - key: manifest.json + path: manifest.json + - name: trusted-keys + secret: + secretName: {{ $keysSecret | quote }} + items: + - key: owner-public-keys.json + path: owner-public-keys.json + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi +{{- end -}} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index ff338c1eae..908707db87 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -21,6 +21,26 @@ previewStack: # A dedicated identity Secret must be provisioned by the environment's # trust owner. The chart never falls back to a service certificate. grpcIdentitySecretName: firemud-grpc-game-design-baseline-migrator + tenantAssociationMigration: + # Operator-invoked Jobs only; ordinary chart releases never run them. + # Evidence Secrets and immutable images are supplied by the operator. + # Each mode also requires its fixed, separately provisioned least-privilege + # database Secret; shared bootstrap/service credentials are never a fallback. + gameDesign: + enabled: false + mode: "" + targetNamespace: "" + runId: "" + image: "" + signedManifestSecretName: "" + trustedKeysSecretName: "" + account: + enabled: false + mode: "" + targetNamespace: "" + runId: "" + image: "" + legacyTenantId: "" # Hosted environments use the HostedEnvironmentIdentity controller for # certificate identity. Local installs retain standalone cert-manager mode. certificateIdentity: diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index efbab43fa4..5d9456c67a 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -158,20 +158,22 @@ spec: request.namespace.matches('^(dev|dev-identity|pr-[1-9][0-9]{0,50}|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - request.name == 'firemud-grpc-game-design-baseline-migrator') || + (request.name == 'firemud-grpc-game-design-baseline-migrator' || + request.name == 'firemud-grpc-game-design-tenant-migrator' || + request.name == 'firemud-grpc-account-tenant-migrator')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || ((request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-social-groups-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-social-groups-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name == 'firemud-grpc-game-design-tenant-migrator' || request.name == 'firemud-grpc-account-tenant-migrator' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') || request.name == 'firemud-grpc-tls-previous' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' || object.metadata.name == 'firemud-grpc-account-tenant-migrator' || object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') || object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || object.metadata.name == 'firemud-grpc-tls-previous' || @@ -204,7 +206,9 @@ spec: request.namespace.substring(0, request.namespace.size() - 9) : request.namespace) + '-'))) || (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - request.name == 'firemud-grpc-game-design-baseline-migrator'))) || + (request.name == 'firemud-grpc-game-design-baseline-migrator' || + request.name == 'firemud-grpc-game-design-tenant-migrator' || + request.name == 'firemud-grpc-account-tenant-migrator')))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && ((request.operation == 'DELETE' && @@ -278,6 +282,46 @@ spec: ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-tenant-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-tenant-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-tenant-migrator'))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-account-tenant-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-account-tenant-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-account-tenant-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-account-tenant-migrator'))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.operation in ['CREATE', 'UPDATE'] && request.namespace.matches('^(dev-identity|' + variables.hostedPreviewIdentityNamespacePattern + ')$') && @@ -338,6 +382,20 @@ spec: ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-tenant-migrator'))) || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-account-tenant-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-account-tenant-migrator'))) || (request.namespace.matches('^(dev-identity|' + variables.hostedPreviewIdentityNamespacePattern + ')$') && object.metadata.name != 'firemud-grpc-tls' && ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || @@ -384,7 +442,9 @@ spec: request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - request.name == request.namespace + '-grpc-game-design-baseline-migrator') || + (request.name == request.namespace + '-grpc-game-design-baseline-migrator' || + request.name == request.namespace + '-grpc-game-design-tenant-migrator' || + request.name == request.namespace + '-grpc-account-tenant-migrator')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.groups.exists(group, group == 'system:masters') && @@ -415,6 +475,20 @@ spec: request.name == request.namespace + '-grpc-game-design-baseline-migrator' && object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && object.spec.issuerRef.name == 'firemud-ca-issuer') || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-tenant-migrator' && + object.spec.secretName == 'firemud-grpc-game-design-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-account-tenant-migrator' && + object.spec.secretName == 'firemud-grpc-account-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || (request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && request.subResource == '' && request.operation == 'DELETE' && diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index 12632b0ba7..03d6ced7f8 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -59,7 +59,9 @@ spec: owner.blockOwnerDeletion == true && (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) + (owner.name == request.namespace + '-grpc-game-design-baseline-migrator' || + owner.name == request.namespace + '-grpc-game-design-tenant-migrator' || + owner.name == request.namespace + '-grpc-account-tenant-migrator')))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -116,7 +118,9 @@ spec: owner.blockOwnerDeletion == true && (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) + (owner.name == request.namespace + '-grpc-game-design-baseline-migrator' || + owner.name == request.namespace + '-grpc-game-design-tenant-migrator' || + owner.name == request.namespace + '-grpc-account-tenant-migrator')))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -153,24 +157,24 @@ spec: (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || ((oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'CREATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || ((object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'UPDATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || (object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')) || (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || (oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -178,21 +182,21 @@ spec: (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$')) || (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && (request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$')) || (request.operation != 'DELETE' && ((request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && (request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || object.metadata.name.contains('-grpc-')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$') && object.metadata.name.startsWith(request.namespace + '-') && has(object.spec.secretName) && ((object.metadata.name.contains('-grpc-') && - object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator)$')) || + object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -288,8 +292,40 @@ spec: object.spec.secretTemplate.metadata.annotations == { 'firemud.dev/provenance': 'cert-manager' } && - (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']) || + (object.metadata.name.endsWith('-grpc-game-design-tenant-migrator') && + object.spec.secretName == 'firemud-grpc-game-design-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'tenant-association-migration', + 'firemud.dev/role': 'grpc-game-design-tenant-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-tenant-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']) || + (object.metadata.name.endsWith('-grpc-account-tenant-migrator') && + object.spec.secretName == 'firemud-grpc-account-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'tenant-association-migration', + 'firemud.dev/role': 'grpc-account-tenant-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/account-tenant-migrator'] && object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto new file mode 100644 index 0000000000..ece5fc66e7 --- /dev/null +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -0,0 +1,48 @@ +syntax = "proto3"; + +package gamedesign.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Owner-local legacy source read. This does not attest an Account numeric tenant key. +service TenantIdentityService { + rpc ResolveLegacyGameTenantIdentity(ResolveLegacyGameTenantIdentityRequest) + returns (ResolveLegacyGameTenantIdentityResponse); + // Owner-approved cross-service legacy association; Account is the sole caller. + rpc ResolveLegacyAccountTenantAssociation(ResolveLegacyAccountTenantAssociationRequest) + returns (ResolveLegacyAccountTenantAssociationResponse); +} + +message ResolveLegacyGameTenantIdentityRequest { + string legacy_game_tenant_id = 1; +} + +message ResolveLegacyGameTenantIdentityResponse { + string canonical_tenant_id = 1; + string source_legacy_game_tenant_id = 2; + int64 source_game_row_id = 3; + string provenance_kind = 4; +} + +message ResolveLegacyAccountTenantAssociationRequest { + int64 legacy_account_tenant_id = 1; +} + +message ResolveLegacyAccountTenantAssociationResponse { + int64 legacy_account_tenant_id = 1; + string source_legacy_game_tenant_id = 2; + string canonical_tenant_id = 3; + int64 source_game_row_id = 4; + string account_evidence_digest = 5; + string operation_id = 6; + string manifest_digest = 7; + string target_namespace = 8; + string signer_key_id = 9; + string approved_by = 10; + string approval_reference = 11; + string signed_at = 12; + int32 operation_entry_count = 13; + string manifest_signature = 14; + int32 manifest_schema_version = 15; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java index b6dcb023b4..869208b209 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java @@ -2,17 +2,61 @@ import net.firedevops.firemud.common.GlobalExceptionHandler; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @ConfigurationPropertiesScan -@EnableScheduling @Import(GlobalExceptionHandler.class) public class AccountServiceApplication { public static void main(String[] args) { - SpringApplication.run(AccountServiceApplication.class, args); + if ("true".equals(System.getenv("FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED"))) { + requireNoSharedJwtSecret(); + SpringApplication application = createMigrationApplication(AccountServiceApplication.class); + try (ConfigurableApplicationContext ignored = application.run(args)) { + // The conditional migration runner completed its one-shot evidence or import operation. + } + } else { + SpringApplication.run(AccountServiceApplication.class, args); + } + } + + static SpringApplication createMigrationApplication(Class source) { + SpringApplication application = new SpringApplication(source); + application.setWebApplicationType(WebApplicationType.NONE); + application.addInitializers(requireFlywayDisabledInitializer()); + application.setDefaultProperties( + java.util.Map.of( + "spring.main.web-application-type", "none", + "spring.grpc.server.enabled", "false", + "firemud.auth.jwt-secret", oneShotJwtSecret())); + return application; + } + + private static ApplicationContextInitializer + requireFlywayDisabledInitializer() { + return context -> { + String flywayEnabled = context.getEnvironment().getProperty("spring.flyway.enabled"); + if (flywayEnabled == null || !"false".equalsIgnoreCase(flywayEnabled.trim())) { + throw new IllegalStateException( + "Account migration Job requires explicit spring.flyway.enabled=false"); + } + }; + } + + private static void requireNoSharedJwtSecret() { + if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null + || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { + throw new IllegalStateException("Account migration Job must not receive the shared JWT key"); + } + } + + private static String oneShotJwtSecret() { + return java.util.UUID.randomUUID().toString().replace("-", "") + + java.util.UUID.randomUUID().toString().replace("-", ""); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java new file mode 100644 index 0000000000..520c70aae3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.accountservice.client; + +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +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.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** Account-only authenticated read of a Game Design owner-approved legacy association. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") +public class GameDesignTenantIdentityClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + public GameDesignTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory) { + super(endpoints, tlsProps, channelFactory, GameDesignTenantIdentityClient.class); + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + io.grpc.ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel).withCompression("gzip"); + } + + public ResolveLegacyAccountTenantAssociationResponse resolveApprovedAssociation(long tenantId) { + if (tenantId <= 0) { + throw new IllegalArgumentException("positive legacy Account tenant key is required"); + } + return stub() + .withDeadlineAfter(5, TimeUnit.SECONDS) + .resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest.newBuilder() + .setLegacyAccountTenantId(tenantId) + .build()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java new file mode 100644 index 0000000000..8396e0e332 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.accountservice.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** Enables Account maintenance jobs only during ordinary service operation. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "false", + matchIfMissing = true) +@EnableScheduling +public class AccountSchedulingConfiguration {} 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/dto/MembershipTransitionReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java new file mode 100644 index 0000000000..146018cab5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Provisional per-membership transition receipt, not a canonical authority outbox checkpoint. */ +public record MembershipTransitionReceipt( + String receiptStreamKey, + long receiptSequence, + UUID receiptId, + String receiptDigest, + String evidenceStatus, + String transitionType, + String requestId, + long membershipId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java new file mode 100644 index 0000000000..b942e92a0c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Deterministic SHA-256 digest for a provisional Account membership transition receipt only. */ +public final class MembershipTransitionReceiptDigest { + public static final String EVIDENCE_STATUS = "PROVISIONAL_TRANSITION_RECEIPT"; + + private static final String VERSIONED_RECEIPT_ID_PREFIX = + "account-membership-transition-receipt/v1:"; + + private MembershipTransitionReceiptDigest() {} + + public static String receiptStreamKey(long accountId, long tenantId) { + requirePositive(accountId, "accountId"); + requirePositive(tenantId, "tenantId"); + return "account:membership-transition-receipt:v1:membership/" + accountId + "/" + tenantId; + } + + public static UUID receiptIdForRequest(String requestId) { + String request = requiredField("requestId", requestId); + return UUID.nameUUIDFromBytes( + (VERSIONED_RECEIPT_ID_PREFIX + request).getBytes(StandardCharsets.UTF_8)); + } + + public static String transitionDigest( + String receiptStreamKey, + long receiptSequence, + UUID receiptId, + String transitionType, + String requestId, + long accountId, + long tenantId, + long membershipId, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) { + requirePositive(receiptSequence, "receiptSequence"); + requirePositive(accountId, "accountId"); + requirePositive(tenantId, "tenantId"); + requirePositive(membershipId, "membershipId"); + requirePositive(membershipVersion, "membershipVersion"); + requirePositive(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + String streamKey = requiredField("receiptStreamKey", receiptStreamKey); + String transition = requiredField("transitionType", transitionType); + String request = requiredField("requestId", requestId); + String lifecycleState = requiredField("membershipLifecycleState", membershipLifecycleState); + String provenance = requiredField("authorityProvenance", authorityProvenance); + if (receiptId == null) { + throw new IllegalArgumentException("receiptId is required"); + } + if (!receiptStreamKey(accountId, tenantId).equals(streamKey)) { + throw new IllegalArgumentException("receiptStreamKey does not match the membership scope"); + } + if (!("MEMBERSHIP_JOINED".equals(transition) || "MEMBERSHIP_REACTIVATED".equals(transition))) { + throw new IllegalArgumentException("transitionType is not a supported membership receipt"); + } + + String preimage = + "accountMembershipTransitionReceiptVersion=v1\n" + + field("evidenceStatus", EVIDENCE_STATUS) + + field("receiptStreamKey", streamKey) + + field("receiptSequence", receiptSequence) + + field("receiptId", receiptId) + + field("transitionType", transition) + + field("requestId", request) + + field("accountId", accountId) + + field("tenantId", tenantId) + + field("membershipId", membershipId) + + field("membershipLifecycleState", lifecycleState) + + field("gameplayAdmissionAllowed", gameplayAdmissionAllowed) + + field("membershipVersion", membershipVersion) + + field("membershipAuthorityGeneration", membershipAuthorityGeneration) + + field("authorityProvenance", provenance); + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static String field(String name, Object value) { + String wireValue = value.toString(); + requiredField(name, wireValue); + return name + "=" + wireValue + "\n"; + } + + private static String requiredField(String name, String value) { + if (value == null + || value.isBlank() + || value.indexOf('=') >= 0 + || value.indexOf('\n') >= 0 + || value.indexOf('\r') >= 0) { + throw new IllegalArgumentException(name + " has an invalid canonical wire value"); + } + return value; + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java index 2fb0e62afe..09ed06a6b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java @@ -1,10 +1,14 @@ package net.firedevops.firemud.accountservice.entity; +import java.util.UUID; import lombok.Data; @Data public class Account { private Long id; + private UUID accountUuid; + private AccountIdentityProvenance accountUuidProvenance; + private Long accountUuidSourceNumericId; private String username; private String email; private String passwordHash; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java new file mode 100644 index 0000000000..f3f17c8704 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.accountservice.entity; + +public enum AccountIdentityProvenance { + ACCOUNT_V29_MIGRATION, + ACCOUNT_REPOSITORY_INSERT, + ACCOUNT_DATABASE_INSERT; + + public static AccountIdentityProvenance fromStorageValue(String value) { + if (value == null) { + throw new IllegalStateException("Account UUID provenance must not be null"); + } + try { + return AccountIdentityProvenance.valueOf(value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Unknown Account UUID provenance: " + value, exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java new file mode 100644 index 0000000000..a75f1a085e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.accountservice.maintenance; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; +import org.springframework.stereotype.Component; + +/** Opt-in Account owner import; ordinary service startup performs no legacy mapping. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") +public class LegacyTenantAssociationImportJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(LegacyTenantAssociationImportJobRunner.class); + + private final Environment environment; + private final LegacyTenantAssociationImportService importService; + private final ObjectProvider schedulingPostProcessor; + private final DataSource dataSource; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") + public LegacyTenantAssociationImportJobRunner( + Environment environment, + LegacyTenantAssociationImportService importService, + ObjectProvider schedulingPostProcessor, + DataSource dataSource) { + this.environment = environment; + this.importService = importService; + this.schedulingPostProcessor = schedulingPostProcessor; + this.dataSource = dataSource; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (schedulingPostProcessor.getIfAvailable() != null) { + throw new IllegalStateException( + "Account tenant migration must not start with scheduling enabled"); + } + if (!"true".equals(System.getenv("FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true)) { + throw new IllegalStateException("Account tenant migration must not start listeners"); + } + String mode = required("firemud.account-tenant-migration.mode"); + requireDatabaseAuthority( + mode, + connectedDatabaseUsername(), + environment.getProperty("spring.flyway.enabled", Boolean.class, true)); + String podNamespace = required("firemud.account-tenant-migration.pod-namespace"); + String targetNamespace = required("firemud.account-tenant-migration.target-namespace"); + if (!podNamespace.equals(targetNamespace) + || !"account-tenant-migrator" + .equals(required("firemud.account-tenant-migration.pod-service-account"))) { + throw new IllegalStateException("Account tenant migration Job has the wrong workload scope"); + } + GrpcPeerIdentity identity = verifiedWorkloadIdentity(); + requireJobIdentity(podNamespace, identity); + long legacyTenantId = + Long.parseLong(required("firemud.account-tenant-migration.legacy-tenant-id")); + if (legacyTenantId <= 0) { + throw new IllegalArgumentException("legacy Account tenant key must be positive"); + } + if ("evidence".equals(mode)) { + LOG.info( + "Account tenant evidence legacyTenantId={} digest={} namespace={}", + legacyTenantId, + importService.retainedEvidenceDigest(legacyTenantId), + targetNamespace); + } else if ("import".equals(mode)) { + var imported = importService.importApproved(legacyTenantId); + LOG.info( + "Account tenant association imported legacyTenantId={} canonicalTenantId={} " + + "operationId={} manifestDigest={} namespace={}", + legacyTenantId, + imported.canonicalTenantId(), + imported.operationId(), + imported.manifestDigest(), + targetNamespace); + } else { + throw new IllegalArgumentException("unsupported Account tenant migration Job mode"); + } + } + + static void requireDatabaseAuthority(String mode, String username, boolean flywayEnabled) { + if (flywayEnabled) { + throw new IllegalStateException("Account tenant migration requires Flyway to be disabled"); + } + String requiredUsername = + switch (mode) { + case "evidence" -> "firemud_account_tenant_evidence"; + case "import" -> "firemud_account_tenant_import"; + default -> + throw new IllegalArgumentException("unsupported Account tenant migration mode"); + }; + if (!requiredUsername.equals(username)) { + throw new IllegalStateException( + "Account tenant migration DB credential does not match the mode"); + } + } + + String connectedDatabaseUsername() { + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metadata = connection == null ? null : connection.getMetaData(); + if (metadata == null) { + throw new IllegalStateException("Account tenant migration DB connection is unverifiable"); + } + String username = metadata.getUserName(); + if (username == null || username.isBlank()) { + throw new IllegalStateException( + "Account tenant migration DB connection did not identify its user"); + } + return username; + } catch (SQLException failure) { + // Avoid surfacing driver diagnostics that can echo the configured database username. + throw new IllegalStateException( + "Account tenant migration DB connection could not be verified"); + } + } + + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { + if (identity == null + || !identity.isService("account-tenant-migrator") + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException( + "Account tenant migration certificate has the wrong identity"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow(() -> new IllegalStateException("Account certificate lacks a valid URI SAN")); + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java new file mode 100644 index 0000000000..ef4bfaf8ef --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -0,0 +1,366 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +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; + +/** + * Retains provisional Account JOIN/reactivation receipts without claiming complete authority proof. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountMembershipTransitionReceiptRepository { + private static final String MEMBERSHIP_JOINED = "MEMBERSHIP_JOINED"; + private static final String MEMBERSHIP_REACTIVATED = "MEMBERSHIP_REACTIVATED"; + + private final DSLContext dsl; + + public AccountMembershipTransitionReceiptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Appends one provisional receipt inside the surrounding Account JOIN transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public MembershipTransitionReceipt appendTransition( + AccountTenantMembership membership, String transitionType, String requestId) { + if (membership == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getId() == null) { + throw new IllegalArgumentException("A persisted Account membership is required"); + } + long accountId = membership.getAccount().getId(); + long tenantId = membership.getTenantId(); + long membershipId = membership.getId(); + if (!MEMBERSHIP_JOINED.equals(transitionType) + && !MEMBERSHIP_REACTIVATED.equals(transitionType)) { + throw new IllegalArgumentException("Membership transition type is unsupported"); + } + if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalArgumentException("JOIN receipt requires its committed active state"); + } + + String streamKey = MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); + Long sequence = + dsl.resultQuery( + "INSERT INTO account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence, updated_at) " + + "VALUES (?, ?, ?, 1, CURRENT_TIMESTAMP) " + + "ON CONFLICT (account_id, tenant_id) DO UPDATE SET " + + "last_receipt_sequence = " + + "account_membership_transition_receipt_stream_heads.last_receipt_sequence + 1, " + + "updated_at = CURRENT_TIMESTAMP " + + "RETURNING last_receipt_sequence", + accountId, + tenantId, + streamKey) + .fetchOne(0, Long.class); + if (sequence == null || sequence <= 0L) { + throw new IllegalStateException("Account membership receipt sequence was not allocated"); + } + String digest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance()); + int inserted = + dsl.execute( + "INSERT INTO account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + streamKey, + sequence, + accountId, + tenantId, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membershipId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance(), + receiptId, + digest); + if (inserted != 1) { + throw new IllegalStateException("Account membership transition receipt was not inserted"); + } + return new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + digest, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membershipId); + } + + /** + * Reads and validates the latest provisional receipt. Empty does not prove a canonical + * sequence-zero stream; existing rows without a receipt fail closed. + */ + @Transactional(readOnly = true) + public Optional findLatestReceipt(long accountId, long tenantId) { + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null) { + return Optional.empty(); + } + MembershipTransitionReceipt receipt = snapshot.receipt(); + if (receipt == null) { + return Optional.empty(); + } + Long currentMembershipId = snapshot.currentMembershipId(); + if (currentMembershipId != null + && (currentMembershipId.longValue() != receipt.membershipId() + || !"ACTIVE".equals(snapshot.currentLifecycleState()) + || !snapshot.currentAdmissionAllowed() + || snapshot.currentMembershipVersion() != snapshot.receiptMembershipVersion() + || snapshot.currentAuthorityGeneration() != snapshot.receiptAuthorityGeneration() + || !"EXPLICIT_JOIN".equals(snapshot.currentAuthorityProvenance()))) { + throw new IllegalStateException( + "Account membership row does not match its latest provisional receipt"); + } + return Optional.of(receipt); + } + + /** + * Fail-closes a new row when prior history exists or no versioned restoration path is defined. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public void assertNewMembershipTransitionCanStart(long accountId, long tenantId) { + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null || snapshot.currentMembershipId() != null) { + throw new IllegalStateException("New Account membership transition scope is inconsistent"); + } + if (snapshot.receipt() != null) { + throw new IllegalStateException( + "Retained Account membership history has no supported restoration path"); + } + if (hasPriorMembershipHistory(accountId, tenantId)) { + throw new IllegalStateException( + "Prior Account membership history exists without a provisional transition receipt"); + } + } + + /** Requires positive retained history before reactivating an existing inactive membership. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public MembershipTransitionReceipt requireInactiveMembershipHistory( + AccountTenantMembership membership) { + if (membership == null + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getTenantId() <= 0L + || !"INACTIVE".equals(membership.getLifecycleState())) { + throw new IllegalArgumentException("A persisted inactive Account membership is required"); + } + long accountId = membership.getAccount().getId(); + long tenantId = membership.getTenantId(); + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null + || snapshot.currentMembershipId() == null + || !snapshot.currentMembershipId().equals(membership.getId()) + || !"INACTIVE".equals(snapshot.currentLifecycleState()) + || snapshot.currentAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(snapshot.currentAuthorityProvenance()) + || snapshot.receipt() == null + || snapshot.receipt().membershipId() != membership.getId() + || snapshot.currentMembershipVersion() < snapshot.receiptMembershipVersion() + || snapshot.currentAuthorityGeneration() < snapshot.receiptAuthorityGeneration()) { + throw new IllegalStateException( + "Inactive Account membership lacks matching positive transition receipt history"); + } + return snapshot.receipt(); + } + + private ReceiptSnapshot readLatestReceiptSnapshot(long accountId, long tenantId) { + if (accountId <= 0L || tenantId <= 0L) { + throw new IllegalArgumentException("Account and tenant IDs must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT h.receipt_stream_key, h.last_receipt_sequence, " + + "m.id AS current_membership_id, " + + "m.lifecycle_state AS current_lifecycle_state, " + + "m.gameplay_admission_allowed AS current_admission_allowed, " + + "m.membership_version AS current_membership_version, " + + "m.membership_authority_generation AS current_authority_generation, " + + "m.authority_provenance AS current_authority_provenance, " + + "r.receipt_sequence AS row_receipt_sequence, r.account_id AS receipt_account_id, " + + "r.tenant_id AS receipt_tenant_id, r.evidence_status, r.transition_type, " + + "r.request_id, r.membership_id AS receipt_membership_id, " + + "r.membership_lifecycle_state AS receipt_lifecycle_state, " + + "r.gameplay_admission_allowed AS receipt_admission_allowed, " + + "r.membership_version AS receipt_membership_version, " + + "r.membership_authority_generation AS receipt_authority_generation, " + + "r.authority_provenance AS receipt_authority_provenance, " + + "r.receipt_id, r.receipt_digest " + + "FROM (SELECT 1) scope " + + "LEFT JOIN account_membership_transition_receipt_stream_heads h " + + "ON h.account_id = ? AND h.tenant_id = ? " + + "LEFT JOIN account_tenant_membership m " + + "ON m.account_id = ? AND m.tenant_id = ? " + + "LEFT JOIN account_membership_transition_receipts r " + + "ON r.receipt_stream_key = h.receipt_stream_key " + + "AND r.receipt_sequence = h.last_receipt_sequence ", + accountId, + tenantId, + accountId, + tenantId); + if (row == null) { + return null; + } + Long sequence = row.get("last_receipt_sequence", Long.class); + Long currentMembershipId = row.get("current_membership_id", Long.class); + if (sequence == null) { + if (currentMembershipId != null) { + throw new IllegalStateException( + "Account membership exists without a provisional transition receipt"); + } + return new ReceiptSnapshot(null, null, null, false, 0L, 0L, null, 0L, 0L); + } + Long rowSequence = row.get("row_receipt_sequence", Long.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + if (sequence <= 0L + || !sequence.equals(rowSequence) + || receiptId == null + || receiptDigest == null) { + throw new IllegalStateException( + "Account membership receipt head lacks its exact retained receipt"); + } + + String streamKey = row.get("receipt_stream_key", String.class); + Long receiptAccountId = row.get("receipt_account_id", Long.class); + Long receiptTenantId = row.get("receipt_tenant_id", Long.class); + String evidenceStatus = row.get("evidence_status", String.class); + String transitionType = row.get("transition_type", String.class); + String requestId = row.get("request_id", String.class); + Long membershipId = row.get("receipt_membership_id", Long.class); + String lifecycleState = row.get("receipt_lifecycle_state", String.class); + Boolean admissionAllowed = row.get("receipt_admission_allowed", Boolean.class); + Long membershipVersion = row.get("receipt_membership_version", Long.class); + Long authorityGeneration = row.get("receipt_authority_generation", Long.class); + String authorityProvenance = row.get("receipt_authority_provenance", String.class); + if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId).equals(streamKey) + || !Long.valueOf(accountId).equals(receiptAccountId) + || !Long.valueOf(tenantId).equals(receiptTenantId) + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus) + || membershipId == null + || lifecycleState == null + || admissionAllowed == null + || membershipVersion == null + || authorityGeneration == null + || authorityProvenance == null + || requestId == null + || !receiptId.equals(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId))) { + throw new IllegalStateException("Account membership receipt scope is inconsistent"); + } + String expectedDigest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance); + if (!expectedDigest.equals(receiptDigest)) { + throw new IllegalStateException("Account membership receipt digest is inconsistent"); + } + return new ReceiptSnapshot( + new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + membershipId), + currentMembershipId, + row.get("current_lifecycle_state", String.class), + Boolean.TRUE.equals(row.get("current_admission_allowed", Boolean.class)), + row.get("current_membership_version", Long.class) == null + ? 0L + : row.get("current_membership_version", Long.class), + row.get("current_authority_generation", Long.class) == null + ? 0L + : row.get("current_authority_generation", Long.class), + row.get("current_authority_provenance", String.class), + membershipVersion, + authorityGeneration); + } + + private boolean hasPriorMembershipHistory(long accountId, long tenantId) { + // A minimized JOIN audit no longer identifies its account, so it conservatively blocks this + // tenant's new stream when no retained receipt proves the membership history. + Boolean hasHistory = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_legacy_membership_sources " + + "WHERE account_id = ? AND tenant_id = ? " + + "UNION ALL SELECT 1 FROM account_join_operations " + + "WHERE account_id = ? AND tenant_id = ? " + + "AND status = 'COMMITTED' AND outcome IN ('JOINED', 'ALREADY_ACTIVE') " + + "UNION ALL SELECT 1 FROM account_audit_outbox " + + "WHERE scope = 'tenant' AND tenant_id = ? " + + "AND producer_service = 'account-service' " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " + + "AND (payload IS NULL OR payload::jsonb ->> 'accountId' = CAST(? AS TEXT))" + + ")", + accountId, + tenantId, + accountId, + tenantId, + tenantId, + accountId); + return Boolean.TRUE.equals(hasHistory); + } + + private record ReceiptSnapshot( + MembershipTransitionReceipt receipt, + Long currentMembershipId, + String currentLifecycleState, + boolean currentAdmissionAllowed, + long currentMembershipVersion, + long currentAuthorityGeneration, + String currentAuthorityProvenance, + long receiptMembershipVersion, + long receiptAuthorityGeneration) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index dbc73e32ab..b1002a2489 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -3,8 +3,11 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountsRecord; import net.firedevops.firemud.common.EmailCanonicalization; import org.jooq.DSLContext; @@ -26,6 +29,14 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + public Optional findByAccountUuid(UUID accountUuid) { + Objects.requireNonNull(accountUuid, "accountUuid must not be null"); + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid)) + .fetchOne(this::toEntity)); + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); @@ -41,8 +52,13 @@ public Optional findByEmail(String email) { public Account save(Account entity) { entity.setEmail(EmailCanonicalization.normalize(entity.getEmail())); if (entity.getId() == null) { - Long id = + UUID expectedUuid = UUID.randomUUID(); + AccountsRecord inserted = dsl.insertInto(ACCOUNTS) + .set(ACCOUNTS.ACCOUNT_UUID, expectedUuid) + .set( + ACCOUNTS.ACCOUNT_UUID_PROVENANCE, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) .set(ACCOUNTS.PASSWORD_HASH, entity.getPasswordHash()) @@ -50,12 +66,20 @@ public Account save(Account entity) { .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) .set(ACCOUNTS.LIFECYCLE_STATE, entity.getLifecycleState().storageValue()) - .returningResult(ACCOUNTS.ID) - .fetchOne(ACCOUNTS.ID); - entity.setId(id); + .returning() + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("Account insert did not return its persisted identity"); + } + requireExactIdentityReadback( + inserted, expectedUuid, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + copyIdentityToEntity(entity, inserted); return entity; } - int updated = + UUID expectedUuid = entity.getAccountUuid(); + AccountIdentityProvenance expectedProvenance = entity.getAccountUuidProvenance(); + Long expectedSourceNumericId = entity.getAccountUuidSourceNumericId(); + var update = dsl.update(ACCOUNTS) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) @@ -63,11 +87,27 @@ public Account save(Account entity) { .set(ACCOUNTS.ROLE, entity.getRole()) .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) - .where(ACCOUNTS.ID.eq(entity.getId())) - .execute(); - if (updated != 1) { + .where(ACCOUNTS.ID.eq(entity.getId())); + if (expectedUuid != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID.eq(expectedUuid)); + } + if (expectedProvenance != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expectedProvenance.name())); + } + if (expectedSourceNumericId != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq(expectedSourceNumericId)); + } + AccountsRecord updated = update.returning().fetchOne(); + if (updated == null) { throw JooqAccountRepositorySupport.staleWrite("accounts", entity.getId()); } + requireExactIdentityReadback( + updated, + expectedUuid == null ? updated.getAccountUuid() : expectedUuid, + expectedProvenance == null + ? AccountIdentityProvenance.fromStorageValue(updated.getAccountUuidProvenance()) + : expectedProvenance); + copyIdentityToEntity(entity, updated); return entity; } @@ -78,15 +118,46 @@ public void delete(Account entity) { } private Account toEntity(AccountsRecord record) { - return JooqAccountRepositorySupport.partialAccount( - record.getId(), - record.getUsername(), - record.getEmail(), - record.getPasswordHash(), - record.getRole(), - record.getEmailVerified(), - record.getLoginAuthModes(), - record.getLifecycleState()); + Account account = + JooqAccountRepositorySupport.partialAccount( + record.getId(), + record.getUsername(), + record.getEmail(), + record.getPasswordHash(), + record.getRole(), + record.getEmailVerified(), + record.getLoginAuthModes(), + record.getLifecycleState()); + if (account != null) { + account.setAccountUuid(record.getAccountUuid()); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + account.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); + requireExactIdentityReadback( + record, record.getAccountUuid(), account.getAccountUuidProvenance()); + } + return account; + } + + private void requireExactIdentityReadback( + AccountsRecord record, UUID expectedUuid, AccountIdentityProvenance expectedProvenance) { + if (record.getId() == null + || expectedUuid == null + || expectedProvenance == null + || !Objects.equals(record.getAccountUuid(), expectedUuid) + || !Objects.equals(record.getAccountUuidProvenance(), expectedProvenance.name()) + || !Objects.equals(record.getAccountUuidSourceNumericId(), record.getId())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } + + private void copyIdentityToEntity(Account entity, AccountsRecord record) { + entity.setId(record.getId()); + entity.setAccountUuid(record.getAccountUuid()); + entity.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + entity.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); } private String normalizedLoginAuthModes(Account entity) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java new file mode 100644 index 0000000000..98240cbae1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Base64; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +/** Account-owned exact retained-row verification and immutable association readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class ApprovedLegacyTenantAssociationRepository { + private final DSLContext dsl; + private final LegacyTenantSourceEvidence sourceEvidence; + private final String workloadNamespace; + + public ApprovedLegacyTenantAssociationRepository( + DSLContext dsl, + LegacyTenantSourceEvidence sourceEvidence, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.dsl = dsl; + this.sourceEvidence = sourceEvidence; + this.workloadNamespace = workloadNamespace; + } + + @Transactional(isolation = Isolation.SERIALIZABLE) + public ApprovedAssociation importApproved( + long requestedLegacyTenantId, ResolveLegacyAccountTenantAssociationResponse ownerResponse) { + ApprovedAssociation expected = requireExactResponse(requestedLegacyTenantId, ownerResponse); + String actualEvidenceDigest = sourceEvidence.digest(requestedLegacyTenantId); + if (!actualEvidenceDigest.equals(expected.accountEvidenceDigest())) { + throw new IllegalStateException( + "approved Account source evidence differs from retained rows"); + } + Optional existing = findByLegacyTenantId(requestedLegacyTenantId); + if (existing.isPresent()) { + if (!existing.orElseThrow().equals(expected)) { + throw new IllegalStateException( + "approved Account tenant association conflicts with readback"); + } + return existing.orElseThrow(); + } + + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (legacy_tenant_id) DO NOTHING", + expected.legacyTenantId(), + expected.canonicalTenantId(), + expected.sourceLegacyGameTenantId(), + expected.sourceGameRowId(), + expected.accountEvidenceDigest(), + expected.operationId(), + expected.manifestDigest(), + expected.manifestSignature(), + expected.targetNamespace(), + expected.signerKeyId(), + expected.approvedBy(), + expected.approvalReference(), + expected.signedAt(), + expected.operationEntryCount(), + expected.manifestSchemaVersion()); + ApprovedAssociation committed = + findByLegacyTenantId(requestedLegacyTenantId) + .orElseThrow( + () -> new IllegalStateException("approved association readback is absent")); + if (!committed.equals(expected)) { + throw new IllegalStateException("approved association readback differs"); + } + return committed; + } + + @Transactional(readOnly = true) + public Optional findByLegacyTenantId(long legacyTenantId) { + if (legacyTenantId <= 0) { + return Optional.empty(); + } + Record row = + dsl.fetchOne( + "SELECT legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, " + + "manifest_schema_version " + + "FROM account_approved_legacy_tenant_associations WHERE legacy_tenant_id = ?", + legacyTenantId); + return Optional.ofNullable(row) + .map( + result -> + new ApprovedAssociation( + result.get(0, Long.class), + result.get(1, UUID.class), + result.get(2, String.class), + result.get(3, Long.class), + result.get(4, String.class), + result.get(5, UUID.class), + result.get(6, String.class), + result.get(7, String.class), + result.get(8, String.class), + result.get(9, String.class), + result.get(10, String.class), + result.get(11, String.class), + result.get(12, String.class), + result.get(13, Integer.class), + result.get(14, Integer.class))); + } + + private ApprovedAssociation requireExactResponse( + long requestedLegacyTenantId, ResolveLegacyAccountTenantAssociationResponse response) { + Objects.requireNonNull(response, "Game Design owner response is required"); + if (requestedLegacyTenantId <= 0 + || response.getLegacyAccountTenantId() != requestedLegacyTenantId + || workloadNamespace == null + || workloadNamespace.isBlank() + || !workloadNamespace.equals(response.getTargetNamespace()) + || response.getSourceLegacyGameTenantId().isBlank() + || response.getSourceLegacyGameTenantId().length() > 36 + || response.getSourceGameRowId() <= 0 + || !digest(response.getAccountEvidenceDigest()) + || !digest(response.getManifestDigest()) + || response.getSignerKeyId().isBlank() + || response.getApprovedBy().isBlank() + || response.getApprovalReference().isBlank() + || response.getOperationEntryCount() <= 0 + || response.getManifestSchemaVersion() != 1) { + throw new IllegalArgumentException( + "Game Design owner association is incomplete or mismatched"); + } + try { + UUID canonicalTenantId = UUID.fromString(response.getCanonicalTenantId()); + UUID operationId = UUID.fromString(response.getOperationId()); + Instant.parse(response.getSignedAt()); + byte[] signature = Base64.getDecoder().decode(response.getManifestSignature()); + if (signature.length != 64 + || !Base64.getEncoder() + .encodeToString(signature) + .equals(response.getManifestSignature())) { + throw new IllegalArgumentException("owner manifest signature has the wrong length"); + } + return new ApprovedAssociation( + requestedLegacyTenantId, + canonicalTenantId, + response.getSourceLegacyGameTenantId(), + response.getSourceGameRowId(), + response.getAccountEvidenceDigest(), + operationId, + response.getManifestDigest(), + response.getManifestSignature(), + response.getTargetNamespace(), + response.getSignerKeyId(), + response.getApprovedBy(), + response.getApprovalReference(), + response.getSignedAt(), + response.getOperationEntryCount(), + response.getManifestSchemaVersion()); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException( + "Game Design owner association has invalid identity evidence", ex); + } + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + public record ApprovedAssociation( + long legacyTenantId, + UUID canonicalTenantId, + String sourceLegacyGameTenantId, + long sourceGameRowId, + String accountEvidenceDigest, + UUID operationId, + String manifestDigest, + String manifestSignature, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + int operationEntryCount, + int manifestSchemaVersion) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java new file mode 100644 index 0000000000..710903a2b0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.List; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Exact V26 retained Account source-row evidence for an operator-approved tenant association. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class LegacyTenantSourceEvidence { + private static final String DOMAIN = "firemud/account-legacy-tenant-source/v1"; + + private final DSLContext dsl; + + public LegacyTenantSourceEvidence(DSLContext dsl) { + this.dsl = dsl; + } + + public String digest(long legacyTenantId) { + if (legacyTenantId <= 0) { + throw new IllegalArgumentException("positive retained Account tenant key is required"); + } + List accounts = + dsl.fetch( + "SELECT account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition, captured_at " + + "FROM account_legacy_tenant_sources WHERE legacy_tenant_id = ? " + + "ORDER BY account_id", + legacyTenantId); + if (accounts.isEmpty()) { + throw new IllegalStateException("retained Account numeric tenant source is absent"); + } + List memberships = + dsl.fetch( + "SELECT membership_id, account_id, tenant_id, " + + "original_gameplay_admission_allowed, matches_account_legacy_tenant, " + + "disposition, captured_at FROM account_legacy_membership_sources " + + "WHERE tenant_id = ? ORDER BY membership_id", + legacyTenantId); + List profiles = + dsl.fetch( + "SELECT profile_id, account_id, tenant_id, matches_account_legacy_tenant, " + + "disposition, captured_at FROM account_legacy_profile_sources " + + "WHERE tenant_id = ? ORDER BY profile_id", + legacyTenantId); + + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + try (DataOutputStream out = + new DataOutputStream(new DigestOutputStream(OutputStream.nullOutputStream(), hash))) { + write(out, DOMAIN); + out.writeLong(legacyTenantId); + out.writeInt(accounts.size()); + for (Record row : accounts) { + if (!"UNVERIFIED".equals(row.get(6, String.class))) { + throw new IllegalStateException("retained Account tenant source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + writeOptionalLong(out, row.get(2, Long.class)); + writeOptionalBoolean(out, row.get(3, Boolean.class)); + out.writeLong(row.get(4, Long.class)); + out.writeLong(row.get(5, Long.class)); + write(out, row.get(6, String.class)); + write(out, row.get(7, LocalDateTime.class).toString()); + } + out.writeInt(memberships.size()); + for (Record row : memberships) { + if (!Boolean.TRUE.equals(row.get(4, Boolean.class)) + || !"UNVERIFIED".equals(row.get(5, String.class))) { + throw new IllegalStateException("retained Account membership source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + out.writeLong(row.get(2, Long.class)); + out.writeBoolean(row.get(3, Boolean.class)); + out.writeBoolean(row.get(4, Boolean.class)); + write(out, row.get(5, String.class)); + write(out, row.get(6, LocalDateTime.class).toString()); + } + out.writeInt(profiles.size()); + for (Record row : profiles) { + if (!Boolean.TRUE.equals(row.get(3, Boolean.class)) + || !"UNVERIFIED".equals(row.get(4, String.class))) { + throw new IllegalStateException("retained Account profile source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + out.writeLong(row.get(2, Long.class)); + out.writeBoolean(row.get(3, Boolean.class)); + write(out, row.get(4, String.class)); + write(out, row.get(5, LocalDateTime.class).toString()); + } + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("retained Account source evidence cannot be digested", ex); + } + } + + private static void write(DataOutputStream out, String value) throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + out.writeInt(bytes.length); + out.write(bytes); + } + + private static void writeOptionalLong(DataOutputStream out, Long value) throws IOException { + out.writeBoolean(value != null); + if (value != null) { + out.writeLong(value); + } + } + + private static void writeOptionalBoolean(DataOutputStream out, Boolean value) throws IOException { + out.writeBoolean(value != null); + if (value != null) { + out.writeBoolean(value); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java index f18c38ff5e..efe53bbaf6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java @@ -14,11 +14,14 @@ import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import org.slf4j.Logger; @@ -51,6 +54,7 @@ public class AccountJoinReconciliationService { private final AccountJoinOperationRepository joinOperationRepository; private final AccountConnectScopeRepository connectScopeRepository; private final AccountTenantMembershipRepository membershipRepository; + private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; private final AccountAuditOutboxRepository auditOutboxRepository; private final TransactionTemplate joinTransactionTemplate; private final int batchSize; @@ -65,6 +69,7 @@ public AccountJoinReconciliationService( AccountJoinOperationRepository joinOperationRepository, AccountConnectScopeRepository connectScopeRepository, AccountTenantMembershipRepository membershipRepository, + AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountAuditOutboxRepository auditOutboxRepository, MeterRegistry meterRegistry, PlatformTransactionManager transactionManager, @@ -86,6 +91,7 @@ public AccountJoinReconciliationService( this.joinOperationRepository = joinOperationRepository; this.connectScopeRepository = connectScopeRepository; this.membershipRepository = membershipRepository; + this.transitionReceiptRepository = transitionReceiptRepository; this.auditOutboxRepository = auditOutboxRepository; this.batchSize = batchSize; this.maxAttempts = maxAttempts; @@ -173,6 +179,8 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no JoinMembershipProof membership = null; JoinAuditEvidence auditEvidence = null; + MembershipTransitionReceipt transitionReceipt = null; + String outcome = null; if (unresolvedReason == null) { membership = membershipRepository @@ -186,17 +194,43 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no } if (unresolvedReason == null) { - auditEvidence = - auditOutboxRepository - .findJoinEnvelopeForUpdate( - joinAuditEventId(operation.requestId()), operation.tenantId()) - .orElse(null); - if (auditEvidence == null) { - unresolvedReason = "JOIN_AUDIT_ENVELOPE_ABSENT"; - } else if (!auditEnvelopeMatches(operation, membership, auditEvidence.envelope())) { - unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; - } else if (!verifiedJoinAuditDelivery(auditEvidence)) { - unresolvedReason = "JOIN_AUDIT_RECEIPT_UNVERIFIED"; + try { + transitionReceipt = + transitionReceiptRepository + .findLatestReceipt(operation.accountId(), operation.tenantId()) + .orElse(null); + } catch (RuntimeException ex) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_UNAVAILABLE"; + } + if (unresolvedReason == null && transitionReceipt == null) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT"; + } else if (unresolvedReason == null) { + auditEvidence = + auditOutboxRepository + .findJoinEnvelopeForUpdate( + joinAuditEventId(operation.requestId()), operation.tenantId()) + .orElse(null); + if (Objects.equals(operation.requestId(), transitionReceipt.requestId())) { + if (!transitionReceiptMatches(operation, membership, transitionReceipt)) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH"; + } else if (auditEvidence == null) { + unresolvedReason = "JOIN_AUDIT_ENVELOPE_ABSENT"; + } else if (!auditEnvelopeMatches(operation, membership, auditEvidence.envelope())) { + unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } else if (!verifiedJoinAuditDelivery(auditEvidence)) { + unresolvedReason = "JOIN_AUDIT_RECEIPT_UNVERIFIED"; + } else { + outcome = "JOINED"; + } + } else if (!existingMembershipHistoryMatches(operation, membership, transitionReceipt)) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH"; + } else if (auditEvidence != null) { + // A request-specific audit without its matching transition receipt is contradictory. + unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } else { + // Existing active membership/history proves ALREADY_ACTIVE; this path writes no events. + outcome = "ALREADY_ACTIVE"; + } } } @@ -207,7 +241,7 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no joinOperationRepository.finish( operation.requestId(), "COMMITTED", - "JOINED", + outcome, membership.membershipId(), membership.membershipVersion(), membership.membershipAuthorityGeneration()); @@ -331,6 +365,41 @@ private static boolean auditEnvelopeMatches( && Objects.equals(payload.requestId(), operation.requestId()); } + private static boolean transitionReceiptMatches( + JoinOperation operation, + JoinMembershipProof membership, + MembershipTransitionReceipt receipt) { + return MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + && MembershipTransitionReceiptDigest.receiptStreamKey( + operation.accountId(), operation.tenantId()) + .equals(receipt.receiptStreamKey()) + && receipt.receiptSequence() > 0L + && MembershipTransitionReceiptDigest.receiptIdForRequest(operation.requestId()) + .equals(receipt.receiptId()) + && Objects.equals(receipt.requestId(), operation.requestId()) + && receipt.membershipId() == membership.membershipId() + && ("MEMBERSHIP_JOINED".equals(receipt.transitionType()) + || "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + } + + private static boolean existingMembershipHistoryMatches( + JoinOperation operation, + JoinMembershipProof membership, + MembershipTransitionReceipt receipt) { + return !Objects.equals(operation.requestId(), receipt.requestId()) + && MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + && MembershipTransitionReceiptDigest.receiptStreamKey( + operation.accountId(), operation.tenantId()) + .equals(receipt.receiptStreamKey()) + && receipt.receiptSequence() > 0L + && receipt.requestId() != null + && MembershipTransitionReceiptDigest.receiptIdForRequest(receipt.requestId()) + .equals(receipt.receiptId()) + && receipt.membershipId() == membership.membershipId() + && ("MEMBERSHIP_JOINED".equals(receipt.transitionType()) + || "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + } + private static boolean verifiedJoinAuditDelivery(JoinAuditEvidence evidence) { return "COMMITTED".equals(evidence.deliveryStatus()) && Integer.valueOf(1).equals(evidence.auditProjectionVersion()) 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 82f6ecb5c5..03aac99601 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 @@ -69,6 +69,7 @@ import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -127,6 +128,7 @@ public class AccountServiceImpl implements AccountService { private final AccountAuditOutboxRepository accountAuditOutboxRepository; private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; + private final AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -157,6 +159,7 @@ public AccountServiceImpl( AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, + AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, @@ -182,6 +185,7 @@ public AccountServiceImpl( this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; + this.membershipTransitionReceiptRepository = membershipTransitionReceiptRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; @@ -750,7 +754,10 @@ private JoinPublicProductionResult executePendingJoinAttempt( return pendingJoinFailure(scope, "AUTH_UNAVAILABLE"); } boolean transitioned = false; + String membershipTransitionType = null; if (membership == null) { + membershipTransitionReceiptRepository.assertNewMembershipTransitionCanStart( + accountId, scope.tenantId()); membership = new AccountTenantMembership(); membership.setAccount(requireAccount(accountId)); membership.setTenantId(scope.tenantId()); @@ -761,7 +768,9 @@ private JoinPublicProductionResult executePendingJoinAttempt( membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); transitioned = true; + membershipTransitionType = "MEMBERSHIP_JOINED"; } else if ("INACTIVE".equals(membership.getLifecycleState())) { + membershipTransitionReceiptRepository.requireInactiveMembershipHistory(membership); accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); membership.setLifecycleState("ACTIVE"); membership.setGameplayAdmissionAllowed(true); @@ -771,11 +780,21 @@ private JoinPublicProductionResult executePendingJoinAttempt( membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); transitioned = true; - } else if (!"ACTIVE".equals(membership.getLifecycleState()) - || !membership.isGameplayAdmissionAllowed()) { + membershipTransitionType = "MEMBERSHIP_REACTIVATED"; + } else if ("ACTIVE".equals(membership.getLifecycleState()) + && membership.isGameplayAdmissionAllowed()) { + membershipTransitionReceiptRepository + .findLatestReceipt(accountId, scope.tenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Active Account membership lacks a provisional transition receipt")); + } else { return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); } if (transitioned) { + membershipTransitionReceiptRepository.appendTransition( + membership, membershipTransitionType, requestId); String payload = AUDIT_JSON.writeValueAsString( new JoinAuditPayload( @@ -1121,6 +1140,7 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { + requireCurrentConnectTokenEligibility(bootstrapContext, scopeContext, request, true); logger.info( "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", bootstrapContext.accountId(), @@ -1162,52 +1182,17 @@ private ConnectTokenResult issueConnectTokenFresh( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, ConnectTokenRequest request) { - RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - RuntimeMembershipDto membership = - getTenantMembershipForRuntime( - bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - - if (membership.membershipExists() - && !"ACTIVE".equals(membership.membershipLifecycleState()) - && !"INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); - } - if (membership.membershipExists() - && "INACTIVE".equals(membership.membershipLifecycleState()) - && isPublicProductionRealm(realm)) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - - if (!membership.membershipExists()) { - if (!isPublicProductionRealm(realm)) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } + RuntimeRealmTarget realm = + requireCurrentConnectTokenEligibility(bootstrapContext, scopeContext, request, false); + if (!isPublicProductionRealm(realm) + && !hasRealmAccessGrant( + bootstrapContext.accountId(), + scopeContext.tenantId(), + scopeContext.worldSlug(), + scopeContext.realmSlug())) { throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + "REALM_ACCESS_DENIED", + "The selected non-public realm does not have an active access grant"); } String jti = @@ -1285,6 +1270,72 @@ && isPublicProductionRealm(realm)) { return result; } + private RuntimeRealmTarget requireCurrentConnectTokenEligibility( + BootstrapContext bootstrapContext, + ConnectScopeContext scopeContext, + ConnectTokenRequest request, + boolean cachedSuccessReplay) { + RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); + boolean publicProductionRealm = isPublicProductionRealm(realm); + if (cachedSuccessReplay && !publicProductionRealm) { + throw new AuthenticationException( + "REALM_ACCESS_DENIED", + "The selected non-public realm does not have an active access grant"); + } + + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + RuntimeMembershipDto membership = + getTenantMembershipForRuntime( + bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); + + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && publicProductionRealm) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + if (membership.membershipExists() && "INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + + if (!membership.membershipExists()) { + if (!publicProductionRealm) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + return realm; + } + @Override @Transactional(readOnly = true) @Timed(value = "account.runtime_membership") @@ -1634,13 +1685,19 @@ private boolean isDiscoveryRealmAdmissible( private boolean hasRealmAdmissionAccess( BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { long tenantId = realm.tenantId(); - if (!isPublicProductionRealm(realm)) { - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { - return false; - } + boolean publicProductionRealm = isPublicProductionRealm(realm); + Optional membership = + accountTenantMembershipRepository.findByAccountIdAndTenantId( + bootstrapContext.accountId(), tenantId); + if (membership.isPresent() + && (!membership.orElseThrow().isGameplayAdmissionAllowed() + || !"ACTIVE".equals(membership.orElseThrow().getLifecycleState()))) { + return false; + } + if (membership.isEmpty() && !publicProductionRealm) { + return false; + } + if (!publicProductionRealm) { if (!hasRealmAccessGrant( bootstrapContext.accountId(), tenantId, realm.worldSlug(), realm.realmSlug())) { return false; @@ -1868,7 +1925,8 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); } if (maybeMembership.isPresent() - && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { + && (!maybeMembership.orElseThrow().isGameplayAdmissionAllowed() + || "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()))) { throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); } @@ -2001,8 +2059,9 @@ private Account requireAccount(Long accountId) { private boolean hasRealmAccessGrant( Long accountId, Long tenantId, String worldSlug, String realmSlug) { - return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); + // The retained four-field row cannot prove the current playtest lifecycle and state generation. + // Keep legacy grant records for write/history paths, but do not use them as REST authority. + return false; } private String mintToken(String subject, long expirationMs, Map claims) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java new file mode 100644 index 0000000000..7e57d9ca3e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import net.firedevops.firemud.accountservice.client.GameDesignTenantIdentityClient; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Operator-invoked import; neither lookup nor evidence enumeration grants membership admission. */ +@Service +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") +public class LegacyTenantAssociationImportService { + private final GameDesignTenantIdentityClient ownerClient; + private final ApprovedLegacyTenantAssociationRepository repository; + private final LegacyTenantSourceEvidence sourceEvidence; + + public LegacyTenantAssociationImportService( + GameDesignTenantIdentityClient ownerClient, + ApprovedLegacyTenantAssociationRepository repository, + LegacyTenantSourceEvidence sourceEvidence) { + this.ownerClient = ownerClient; + this.repository = repository; + this.sourceEvidence = sourceEvidence; + } + + @Transactional(readOnly = true) + public String retainedEvidenceDigest(long legacyTenantId) { + return sourceEvidence.digest(legacyTenantId); + } + + public ApprovedAssociation importApproved(long legacyTenantId) { + return repository.importApproved( + legacyTenantId, ownerClient.resolveApprovedAssociation(legacyTenantId)); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql new file mode 100644 index 0000000000..bc7962b8cd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql @@ -0,0 +1,80 @@ +-- Keep the numeric primary key as an Account-local storage detail while adding +-- the canonical, durable UUID identity required at cross-service boundaries. +-- Each retained UUID is assigned to its exact source row in place; the numeric +-- source is copied from that row's unchanged primary key. +ALTER TABLE accounts + ADD COLUMN account_uuid UUID, + ADD COLUMN account_uuid_provenance VARCHAR(40), + ADD COLUMN account_uuid_source_numeric_id BIGINT; + +UPDATE accounts +SET account_uuid = gen_random_uuid(), + account_uuid_provenance = 'ACCOUNT_V29_MIGRATION', + account_uuid_source_numeric_id = id; + +-- jOOQ's open-source DDL parser cannot model the PostgreSQL UUID generator default. +-- [jooq ignore start] +ALTER TABLE accounts ALTER COLUMN account_uuid SET DEFAULT gen_random_uuid(); +ALTER TABLE accounts + ALTER COLUMN account_uuid_provenance SET DEFAULT 'ACCOUNT_DATABASE_INSERT'; +-- [jooq ignore stop] + +ALTER TABLE accounts ALTER COLUMN account_uuid SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_provenance SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_source_numeric_id SET NOT NULL; +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_unique UNIQUE (account_uuid); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_unique + UNIQUE (account_uuid_source_numeric_id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_check + CHECK (account_uuid_source_numeric_id = id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )); + +-- The UUID and its source record are immutable identity evidence. The numeric +-- primary key remains unchanged and cannot be reassigned after UUID backfill. +-- [jooq ignore start] +CREATE FUNCTION account_identity_source_row_on_insert() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.account_uuid_source_numeric_id := NEW.id; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_source_row_on_insert + BEFORE INSERT ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_source_row_on_insert(); + +CREATE FUNCTION account_identity_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id THEN + RAISE EXCEPTION 'Account identity cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_immutable + BEFORE UPDATE OF id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql b/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql new file mode 100644 index 0000000000..761ba9b457 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql @@ -0,0 +1,39 @@ +-- No retained numeric tenant key is mapped by this migration. An Account-owned +-- import verifies exact V26 source evidence against a Game Design approved read. +CREATE TABLE account_approved_legacy_tenant_associations ( + legacy_tenant_id BIGINT PRIMARY KEY CHECK (legacy_tenant_id > 0), + canonical_tenant_id UUID NOT NULL UNIQUE, + source_legacy_game_tenant_id VARCHAR(36) NOT NULL UNIQUE, + source_game_row_id BIGINT NOT NULL UNIQUE CHECK (source_game_row_id > 0), + account_evidence_digest VARCHAR(71) NOT NULL, + operation_id UUID NOT NULL, + manifest_digest VARCHAR(71) NOT NULL, + manifest_signature VARCHAR(128) NOT NULL, + target_namespace VARCHAR(128) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at VARCHAR(40) NOT NULL, + operation_entry_count INTEGER NOT NULL CHECK (operation_entry_count > 0), + manifest_schema_version INTEGER NOT NULL CHECK (manifest_schema_version = 1), + imported_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_approved_tenant_evidence_digest_shape + CHECK (account_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_approved_tenant_manifest_digest_shape + CHECK (manifest_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_approved_tenant_signature_shape + CHECK (length(manifest_signature) = 88) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_account_approved_tenant_change() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Approved Account legacy tenant association is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_approved_tenant_association_immutable + BEFORE UPDATE OR DELETE ON account_approved_legacy_tenant_associations + FOR EACH ROW EXECUTE FUNCTION reject_account_approved_tenant_change(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V40__account_membership_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V40__account_membership_transition_receipts.sql new file mode 100644 index 0000000000..a9f29d47d9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V40__account_membership_transition_receipts.sql @@ -0,0 +1,64 @@ +-- Provisional transition receipts retain exact Account JOIN/reactivation history without +-- claiming the full authorityTuple or issuanceFence required by the canonical authority outbox. +-- Their distinct stream key cannot consume canonical account:auth-authority:v1 sequence values. +CREATE TABLE account_membership_transition_receipt_stream_heads ( + account_id BIGINT NOT NULL CHECK (account_id > 0), + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + receipt_stream_key VARCHAR(256) NOT NULL, + last_receipt_sequence BIGINT NOT NULL CHECK (last_receipt_sequence > 0), + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_membership_transition_receipt_stream_heads_pk + PRIMARY KEY (account_id, tenant_id), + CONSTRAINT account_membership_transition_receipt_stream_heads_key_unique + UNIQUE (receipt_stream_key), + CONSTRAINT account_membership_transition_receipt_stream_heads_key_check + CHECK (receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT) +); + +CREATE TABLE account_membership_transition_receipts ( + receipt_stream_key VARCHAR(256) NOT NULL, + receipt_sequence BIGINT NOT NULL CHECK (receipt_sequence > 0), + account_id BIGINT NOT NULL CHECK (account_id > 0), + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + evidence_status VARCHAR(48) NOT NULL, + transition_type VARCHAR(32) NOT NULL, + request_id VARCHAR(128) NOT NULL, + membership_id BIGINT NOT NULL CHECK (membership_id > 0), + membership_lifecycle_state VARCHAR(32) NOT NULL, + gameplay_admission_allowed BOOLEAN NOT NULL, + membership_version BIGINT NOT NULL CHECK (membership_version > 0), + membership_authority_generation BIGINT NOT NULL CHECK (membership_authority_generation > 0), + authority_provenance VARCHAR(32) NOT NULL, + receipt_id UUID NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_membership_transition_receipts_pk + PRIMARY KEY (receipt_stream_key, receipt_sequence), + CONSTRAINT account_membership_transition_receipts_id_unique + UNIQUE (receipt_id), + CONSTRAINT account_membership_transition_receipts_request_unique + UNIQUE (request_id), + CONSTRAINT account_membership_transition_receipts_stream_fk + FOREIGN KEY (account_id, tenant_id) + REFERENCES account_membership_transition_receipt_stream_heads (account_id, tenant_id) + ON DELETE RESTRICT, + CONSTRAINT account_membership_transition_receipts_key_check + CHECK (receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT), + CONSTRAINT account_membership_transition_receipts_status_check + CHECK (evidence_status = 'PROVISIONAL_TRANSITION_RECEIPT'), + CONSTRAINT account_membership_transition_receipts_transition_check + CHECK (transition_type IN ('MEMBERSHIP_JOINED', 'MEMBERSHIP_REACTIVATED')), + CONSTRAINT account_membership_transition_receipts_state_check + CHECK (membership_lifecycle_state = 'ACTIVE' + AND gameplay_admission_allowed = TRUE + AND authority_provenance = 'EXPLICIT_JOIN'), + CONSTRAINT account_membership_transition_receipts_digest_check + CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE INDEX idx_account_membership_transition_receipts_latest + ON account_membership_transition_receipts (account_id, tenant_id, receipt_sequence DESC); diff --git a/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql new file mode 100644 index 0000000000..90937be90e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql @@ -0,0 +1,14 @@ +-- JOIN transition receipts are retained recovery evidence and may only be appended. +-- The independent stream head remains mutable so legitimate receipt appends can advance it. +-- [jooq ignore start] +CREATE FUNCTION reject_account_membership_transition_receipt_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account membership transition receipts are append-only' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_membership_transition_receipts_append_only + BEFORE UPDATE OR DELETE ON account_membership_transition_receipts + FOR EACH ROW EXECUTE FUNCTION reject_account_membership_transition_receipt_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 0bcd50ad58..fa78e49950 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -147,8 +147,6 @@ components: type: string connectScopeId: type: string - jti: - type: string requestId: type: string issuedAt: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index d86af7f70a..6f052cf92b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -8,7 +8,9 @@ import static org.mockito.Mockito.when; 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 java.util.concurrent.atomic.AtomicBoolean; @@ -20,7 +22,10 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; @@ -79,11 +84,15 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired + private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; + @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private LoggingAdminClient loggingAdminClient; @MockitoBean private JavaMailSender mailSender; @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + private final Map fixtureRealms = new LinkedHashMap<>(); @Test void terminalCommitWithLostAcknowledgementReadsBackExactStoredJoinResult() { @@ -180,6 +189,7 @@ void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { }); assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); JoinPublicProductionResult recovered = join(fixture); @@ -247,12 +257,298 @@ void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + } + + @Test + void exactJoinRetryDoesNotAppendAnotherMembershipTransitionReceipt() { + JoinFixture fixture = fixture("active"); + + JoinPublicProductionResult joined = join(fixture); + JoinPublicProductionResult replayed = join(fixture); + + assertThat(joined.success()).isTrue(); + assertThat(joined.outcomeCode()).isEqualTo("JOINED"); + assertThat(replayed.replayed()).isTrue(); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + } + + @Test + void newRequestForRetainedActiveMembershipIsEventFreeAndRequiresPositiveHistory() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).outcomeCode()).isEqualTo("JOINED"); + JoinFixture alreadyActive = fixtureForMembership(initialJoin); + + JoinPublicProductionResult result = join(alreadyActive); + + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(countMembershipTransitionReceipts(alreadyActive)).isEqualTo(1L); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat(countTenantJoinOutboxEvents(initialJoin)).isEqualTo(1L); + assertThat(countTenantJoinOutboxEvents(alreadyActive)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_join_operations " + + "WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'ALREADY_ACTIVE'", + alreadyActive.requestId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void membershipTransitionReceiptSequenceIsIndependentForEachAccountTenantStream() { + JoinFixture first = fixture("active"); + JoinFixture second = fixture("active", first.accountId()); + + assertThat(join(first).success()).isTrue(); + assertThat(join(second).success()).isTrue(); + + assertMembershipTransitionReceipt(first, "MEMBERSHIP_JOINED", 1L); + assertMembershipTransitionReceipt(second, "MEMBERSHIP_JOINED", 1L); + assertThat(receiptStreamKey(first)).isNotEqualTo(receiptStreamKey(second)); + } + + @Test + void reactivationAppendsTheNextPositiveMembershipTransitionReceiptSequence() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture reactivation = fixtureForMembership(initialJoin); + + JoinPublicProductionResult result = join(reactivation); + + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("JOINED"); + assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT membership_version, membership_authority_generation " + + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + reactivation.accountId(), + reactivation.tenantId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("membership_version", Long.class)).isEqualTo(2L); + assertThat(row.get("membership_authority_generation", Long.class)).isEqualTo(2L); + }); + } + + @Test + void committedMembershipTransitionReceiptHistorySurvivesAbsenceOfCurrentMembershipRow() { + JoinFixture fixture = fixture("active"); + assertThat(join(fixture).success()).isTrue(); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + + dsl.execute("DELETE FROM account_join_operations WHERE request_id = ?", fixture.requestId()); + + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()); + + assertThat(countMemberships(fixture)).isZero(); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + } + + @Test + void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvance() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + dsl.execute( + "UPDATE account_membership_transition_receipts " + + "SET transition_type = 'MEMBERSHIP_REACTIVATED' " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId())); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + dsl.execute( + "DELETE FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId())); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat( + dsl.resultQuery( + "SELECT last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture reactivation = fixtureForMembership(initialJoin); + + assertThat(join(reactivation).success()).isTrue(); + assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + reactivation.accountId(), + reactivation.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + } + + @Test + void minimizedPriorJoinAuditWithoutMembershipOrReceiptKeepsJoinRetryable() { + JoinFixture retry = fixture("active"); + 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, delivery_status, " + + "next_attempt_at) " + + "VALUES (?, 'tenant', ?, 'account-service', " + + "'ACCOUNT_JOINED_PUBLIC_PRODUCTION', CURRENT_TIMESTAMP, 1, 1, ?, NULL, 'MINIMIZED', NULL)", + UUID.randomUUID(), + retry.tenantId(), + "sha256:" + "0".repeat(64)); + + for (int attempt = 0; attempt < 2; attempt++) { + AuthenticationException blocked = + assertThrows(AuthenticationException.class, () -> join(retry)); + assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } + + assertThat(countMemberships(retry)).isZero(); + assertThat(countMembershipTransitionReceipts(retry)).isZero(); + assertThat(countJoinOutbox(retry)).isZero(); + assertThat(countTenantJoinOutboxEvents(retry)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT status, last_attempt_failure_code FROM account_join_operations " + + "WHERE request_id = ?", + retry.requestId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("last_attempt_failure_code", String.class)) + .isEqualTo("AUTH_UNAVAILABLE"); + }); + assertThat( + dsl.resultQuery( + "SELECT delivery_status, payload FROM account_audit_outbox " + + "WHERE scope = 'tenant' AND tenant_id = ? " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + retry.tenantId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("delivery_status", String.class)).isEqualTo("MINIMIZED"); + assertThat(row.get("payload", String.class)).isNull(); + }); + } + + @Test + void absentMembershipWithRetainedReceiptFailsClosedWithoutResettingSequence() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + dsl.execute( + "DELETE FROM account_join_operations WHERE request_id = ?", initialJoin.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture retry = fixtureForMembership(initialJoin); + + AuthenticationException blocked = + assertThrows(AuthenticationException.class, () -> join(retry)); + + assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMemberships(retry)).isZero(); + assertThat(countMembershipTransitionReceipts(retry)).isEqualTo(1L); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat(countTenantJoinOutboxEvents(retry)).isEqualTo(1L); + } + + @Test + void retainedActiveOrInactiveMembershipWithoutTransitionReceiptFailsClosed() { + JoinFixture active = fixture("active"); + JoinFixture inactive = fixture("active"); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", + active.accountId(), + active.tenantId()); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'INACTIVE', 1, 1, 'EXPLICIT_JOIN')", + inactive.accountId(), + inactive.tenantId()); + + IllegalStateException activeFailure = + assertThrows( + IllegalStateException.class, + () -> + membershipTransitionReceiptRepository.findLatestReceipt( + active.accountId(), active.tenantId())); + IllegalStateException inactiveFailure = + assertThrows( + IllegalStateException.class, + () -> + membershipTransitionReceiptRepository.findLatestReceipt( + inactive.accountId(), inactive.tenantId())); + + assertThat(activeFailure) + .hasMessageContaining("Account membership exists without a provisional transition receipt"); + assertThat(inactiveFailure) + .hasMessageContaining("Account membership exists without a provisional transition receipt"); + assertThat(countMembershipTransitionReceipts(active)).isZero(); + assertThat(countMembershipTransitionReceipts(inactive)).isZero(); + + AuthenticationException activeJoinFailure = + assertThrows(AuthenticationException.class, () -> join(active)); + AuthenticationException inactiveJoinFailure = + assertThrows(AuthenticationException.class, () -> join(inactive)); + + assertThat(activeJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(inactiveJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMembershipTransitionReceipts(active)).isZero(); + assertThat(countMembershipTransitionReceipts(inactive)).isZero(); + assertThat( + dsl.resultQuery( + "SELECT lifecycle_state FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + inactive.accountId(), + inactive.tenantId()) + .fetchOne(0, String.class)) + .isEqualTo("INACTIVE"); } private JoinFixture fixture(String subscriptionStatus) { String suffix = UUID.randomUUID().toString(); - String requestId = "join-proof-" + suffix; - long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; long accountId = Objects.requireNonNull( dsl.resultQuery( @@ -261,12 +557,33 @@ private JoinFixture fixture(String subscriptionStatus) { "join-proof-" + suffix + "@example.com", "test-hash") .fetchOne(0, Long.class)); - dsl.execute( - "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", - accountId, - tenantId, - "join-proof", - subscriptionStatus); + return fixture(subscriptionStatus, accountId, null, suffix); + } + + private JoinFixture fixture(String subscriptionStatus, long accountId) { + return fixture(subscriptionStatus, accountId, null, UUID.randomUUID().toString()); + } + + private JoinFixture fixtureForMembership(JoinFixture existing) { + return fixture( + "active", existing.accountId(), existing.tenantId(), UUID.randomUUID().toString()); + } + + private JoinFixture fixture( + String subscriptionStatus, long accountId, Long existingTenantId, String suffix) { + String requestId = "join-proof-" + suffix; + long tenantId = + existingTenantId == null + ? UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE + : existingTenantId; + if (existingTenantId == null) { + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", + accountId, + tenantId, + "join-proof", + subscriptionStatus); + } GameplayRealm realm = GameplayRealm.newBuilder() @@ -296,7 +613,9 @@ private JoinFixture fixture(String subscriptionStatus) { .setPublicProductionRealm(true) .setStateScope("SHARED") .build(); - when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + fixtureRealms.put(tenantId, realm); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)) + .thenReturn(List.copyOf(fixtureRealms.values())); when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) .thenReturn(pointer); @@ -352,6 +671,95 @@ private long countJoinOutbox(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long countTenantJoinOutboxEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE scope = 'tenant' " + + "AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countMembershipTransitionReceipts(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private String receiptStreamKey(JoinFixture fixture) { + return MembershipTransitionReceiptDigest.receiptStreamKey( + fixture.accountId(), fixture.tenantId()); + } + + private void assertMembershipTransitionReceipt( + JoinFixture fixture, String transitionType, long expectedSequence) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, evidence_status, transition_type, " + + "request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, " + + "receipt_digest FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? AND receipt_sequence = ?", + fixture.accountId(), + fixture.tenantId(), + expectedSequence) + .fetchOne(); + assertThat(row).isNotNull(); + String streamKey = row.get("receipt_stream_key", String.class); + long sequence = row.get("receipt_sequence", Long.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + long membershipId = row.get("membership_id", Long.class); + String lifecycleState = row.get("membership_lifecycle_state", String.class); + boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + long membershipVersion = row.get("membership_version", Long.class); + long authorityGeneration = row.get("membership_authority_generation", Long.class); + String authorityProvenance = row.get("authority_provenance", String.class); + String requestId = row.get("request_id", String.class); + + assertThat(streamKey).isEqualTo(receiptStreamKey(fixture)); + assertThat(sequence).isEqualTo(expectedSequence); + String evidenceStatus = row.get("evidence_status", String.class); + assertThat(evidenceStatus).isEqualTo(MembershipTransitionReceiptDigest.EVIDENCE_STATUS); + assertThat(row.get("transition_type", String.class)).isEqualTo(transitionType); + assertThat(receiptId) + .isEqualTo(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId)); + assertThat(receiptDigest) + .isEqualTo( + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + fixture.accountId(), + fixture.tenantId(), + membershipId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance)); + assertThat( + membershipTransitionReceiptRepository.findLatestReceipt( + fixture.accountId(), fixture.tenantId())) + .contains( + new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + membershipId)); + } + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat( @@ -363,6 +771,8 @@ private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long member .fetchOne(0, Long.class)) .isEqualTo(1L); assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND payload LIKE ?", 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 a557f5b334..a71471b42b 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 @@ -22,6 +22,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; 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.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.service.ExpiredConnectScopeCleanupJob; @@ -62,6 +63,7 @@ class AccountRepositoryIntegrationTest { "account_profile_identity_migration_proof"; private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = "account_global_registration_migration_proof"; + private static final String ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA = "account_uuid_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -800,6 +802,55 @@ void saveCanonicalizesEmail() { assertThat(repository.findByEmail(" PLAYER@EXAMPLE.COM ")).isPresent(); } + @Test + void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { + Account saved = + repository.save( + account("uuid-account", "uuid-account@example.com", AccountLifecycleState.ACTIVE)); + UUID accountUuid = saved.getAccountUuid(); + + assertThat(accountUuid).isNotNull(); + assertThat(saved.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(saved.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + Account foundByNumericId = repository.findById(saved.getId()).orElseThrow(); + Account foundByUuid = repository.findByAccountUuid(accountUuid).orElseThrow(); + assertThat(foundByNumericId.getAccountUuid()).isEqualTo(accountUuid); + assertThat(foundByUuid.getId()).isEqualTo(saved.getId()); + assertThat(foundByUuid.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(foundByUuid.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + saved.setUsername("uuid-account-updated"); + Account updated = repository.save(saved); + assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); + assertThat(updated.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(updated.getAccountUuidSourceNumericId()).isEqualTo(updated.getId()); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "duplicate-uuid-account", + "duplicate-uuid-account@example.com", + "hash", + accountUuid, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_account_uuid_unique"); + + saved.setAccountUuid(UUID.randomUUID()); + assertThatThrownBy(() -> repository.save(saved)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Failed to update accounts id="); + assertThat(repository.findById(saved.getId()).orElseThrow().getAccountUuid()) + .isEqualTo(accountUuid); + } + @ParameterizedTest @NullSource @ValueSource(strings = {"", " "}) @@ -1093,6 +1144,354 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { .isEqualTo(0L); } + @Test + void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + String schema = ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("28") + .load() + .migrate(); + + long firstAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-one', 'uuid-retained-one@example.com', 'hash-one', 41) " + + "RETURNING id")) + .longValue(); + long secondAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-two', 'uuid-retained-two@example.com', 'hash-two', 42) " + + "RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + + schema + + ".profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", + firstAccountId, + 41L, + "Retained profile", + "retained bio"); + dsl.execute( + "INSERT INTO " + + schema + + ".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')", + firstAccountId, + 41L); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, TRUE, 'ACTIVE', 2, 3, 'EXPLICIT_JOIN')", + secondAccountId); + String pendingJoinRequestId = "retained-v28-pending-join"; + VerifiedJoinScope pendingJoinScopeBase = + new VerifiedJoinScope( + "retained-scope-token", + secondAccountId, + 42L, + UUID.fromString("61d40f5d-2d59-4cc5-8774-54f7445d144b"), + "retained-world", + "retained-realm", + "retained-namespace", + "REALM", + 7L, + 11L, + 13L, + "2026-09-01T11:59:00Z", + "2026-09-01T12:00:00Z", + null); + VerifiedJoinScope pendingJoinScope = + new VerifiedJoinScope( + pendingJoinScopeBase.connectScopeId(), + pendingJoinScopeBase.accountId(), + pendingJoinScopeBase.tenantId(), + pendingJoinScopeBase.realmId(), + pendingJoinScopeBase.worldSlug(), + pendingJoinScopeBase.realmSlug(), + pendingJoinScopeBase.playableStateNamespaceId(), + pendingJoinScopeBase.playableStateScope(), + pendingJoinScopeBase.gameInstanceId(), + pendingJoinScopeBase.catalogRevision(), + pendingJoinScopeBase.pointerVersion(), + pendingJoinScopeBase.evaluatedAt(), + pendingJoinScopeBase.connectScopeExpiresAt(), + AccountJoinDigest.scope(pendingJoinScopeBase)); + String scopeTokenHash = AccountJoinDigest.tokenHash(pendingJoinScope.connectScopeId()); + String scopeDigest = pendingJoinScope.snapshotDigest(); + String intentDigest = + AccountJoinDigest.intent(pendingJoinRequestId, pendingJoinScope, "retained-caller"); + dsl.execute( + "INSERT INTO " + + schema + + ".account_connect_scope_records " + + "(scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "snapshot_digest) " + + "VALUES (?, ?, 'PUBLIC_PRODUCTION', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scopeTokenHash, + pendingJoinScope.accountId(), + pendingJoinScope.tenantId(), + pendingJoinScope.realmId(), + pendingJoinScope.worldSlug(), + pendingJoinScope.realmSlug(), + pendingJoinScope.playableStateNamespaceId(), + pendingJoinScope.playableStateScope(), + pendingJoinScope.gameInstanceId(), + pendingJoinScope.catalogRevision(), + pendingJoinScope.pointerVersion(), + pendingJoinScope.evaluatedAt(), + pendingJoinScope.connectScopeExpiresAt(), + scopeDigest); + dsl.execute( + "INSERT INTO " + + schema + + ".account_join_operations " + + "(request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + + "connect_scope_digest, world_slug, realm_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, game_instance_id, catalog_revision, pointer_version, " + + "intent_digest_version, intent_digest, caller_bound_authority_invalidated, status) " + + "VALUES (?, ?, ?, 'retained-caller', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, FALSE, " + + "'PENDING')", + pendingJoinRequestId, + secondAccountId, + pendingJoinScope.tenantId(), + scopeTokenHash, + scopeDigest, + pendingJoinScope.worldSlug(), + pendingJoinScope.realmSlug(), + pendingJoinScope.realmId(), + pendingJoinScope.playableStateNamespaceId(), + pendingJoinScope.playableStateScope(), + pendingJoinScope.gameInstanceId(), + pendingJoinScope.catalogRevision(), + pendingJoinScope.pointerVersion(), + intentDigest); + + UUID auditEventId = UUID.fromString("1596dcce-a52c-4c39-86bf-138a06069012"); + String payload = "{\"accountId\":" + firstAccountId + ",\"event\":\"retained\"}"; + String payloadDigest = AccountAuditDigest.ofPayload(payload); + dsl.execute( + "INSERT INTO " + + schema + + ".account_audit_outbox " + + "(audit_event_id, scope, producer_service, event_type, occurred_at, schema_version, " + + "payload_digest_version, payload_digest, payload) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', " + + "TIMESTAMP '2026-09-01 12:00:00', 1, 1, ?, ?)", + auditEventId, + payloadDigest, + payload); + + String firstAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", firstAccountId); + String secondAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId); + String profileBefore = + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId); + String membershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId); + String explicitMembershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId); + String pendingJoinProjection = + "(to_jsonb(j) - 'reconciliation_attempt_count' - 'last_reconciliation_attempt_at' " + + "- 'last_reconciliation_attempt_reason' - 'next_reconciliation_attempt_at')::text"; + String pendingJoinBefore = + jsonRow( + "SELECT " + + pendingJoinProjection + + " FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId); + String connectScopeBefore = + jsonRow( + "SELECT to_jsonb(s)::text FROM " + + schema + + ".account_connect_scope_records s WHERE scope_token_hash = ?", + scopeTokenHash); + String outboxProjection = "(to_jsonb(o) - 'receiver_audit_projection_version')::text"; + String outboxBefore = + jsonRow( + "SELECT " + + outboxProjection + + " FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + String accountProjection = + "(to_jsonb(a) - 'account_uuid' - 'account_uuid_provenance' " + + "- 'account_uuid_source_numeric_id')::text"; + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + firstAccountId)) + .isEqualTo(firstAccountBefore); + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId)) + .isEqualTo(secondAccountBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId)) + .isEqualTo(profileBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId)) + .isEqualTo(membershipBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId)) + .isEqualTo(explicitMembershipBefore); + assertThat( + jsonRow( + "SELECT " + + pendingJoinProjection + + " FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId)) + .isEqualTo(pendingJoinBefore); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + schema + + ".account_join_operations WHERE request_id = ? " + + "AND reconciliation_attempt_count = 0 " + + "AND last_reconciliation_attempt_at IS NULL " + + "AND last_reconciliation_attempt_reason IS NULL " + + "AND next_reconciliation_attempt_at IS NOT NULL", + pendingJoinRequestId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + jsonRow( + "SELECT to_jsonb(s)::text FROM " + + schema + + ".account_connect_scope_records s WHERE scope_token_hash = ?", + scopeTokenHash)) + .isEqualTo(connectScopeBefore); + assertThat( + jsonRow( + "SELECT " + + outboxProjection + + " FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId)) + .isEqualTo(outboxBefore); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_outbox WHERE audit_event_id = ? " + + "AND receiver_audit_projection_version IS NULL", + auditEventId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + + UUID firstUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)); + UUID secondUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", + secondAccountId) + .fetchOne(0, UUID.class)); + assertThat(firstUuid).isNotEqualTo(secondUuid); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_provenance FROM " + schema + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, String.class)) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name()); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM " + + schema + + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, Long.class)) + .isEqualTo(firstAccountId); + assertThat( + dsl.resultQuery("SELECT COUNT(DISTINCT account_uuid) FROM " + schema + ".accounts") + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_outbox WHERE payload_digest = ?", + payloadDigest) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid = ? WHERE id = ?", + UUID.randomUUID(), + firstAccountId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Account identity cannot be reassigned"); + assertThat( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)) + .isEqualTo(firstUuid); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); @@ -1103,4 +1502,8 @@ private Account account(String username, String email, AccountLifecycleState lif account.setLifecycleState(lifecycleState); return account; } + + private String jsonRow(String query, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(query, bindings)).get(0, String.class); + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java new file mode 100644 index 0000000000..9dc8228ba4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java @@ -0,0 +1,136 @@ +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.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class LegacyTenantAssociationImportIntegrationTest { + private static final String SCHEMA = "account_tenant_association_proof"; + private static final long LEGACY_TENANT_ID = 41L; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .target("25") + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long accountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES ('retained-tenant', 'retained@example.test', 'hash', ?) " + + "RETURNING id", + LEGACY_TENANT_ID)) + .longValue(); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", + accountId, + LEGACY_TENANT_ID); + dsl.execute( + "INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, LEGACY_TENANT_ID); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + LegacyTenantSourceEvidence sources = new LegacyTenantSourceEvidence(dsl); + ApprovedLegacyTenantAssociationRepository repository = + new ApprovedLegacyTenantAssociationRepository(dsl, sources, SCHEMA); + String exactDigest = sources.digest(LEGACY_TENANT_ID); + ResolveLegacyAccountTenantAssociationResponse approved = ownerRead(exactDigest); + + assertThatThrownBy(() -> repository.importApproved(42L, approved)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mismatched"); + assertThatThrownBy( + () -> + repository.importApproved(LEGACY_TENANT_ID, ownerRead("sha256:" + "f".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs"); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).isEmpty(); + + var first = repository.importApproved(LEGACY_TENANT_ID, approved); + assertThat(first.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(first.accountEvidenceDigest()).isEqualTo(exactDigest); + assertThat(repository.importApproved(LEGACY_TENANT_ID, approved)).isEqualTo(first); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_approved_legacy_tenant_associations " + + "SET canonical_tenant_id = ? WHERE legacy_tenant_id = ?", + UUID.randomUUID(), + LEGACY_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Approved Account legacy tenant association is immutable"); + + dsl.execute( + "UPDATE account_legacy_tenant_sources SET disposition = 'CONFLICT' " + + "WHERE account_id = ?", + accountId); + assertThatThrownBy(() -> repository.importApproved(LEGACY_TENANT_ID, approved)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicting"); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + } + + private ResolveLegacyAccountTenantAssociationResponse ownerRead(String accountEvidenceDigest) { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(LEGACY_TENANT_ID) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setSourceLegacyGameTenantId("legacy-game-7") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest(accountEvidenceDigest) + .setOperationId("11111111-1111-4111-8111-111111111111") + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(SCHEMA) + .setSignerKeyId("game-design-owner-2026") + .setApprovedBy("owner@example.test") + .setApprovalReference("reviewed-change-123") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java new file mode 100644 index 0000000000..2ef2377d62 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +class AccountServiceApplicationTest { + private static final AtomicInteger BEAN_INITIALIZATIONS = new AtomicInteger(); + private static final AtomicInteger MIGRATION_SIDE_EFFECTS = new AtomicInteger(); + + @BeforeEach + void resetStartupEffects() { + BEAN_INITIALIZATIONS.set(0); + MIGRATION_SIDE_EFFECTS.set(0); + } + + @Test + void oneShotStartupRejectsMissingFlywaySettingBeforeBeanOrMigrationInitialization() { + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + assertThrows( + IllegalStateException.class, + () -> + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml")); + + assertEquals(0, BEAN_INITIALIZATIONS.get()); + assertEquals(0, MIGRATION_SIDE_EFFECTS.get()); + } + + @Test + void oneShotStartupRejectsEnabledOrInvalidFlywaySettingBeforeInitialization() { + for (String value : new String[] {"true", "enabled"}) { + resetStartupEffects(); + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + assertThrows( + IllegalStateException.class, + () -> + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml", + "--spring.flyway.enabled=" + value)); + + assertEquals(0, BEAN_INITIALIZATIONS.get()); + assertEquals(0, MIGRATION_SIDE_EFFECTS.get()); + } + } + + @Test + void explicitFlywayFalseAllowsOneShotStartupInitialization() { + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + try (var ignored = + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml", + "--spring.flyway.enabled=false")) { + assertEquals(2, BEAN_INITIALIZATIONS.get()); + assertEquals(1, MIGRATION_SIDE_EFFECTS.get()); + } + } + + @Configuration(proxyBeanMethods = false) + static class StartupProbeConfiguration { + @Bean + Object beanInitializationProbe() { + BEAN_INITIALIZATIONS.incrementAndGet(); + return new Object(); + } + + @Bean + ApplicationRunner migrationProbe() { + BEAN_INITIALIZATIONS.incrementAndGet(); + return args -> MIGRATION_SIDE_EFFECTS.incrementAndGet(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java new file mode 100644 index 0000000000..2ad14c6a89 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; + +class AccountSchedulingConfigurationTest { + @Test + void migrationModeDoesNotRegisterSchedulingPostProcessor() { + try (AnnotationConfigApplicationContext context = contextWithMigrationEnabled(true)) { + assertThat(context.getBeansOfType(ScheduledAnnotationBeanPostProcessor.class)).isEmpty(); + } + } + + @Test + void ordinaryModeRegistersSchedulingPostProcessor() { + try (AnnotationConfigApplicationContext context = contextWithMigrationEnabled(false)) { + assertThat(context.getBeansOfType(ScheduledAnnotationBeanPostProcessor.class)).hasSize(1); + } + } + + private static AnnotationConfigApplicationContext contextWithMigrationEnabled(boolean enabled) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test", Map.of("firemud.account-tenant-migration.enabled", enabled))); + context.register(AccountSchedulingConfiguration.class); + context.refresh(); + return context; + } +} 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 2969ddafd3..6fed8d221d 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 @@ -170,7 +170,7 @@ 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(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")) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java new file mode 100644 index 0000000000..e37dd11419 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class MembershipTransitionReceiptDigestTest { + @Test + void joinsUseTheNamespacedProvisionalReceiptIdentityAndDigestVector() { + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest("join-request-1"); + + assertThat(MembershipTransitionReceiptDigest.receiptStreamKey(42L, 7L)) + .isEqualTo("account:membership-transition-receipt:v1:membership/42/7"); + assertThat(receiptId).isEqualTo(UUID.fromString("171e5793-c53b-3308-934c-bdd7b7c0e13a")); + assertThat( + MembershipTransitionReceiptDigest.transitionDigest( + "account:membership-transition-receipt:v1:membership/42/7", + 1L, + receiptId, + "MEMBERSHIP_JOINED", + "join-request-1", + 42L, + 7L, + 18L, + "ACTIVE", + true, + 3L, + 4L, + "EXPLICIT_JOIN")) + .isEqualTo("sha256:2a07588ddf2444d1b4304cf5bd746365640fc30a2474dc3d0dbe0787d7cc494c"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java new file mode 100644 index 0000000000..6f931abb5b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.accountservice.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +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.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; + +class LegacyTenantAssociationImportJobRunnerTest { + @Test + void requiresFlywayDisabledAndExactDatabaseUserForEachMode() { + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "evidence", "firemud_account_tenant_evidence", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "import", "firemud_account_tenant_import", false)) + .doesNotThrowAnyException(); + + for (String[] wrongModeAndUser : + new String[][] { + {"evidence", "firemud_account_tenant_import"}, + {"import", "firemud_account_tenant_evidence"}, + {"evidence", "firemud"}, + {"import", "firemud_account_service"}, + {"evidence", null}, + {"import", ""}, + {"evidence", " "} + }) { + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + wrongModeAndUser[0], wrongModeAndUser[1], false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB credential does not match the mode"); + } + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "unsupported", "firemud_account_tenant_evidence", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unsupported Account tenant migration mode"); + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "evidence", "firemud_account_tenant_evidence", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration requires Flyway to be disabled"); + } + + @Test + void readsAndClosesTheActualJdbcConnectionForDatabaseIdentity() throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn("firemud_account_tenant_evidence"); + + assertThat(runner(dataSource).connectedDatabaseUsername()) + .isEqualTo("firemud_account_tenant_evidence"); + verify(connection).close(); + } + + @Test + void rejectsMissingOrUnverifiableJdbcIdentityWithoutLeakingDriverDetails() throws Exception { + for (String username : new String[] {null, "", " "}) { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn(username); + + assertThatThrownBy(() -> runner(dataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection did not identify its user"); + verify(connection).close(); + } + + DataSource unavailableDataSource = mock(DataSource.class); + when(unavailableDataSource.getConnection()) + .thenThrow(new SQLException("sensitive driver credential diagnostic")); + assertThatThrownBy(() -> runner(unavailableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive driver credential diagnostic"); + + DataSource missingMetadataDataSource = mock(DataSource.class); + Connection missingMetadataConnection = mock(Connection.class); + when(missingMetadataDataSource.getConnection()).thenReturn(missingMetadataConnection); + when(missingMetadataConnection.getMetaData()).thenReturn(null); + assertThatThrownBy(() -> runner(missingMetadataDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection is unverifiable"); + verify(missingMetadataConnection).close(); + + DataSource unverifiableDataSource = mock(DataSource.class); + Connection unverifiableConnection = mock(Connection.class); + when(unverifiableDataSource.getConnection()).thenReturn(unverifiableConnection); + when(unverifiableConnection.getMetaData()) + .thenThrow(new SQLException("sensitive metadata credential diagnostic")); + assertThatThrownBy(() -> runner(unverifiableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive metadata credential diagnostic"); + verify(unverifiableConnection).close(); + } + + @Test + void failsBeforeOwnerEvidenceOrImportWhenSchedulingIsPresent() { + Environment environment = mock(Environment.class); + LegacyTenantAssociationImportService importService = + mock(LegacyTenantAssociationImportService.class); + @SuppressWarnings("unchecked") + ObjectProvider schedulingPostProcessor = + mock(ObjectProvider.class); + ScheduledAnnotationBeanPostProcessor processor = + mock(ScheduledAnnotationBeanPostProcessor.class); + when(schedulingPostProcessor.getIfAvailable()).thenReturn(processor); + + LegacyTenantAssociationImportJobRunner runner = + new LegacyTenantAssociationImportJobRunner( + environment, importService, schedulingPostProcessor, mock(DataSource.class)); + + assertThatThrownBy(() -> runner.run(new DefaultApplicationArguments())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("scheduling enabled"); + verifyNoInteractions(importService); + } + + @Test + void acceptsOnlyExactDedicatedMigratorCertificate() { + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireJobIdentity( + "dev", peer("dev", "account-tenant-migrator"))) + .doesNotThrowAnyException(); + for (GrpcPeerIdentity wrong : + new GrpcPeerIdentity[] { + null, + peer("dev", "account-service"), + peer("pr-12", "account-tenant-migrator"), + peer("dev", "game-design-tenant-migrator") + }) { + assertThatThrownBy( + () -> LegacyTenantAssociationImportJobRunner.requireJobIdentity("dev", wrong)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong identity"); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + @SuppressWarnings("unchecked") + private static LegacyTenantAssociationImportJobRunner runner(DataSource dataSource) { + return new LegacyTenantAssociationImportJobRunner( + mock(Environment.class), + mock(LegacyTenantAssociationImportService.class), + mock(ObjectProvider.class), + dataSource); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java index 211338bcfb..fa52c73c14 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -27,13 +27,42 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws .contains( "V28__account_audit_delivery_backoff.sql", "V37__verified_audit_projection_evidence.sql", - "V38__account_join_reconciliation.sql") - .doesNotContain("V28__account_join_reconciliation.sql"); + "V38__account_join_reconciliation.sql", + "V40__account_membership_transition_receipts.sql", + "V41__protect_account_membership_transition_receipts.sql") + .doesNotContain( + "V28__account_join_reconciliation.sql", + "V28__account_membership_transition_receipts.sql", + "V28.1__account_membership_transition_receipts.sql"); assertThat(migrations.stream().map(AccountMigrationVersionTest::version).toList()) .as("Flyway rejects two different migration descriptions with the same version") .doesNotHaveDuplicates(); assertThat(version("V28__account_audit_delivery_backoff.sql")) .isEqualTo(version("V28__account_join_reconciliation.sql")); + assertThat(version("V40__account_membership_transition_receipts.sql")) + .isGreaterThan(version("V38__account_join_reconciliation.sql")) + .isGreaterThan(MigrationVersion.fromVersion("39.1")); + assertThat(version("V41__protect_account_membership_transition_receipts.sql")) + .isGreaterThan(version("V40__account_membership_transition_receipts.sql")); + } + + @Test + void receiptProtectionMigrationGuardsOnlyUpdatesAndDeletesWithoutDocker() throws IOException { + String migration = + Files.readString( + Path.of( + "src/main/resources/db/migration/" + + "V41__protect_account_membership_transition_receipts.sql")); + + assertThat(migration) + .contains( + "CREATE TRIGGER account_membership_transition_receipts_append_only", + "BEFORE UPDATE OR DELETE ON account_membership_transition_receipts", + "EXECUTE FUNCTION reject_account_membership_transition_receipt_mutation()") + .doesNotContain( + "BEFORE INSERT ON account_membership_transition_receipts", + "INSERT OR UPDATE OR DELETE ON account_membership_transition_receipts", + "ON account_membership_transition_receipt_stream_heads"); } private static MigrationVersion version(String name) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java new file mode 100644 index 0000000000..6f7f3c5e17 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.Base64; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class ApprovedLegacyTenantAssociationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final LegacyTenantSourceEvidence sources = mock(LegacyTenantSourceEvidence.class); + private final ApprovedLegacyTenantAssociationRepository repository = + new ApprovedLegacyTenantAssociationRepository(dsl, sources, "proof"); + + @Test + void mismatchedOrIncompleteOwnerReadNeverTouchesRetainedRows() { + ResolveLegacyAccountTenantAssociationResponse valid = response().build(); + + assertThatThrownBy(() -> repository.importApproved(42L, valid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.importApproved( + 41L, response().setTargetNamespace("other-namespace").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> repository.importApproved(41L, response().clearManifestSignature().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> repository.importApproved(41L, response().clearCanonicalTenantId().build())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl, sources); + } + + private ResolveLegacyAccountTenantAssociationResponse.Builder response() { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(41L) + .setCanonicalTenantId("22222222-2222-4222-8222-222222222222") + .setSourceLegacyGameTenantId("legacy-game-7") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest("sha256:" + "a".repeat(64)) + .setOperationId("11111111-1111-4111-8111-111111111111") + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace("proof") + .setSignerKeyId("game-design-owner-2026") + .setApprovedBy("owner@example.test") + .setApprovalReference("reviewed-change-123") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java index c4b429974e..0402e58dbf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -21,6 +21,8 @@ import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; @@ -28,6 +30,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.ConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import org.junit.jupiter.api.Test; @@ -63,8 +66,7 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( @@ -87,9 +89,156 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { verify(fixture.joinOperations, never()) .recordReconciliationAttempt( anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); + verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); } + @Test + void priorMembershipHistoryCommitsEventFreeAlreadyActiveOutcome() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + stubReceiptFor(fixture, "prior-join-request", MEMBERSHIP_ID); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "ALREADY_ACTIVE", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + verify(fixture.auditOutbox, never()) + .append(any(), anyString(), any(), anyString(), anyString()); + } + + @Test + void mismatchedPriorMembershipReceiptStaysPending() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + stubReceiptFor(fixture, "prior-join-request", MEMBERSHIP_ID + 1L); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void missingTransitionReceiptDoesNotInferJoinedFromMembershipAndAuditAlone() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.transitionReceipts.findLatestReceipt(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.auditOutbox); + } + + @Test + void missingMembershipAfterScopeExpiryStaysPendingAndRecordsBackoffReason() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.auditOutbox, fixture.transitionReceipts); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + } + @ParameterizedTest @MethodSource("unverifiedAuditDeliveryEvidence") void incompleteOrLegacyAuditDeliveryEvidenceStaysPending( @@ -100,8 +249,7 @@ void incompleteOrLegacyAuditDeliveryEvidenceStaysPending( when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( @@ -192,8 +340,7 @@ void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.empty()); when(fixture.joinOperations.recordReconciliationAttempt( @@ -288,8 +435,7 @@ void wrongPayloadDigestStaysPending() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( @@ -328,8 +474,7 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); String mismatchedPayload = joinAuditEnvelope("other-world", TENANT_ID, "unused").payload(); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( @@ -395,7 +540,7 @@ void wrongRetainedTargetStaysPending() { NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); - verifyNoInteractions(fixture.memberships, fixture.auditOutbox); + verifyNoInteractions(fixture.memberships, fixture.transitionReceipts, fixture.auditOutbox); } @Test @@ -407,8 +552,7 @@ void repeatedRunDoesNotFinishSameJoinTwice() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( @@ -450,13 +594,19 @@ void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { verify(fixture.joinOperations, never()) .recordReconciliationAttempt( anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); - verifyNoInteractions(fixture.connectScopes, fixture.memberships, fixture.auditOutbox); + verifyNoInteractions( + fixture.connectScopes, + fixture.memberships, + fixture.transitionReceipts, + fixture.auditOutbox); } private static Fixture fixture(int maxAttempts) { AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountMembershipTransitionReceiptRepository transitionReceipts = + mock(AccountMembershipTransitionReceiptRepository.class); AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); when(transactionManager.getTransaction(any(TransactionDefinition.class))) @@ -467,6 +617,7 @@ private static Fixture fixture(int maxAttempts) { joinOperations, connectScopes, memberships, + transitionReceipts, auditOutbox, meterRegistry, transactionManager, @@ -474,7 +625,52 @@ private static Fixture fixture(int maxAttempts) { maxAttempts, 5_000); return new Fixture( - service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); + service, + joinOperations, + connectScopes, + memberships, + transitionReceipts, + auditOutbox, + meterRegistry); + } + + private static void stubActiveMembership(Fixture fixture) { + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(activeJoinMembership())); + stubReceiptFor(fixture, REQUEST_ID, MEMBERSHIP_ID); + } + + private static void stubReceiptFor(Fixture fixture, String requestId, long membershipId) { + String receiptStreamKey = + MembershipTransitionReceiptDigest.receiptStreamKey(ACCOUNT_ID, TENANT_ID); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); + String receiptDigest = + MembershipTransitionReceiptDigest.transitionDigest( + receiptStreamKey, + 1L, + receiptId, + "MEMBERSHIP_JOINED", + requestId, + ACCOUNT_ID, + TENANT_ID, + membershipId, + "ACTIVE", + true, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + "EXPLICIT_JOIN"); + when(fixture.transitionReceipts.findLatestReceipt(ACCOUNT_ID, TENANT_ID)) + .thenReturn( + Optional.of( + new MembershipTransitionReceipt( + receiptStreamKey, + 1L, + receiptId, + receiptDigest, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + requestId, + membershipId))); } private static void stubDue(Fixture fixture, JoinOperation operation) { @@ -692,6 +888,7 @@ private record Fixture( AccountJoinOperationRepository joinOperations, AccountConnectScopeRepository connectScopes, AccountTenantMembershipRepository memberships, + AccountMembershipTransitionReceiptRepository transitionReceipts, AccountAuditOutboxRepository auditOutbox, SimpleMeterRegistry meterRegistry) {} } 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 2c17d3b3c7..a94d0254cc 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 @@ -56,6 +56,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -103,6 +104,7 @@ class AccountServiceImplTest { @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; + @Mock private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -213,6 +215,7 @@ void setup() { accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, + membershipTransitionReceiptRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -482,6 +485,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); account.setLifecycleState(lifecycleState); AuthenticationException exception = @@ -1552,6 +1556,7 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig retainJoinEvidence(retainedScope, retainedOperation); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); VerifiedJoinScope scope = retainedScope.get(); String requestId = "join-global-collision-" + originalStatus.toLowerCase(); String originalOutcome = @@ -1703,7 +1708,7 @@ void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { quarantined.setLifecycleState("LEGACY_UNVERIFIED"); quarantined.setGameplayAdmissionAllowed(false); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(quarantined)); + .thenReturn(Optional.of(membership(account, 7L)), Optional.of(quarantined)); Subscription active = new Subscription(); active.setId(22L); active.setTenantId(7L); @@ -2408,6 +2413,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, + membershipTransitionReceiptRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -3504,6 +3510,139 @@ void issueConnectTokenReturnsShortLivedConnectToken() { org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(30000L)); + org.mockito.Mockito.verifyNoInteractions(accountRealmAccessGrantRepository); + } + + @Test + void issueConnectTokenRejectsLegacyGrantWithoutLifecycleProof() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-grant"))); + + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void issueConnectTokenRejectsNonPublicRealmWhenCurrentGrantIsMissing() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, false); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-grant-denied"))); + + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(context.connectScopeId()), + org.mockito.ArgumentMatchers.eq("req-private-grant-denied"), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && "REALM_ACCESS_DENIED".equals(replay.errorCode())), + org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); + } + + @Test + void issueConnectTokenRequiresJoinForInactivePublicMembership() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePublicInactiveConnectTokenContext(account, true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-inactive-public-join"))); + + assertEquals("JOIN_REQUIRED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), "req-inactive-public-join", "JOIN_REQUIRED"); + } + + @Test + void issueConnectTokenRejectsInactivePublicMembershipWhenJoiningIsDisabled() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePublicInactiveConnectTokenContext(account, false); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest( + context.connectScopeId(), "req-inactive-public-policy-denied"))); + + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), + "req-inactive-public-policy-denied", + "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + + @Test + void issueConnectTokenRequiresActiveMembershipForNonPublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = + preparePrivateConnectTokenContext(account, true, "INACTIVE"); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-inactive-private"))); + + assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), "req-inactive-private", "CONNECT_TOKEN_REJECTED"); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -3728,7 +3867,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { } @Test - void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { + void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3754,6 +3893,32 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); + org.mockito.Mockito.clearInvocations(sessionService); + + ConnectTokenResult replayed = + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + + assertEquals(firstResult.connectToken(), replayed.connectToken()); + assertEquals(firstResult.issuedAt(), replayed.issuedAt()); + assertEquals(firstResult.expiresAt(), replayed.expiresAt()); + assertEquals(firstResult.requestId(), replayed.requestId()); + assertTrue(replayed.replayed()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -3773,16 +3938,127 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + org.mockito.Mockito.clearInvocations(sessionService); - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + AuthenticationException staleReplayException = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", staleReplayException.getCode()); + verifyCachedConnectTokenReplayDidNotWrite(); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,JOIN_REQUIRED", + "INACTIVE,JOIN_REQUIRED", + "NON_ADMITTING,CONNECT_TOKEN_REJECTED" + }) + void issueConnectTokenRevalidatesMembershipBeforeCachedSuccessReplay( + String currentMembershipState, String expectedCode) { + CachedPublicConnectTokenReplay cached = prepareCachedPublicConnectTokenReplay(); + if ("MISSING".equals(currentMembershipState)) { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + } else { + Account account = new Account(); + account.setId(11L); + AccountTenantMembership currentMembership = membership(account, 7L); + if ("INACTIVE".equals(currentMembershipState)) { + currentMembership.setLifecycleState("INACTIVE"); + currentMembership.setGameplayAdmissionAllowed(false); + } else { + currentMembership.setGameplayAdmissionAllowed(false); + } + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(currentMembership)); + } + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); + org.mockito.Mockito.clearInvocations(sessionService); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + cached.bootstrapToken(), + new ConnectTokenRequest(cached.connectScopeId(), cached.requestId()))); + + assertEquals(expectedCode, exception.getCode()); + verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyCachedConnectTokenReplayDidNotWrite(); + } + + @ParameterizedTest + @CsvSource({"BLOCKED,TENANT_BILLING_BLOCKED", "UNAVAILABLE,ENTITLEMENT_UNAVAILABLE"}) + void issueConnectTokenRevalidatesEntitlementBeforeCachedSuccessReplay( + String currentEntitlementState, String expectedCode) { + CachedPublicConnectTokenReplay cached = prepareCachedPublicConnectTokenReplay(); + if ("BLOCKED".equals(currentEntitlementState)) { + Subscription canceled = new Subscription(); + canceled.setId(22L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + } else { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + } + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); + org.mockito.Mockito.clearInvocations(sessionService); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + cached.bootstrapToken(), + new ConnectTokenRequest(cached.connectScopeId(), cached.requestId()))); + + assertEquals(expectedCode, exception.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .findByAccountIdAndTenantId(11L, 7L); + verifyCachedConnectTokenReplayDidNotWrite(); + } + + @Test + void issueConnectTokenRejectsCachedSuccessForNonPublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + ConnectTokenResult cachedResult = + new ConnectTokenResult( + 11L, + 7L, + 55L, + "preview", + context.connectScopeId(), + "cached-private-connect-token", + "cached-jti", + "req-private-cached", + "2026-09-30T00:00:00Z", + "2026-09-30T00:00:30Z", + false); + when(sessionService.getConnectTokenReplay( + 7L, 11L, context.connectScopeId(), "req-private-cached")) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, cachedResult, "", ""))); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-cached"))); + + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -3893,8 +4169,20 @@ void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + // Current INACTIVE membership suppresses new discovery, so exercise the selected-target check + // with a valid signed scope retained from an earlier eligible snapshot. String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + retainedConnectScopeForTest( + 11L, + 7L, + REALM_ID, + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); AuthenticationException exception = assertThrows( @@ -3986,6 +4274,34 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); + if (!publicProductionRealm) { + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + AccountTenantMembership deniedMembership = membership(account, 7L); + deniedMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(deniedMembership)); + + AuthenticationException privateException = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-membership-denied"))); + + assertEquals("CONNECT_TOKEN_REJECTED", privateException.getCode()); + assertEquals( + "Gameplay admission is not allowed for this account", privateException.getMessage()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + return; + } when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountTenantMembership deniedMembership = membership(account, 7L); @@ -4206,10 +4522,10 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); if (membershipExists) { - AccountTenantMembership membership = membership(account, 7L); - membership.setGameplayAdmissionAllowed(false); + AccountTenantMembership nonAdmittingMembership = membership(account, 7L); + nonAdmittingMembership.setGameplayAdmissionAllowed(false); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership)); + .thenReturn(Optional.of(nonAdmittingMembership)); } else { when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.empty()); @@ -4223,7 +4539,17 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + retainedConnectScopeForTest( + 11L, + 7L, + REALM_ID, + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); AuthenticationException exception = assertThrows( @@ -4301,8 +4627,20 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + // Current INACTIVE membership suppresses new discovery, so exercise the selected-target check + // with a valid signed scope retained from an earlier eligible snapshot. String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + retainedConnectScopeForTest( + 11L, + 7L, + REALM_ID, + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); AuthenticationException exception = assertThrows( @@ -4348,9 +4686,11 @@ void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnav bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .findByAccountIdAndTenantId(11L, 7L); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); - verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); + verifyNoInteractions(entityManagementClient); } @Test @@ -4359,13 +4699,36 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + context.bootstrapToken(), "demo", "preview", context.connectScopeId())); + + assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); + assertEquals( + "Existing game membership is required for this non-public realm", exception.getMessage()); + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + } + + @Test + void + listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterReachableDiscovery() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); + .thenReturn(Optional.empty()); var privateRealm = net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() .setWorldSlug("demo") @@ -4406,8 +4769,20 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + // The retained scope names a realm whose slug is "production", but its pointer is explicitly + // private. A missing membership must not inherit public JOIN behavior from the slug. String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + retainedConnectScopeForTest( + 11L, + 7L, + REALM_ID, + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); AuthenticationException exception = assertThrows( @@ -4417,9 +4792,30 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); - assertEquals( - "Existing game membership is required for this non-public realm", exception.getMessage()); verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "production"); + } + + @Test + void listBootstrapCharactersRejectsLegacyGrantWithoutLifecycleProof() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + context.bootstrapToken(), "demo", "preview", context.connectScopeId())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -4645,28 +5041,6 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { .build())); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.of(membership(account, 7L))); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -4676,10 +5050,13 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { .findByTenantId(7L); var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - assertEquals(2, firstCall.size()); - assertEquals(2, secondCall.size()); + assertEquals(1, firstCall.size()); + assertEquals("production", firstCall.getFirst().realmSlug()); + assertEquals(1, secondCall.size()); + assertEquals("production", secondCall.getFirst().realmSlug()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); + verifyNoInteractions(accountRealmAccessGrantRepository); } @Test @@ -5547,7 +5924,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( @ParameterizedTest @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( + void listBootstrapRealmsDoesNotUseLegacyGrantAsLifecycleProof( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); @@ -5601,23 +5978,25 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - assertEquals(1, realms.size()); - assertEquals("preview", realms.getFirst().realmSlug()); - assertFalse(realms.getFirst().connectScopeId().isBlank()); + assertTrue(realms.isEmpty()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( - boolean visible, boolean publicProductionRealm) { + @CsvSource({"true", "false"}) + void listBootstrapRealmsExcludesInactiveMembershipDespiteAdmissionFlag( + boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); + .thenReturn(Optional.of(inactiveMembership)); Subscription active = new Subscription(); active.setId(22L); active.setTenantId(7L); @@ -5636,7 +6015,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) - .setVisible(visible) + .setVisible(true) .setPublicProductionRealm(publicProductionRealm) .setRequiresCharacterSelection(false) .setStateScope("SHARED") @@ -5655,7 +6034,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) - .setVisible(visible) + .setVisible(true) .setPublicProductionRealm(publicProductionRealm) .setRequiresCharacterSelection(false) .setStateScope("SHARED") @@ -5667,25 +6046,40 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + } + + @Test + void issueConnectTokenRequiresMembershipForPrivateTargetDespiteLegacyGrant() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, () -> service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-preview-1"))); + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-preview-1"))); assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); assertEquals( "Existing game membership is required for this non-public realm", exception.getMessage()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); org.mockito.Mockito.verify(sessionService) .storeConnectTokenReplay( org.mockito.ArgumentMatchers.eq(7L), org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq(context.connectScopeId()), org.mockito.ArgumentMatchers.eq("req-preview-1"), org.mockito.ArgumentMatchers.argThat( replay -> @@ -6386,6 +6780,203 @@ private static String hash(String password) { } } + private String retainedConnectScopeForTest( + long accountId, + long tenantId, + String realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) { + java.time.Instant evaluatedAt = java.time.Instant.now(); + java.time.Instant expiresAt = + evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + return new JwtUtil(JWT_SECRET, 30000L) + .generateToken( + Long.toString(accountId), + tokenProperties.getConnectScopeExpirationMs(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", accountId), + Map.entry("tenantId", tenantId), + Map.entry("realmId", realmId), + Map.entry("worldSlug", worldSlug), + Map.entry("realmSlug", realmSlug), + Map.entry("playableStateNamespaceId", playableStateNamespaceId), + Map.entry("playableStateScope", playableStateScope), + Map.entry("gameInstanceId", gameInstanceId), + Map.entry("catalogRevision", catalogRevision), + Map.entry("pointerVersion", pointerVersion), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()))); + } + + private PrivateConnectTokenContext preparePrivateConnectTokenContext( + Account account, boolean grantAtIssuance) { + return preparePrivateConnectTokenContext(account, grantAtIssuance, "ACTIVE"); + } + + private PrivateConnectTokenContext preparePrivateConnectTokenContext( + Account account, boolean grantAtIssuance, String membershipLifecycleState) { + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership tenantMembership = membership(account, 7L); + tenantMembership.setLifecycleState(membershipLifecycleState); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(tenantMembership)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer(7L, "demo", "preview", "55", 19L, true, false, "SHARED", "ALLOW_NEW")); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(grantAtIssuance); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + java.time.Instant evaluatedAt = java.time.Instant.now(); + java.time.Instant expiresAt = + evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + // Simulate a retained legacy scope that has no lifecycle-qualified grant evidence. + String connectScopeId = + new JwtUtil(JWT_SECRET, 30000L) + .generateToken( + "11", + tokenProperties.getConnectScopeExpirationMs(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", 11L), + Map.entry("tenantId", 7L), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "preview"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", 55L), + Map.entry("catalogRevision", 23L), + Map.entry("pointerVersion", 19L), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()))); + return new PrivateConnectTokenContext(bootstrap.bootstrapToken(), connectScopeId); + } + + private PrivateConnectTokenContext preparePublicInactiveConnectTokenContext( + Account account, boolean publicJoiningAllowed) { + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership tenantMembership = membership(account, 7L); + tenantMembership.setLifecycleState("INACTIVE"); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L)), Optional.of(tenantMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(publicJoiningAllowed ? "active" : "grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + return new PrivateConnectTokenContext(bootstrap.bootstrapToken(), connectScopeId); + } + + private void verifyConnectTokenFailureDoesNotStoreSuccess( + String connectScopeId, String requestId, String errorCode) { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && errorCode.equals(replay.errorCode())), + org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); + } + + private CachedPublicConnectTokenReplay prepareCachedPublicConnectTokenReplay() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String requestId = "req-cached-current-authority"; + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, requestId); + ConnectTokenResult storedResult = + service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, requestId)) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, storedResult, "", ""))); + return new CachedPublicConnectTokenReplay( + bootstrap.bootstrapToken(), connectScopeId, requestId); + } + + private void verifyCachedConnectTokenReplayDidNotWrite() { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + } + + private record CachedPublicConnectTokenReplay( + String bootstrapToken, String connectScopeId, String requestId) {} + + private record PrivateConnectTokenContext(String bootstrapToken, String connectScopeId) {} + private DirectTextJoinScope issueDirectTextConnectScopeForTest() { Account account = new Account(); account.setId(11L); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java index 3d15d9f402..1a596507b4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java @@ -28,10 +28,12 @@ public record GrpcPeerIdentity(String uri, String namespace, String service) { public static final Set ALLOWED_SERVICE_NAMES = Set.of( "account-service", + "account-tenant-migrator", "automation-scripting-service", "entity-management-service", "game-design-baseline-migrator", "game-design-service", + "game-design-tenant-migrator", "game-logic-service", "game-session-service", "logging-admin-service", diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java index 2887f94192..233625d94c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java @@ -39,6 +39,19 @@ void extractsDedicatedEntityBaselineMigratorIdentity() throws Exception { .containsExactly(uri, "firemud", "game-design-baseline-migrator"); } + @Test + void extractsOnlyTheTwoDedicatedTenantMigratorIdentityNames() throws Exception { + for (String service : List.of("account-tenant-migrator", "game-design-tenant-migrator")) { + String uri = "spiffe://firemud/ns/firemud/sa/" + service; + assertThat(GrpcPeerIdentity.fromSslSession(sessionWithUriSans(uri))) + .get() + .extracting(GrpcPeerIdentity::uri, GrpcPeerIdentity::namespace, GrpcPeerIdentity::service) + .containsExactly(uri, "firemud", service); + } + assertThat(GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/tenant-migrator")) + .isEmpty(); + } + @Test void normalizesCanonicalEquivalentUriSanBeforeValidatingWorkloadIdentity() { assertThat(GrpcPeerIdentity.parseUri("spiffe://FIREMUD/ns/%66iremud/sa/game-%64esign-service")) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 684c2f417d..66e4367eaa 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -17,7 +17,8 @@ class AccountRuntimeStubServerTest { @Test - void authenticationAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exception { + void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComplete() + throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); @@ -35,21 +36,21 @@ void authenticationAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exce .getAccountId()) .isEqualTo("7"); - var activeMembership = - stub.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("7") - .setTenantId("1") - .setRequestId("request-active") - .build()); + var request = + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-1") + .build(); + var activeMembership = stub.getTenantMembershipForRuntime(request); assertThat(activeMembership.getMembershipExists()).isTrue(); assertThat(activeMembership.getGameplayAdmissionAllowed()).isTrue(); assertThat(activeMembership.getMembershipLifecycleState()).isEqualTo("ACTIVE"); assertThat(activeMembership.getMembershipVersion()).isEqualTo(1L); - assertThat(activeMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertThat(activeMembership.getMembershipAuthorityGeneration()).isPositive(); assertFresh(activeMembership.getEvaluatedAt()); - server.denyGameplayAdmission(); + server.setGameplayAdmissionAllowed(false); var deniedMembership = stub.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() @@ -64,15 +65,14 @@ void authenticationAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exce assertThat(deniedMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); assertFresh(deniedMembership.getEvaluatedAt()); - server.setMembershipExists(false); + server.setMembershipInactive(); + var inactive = stub.getTenantMembershipForRuntime(request); + assertThat(inactive.getMembershipExists()).isTrue(); + assertThat(inactive.getGameplayAdmissionAllowed()).isFalse(); + assertThat(inactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); - var membership = - stub.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("7") - .setTenantId("1") - .setRequestId("request-1") - .build()); + server.setMembershipExists(false); + var membership = stub.getTenantMembershipForRuntime(request); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index c7b85f190b..07e677ce1b 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -13,6 +13,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -54,6 +55,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final List authenticateRequests = new CopyOnWriteArrayList<>(); private final AtomicBoolean membershipExists = new AtomicBoolean(true); private final AtomicBoolean gameplayAdmissionAllowed = new AtomicBoolean(true); + private final AtomicReference membershipLifecycleState = new AtomicReference<>("ACTIVE"); private final AtomicBoolean gameplayAvailable = new AtomicBoolean(true); private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); @@ -104,6 +106,7 @@ public void setMembershipExists(boolean exists) { gameplayAdmissionAllowed.set(false); } membershipExists.set(exists); + membershipLifecycleState.set(exists ? "ACTIVE" : "MISSING"); } public void allowGameplayAdmission() { @@ -116,6 +119,12 @@ public void denyGameplayAdmission() { setGameplayAdmissionAllowed(false); } + public void setMembershipInactive() { + setMembershipExists(true); + setGameplayAdmissionAllowed(false); + membershipLifecycleState.set("INACTIVE"); + } + public void setGameplayAvailable(boolean available) { gameplayAvailable.set(available); } @@ -132,6 +141,7 @@ public void resetRuntimeState() { authenticateRequests.clear(); membershipExists.set(true); gameplayAdmissionAllowed.set(true); + membershipLifecycleState.set("ACTIVE"); gameplayAvailable.set(true); allowPublicJoin.set(true); realmAccessGranted.set(true); @@ -170,9 +180,9 @@ public void getTenantMembershipForRuntime( .setAccountId(request.getAccountId()) .setTenantId(request.getTenantId()) .setMembershipExists(exists) + .setMembershipLifecycleState(membershipLifecycleState.get()) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .setMembershipVersion(exists ? 1L : 0L) - .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") .setMembershipAuthorityGeneration(exists ? 1L : 0L) .setEvaluatedAt(Instant.now().toString()) .build()); @@ -319,6 +329,7 @@ public void joinPublicProductionMembership( } else { membershipExists.set(true); gameplayAdmissionAllowed.set(true); + membershipLifecycleState.set("ACTIVE"); responseObserver.onNext( JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(true) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java index 2e5663f873..346e38e895 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java @@ -5,6 +5,7 @@ import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; @@ -13,14 +14,15 @@ @Import(GlobalExceptionHandler.class) public class GameDesignServiceApplication { public static void main(String[] args) { - if ("true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED"))) { - if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null - || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { - throw new IllegalStateException( - "migration Job must not receive the shared JWT signing key"); - } + MigrationMode migrationMode = + selectMigrationMode( + System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED"), + System.getenv("FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED")); + if (migrationMode != MigrationMode.NORMAL) { + requireNoSharedJwtSecret(); SpringApplication application = new SpringApplication(GameDesignServiceApplication.class); application.setWebApplicationType(WebApplicationType.NONE); + application.addInitializers(new RequireFlywayDisabledInitializer()); application.setDefaultProperties( java.util.Map.of( "spring.main.web-application-type", "none", @@ -36,4 +38,47 @@ public static void main(String[] args) { SpringApplication.run(GameDesignServiceApplication.class, args); } } + + static MigrationMode selectMigrationMode(String entityBaseline, String tenantAssociation) { + boolean entityBaselineEnabled = "true".equals(entityBaseline); + boolean tenantAssociationEnabled = "true".equals(tenantAssociation); + if (entityBaselineEnabled && tenantAssociationEnabled) { + throw new IllegalStateException( + "Game Design one-shot migration modes cannot be enabled together"); + } + if (entityBaselineEnabled) { + return MigrationMode.ENTITY_BASELINE; + } + if (tenantAssociationEnabled) { + return MigrationMode.TENANT_ASSOCIATION; + } + return MigrationMode.NORMAL; + } + + enum MigrationMode { + NORMAL, + ENTITY_BASELINE, + TENANT_ASSOCIATION + } + + static final class RequireFlywayDisabledInitializer + implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + String flywayEnabled = + applicationContext.getEnvironment().getProperty("spring.flyway.enabled"); + if (!"false".equalsIgnoreCase(flywayEnabled)) { + throw new IllegalStateException( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + } + } + } + + private static void requireNoSharedJwtSecret() { + if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null + || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { + throw new IllegalStateException( + "Game Design migration Job must not receive the shared JWT key"); + } + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java index 83572c7198..204de77695 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamedesign.entity; +import java.util.UUID; import lombok.Data; @Data public class Game { private Long id; private String tenantId; + private UUID canonicalTenantId; private String name; private String description; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java new file mode 100644 index 0000000000..d035d50b7c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +/** One approved, exact legacy Account-key to Game Design tenant association operation. */ +public record TenantAssociationManifest( + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + Instant signedAt, + List entries) { + public TenantAssociationManifest { + if (entries != null) { + entries = List.copyOf(entries); + } + } + + @Override + public List entries() { + return entries == null ? null : List.copyOf(entries); + } + + public record Entry( + long legacyAccountTenantId, + String legacyGameTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String accountEvidenceDigest) {} + + public record Signed(TenantAssociationManifest manifest, String ed25519Signature) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java new file mode 100644 index 0000000000..e31dcca75b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.Map; +import javax.sql.DataSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** Opt-in, owner-approved one-shot migration; no service mutation endpoint is exposed. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.tenant-association-migration", + name = "enabled", + havingValue = "true") +public class TenantAssociationManifestJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(TenantAssociationManifestJobRunner.class); + private static final String MIGRATOR_SERVICE_ACCOUNT = "game-design-tenant-migrator"; + + private final Environment environment; + private final ObjectMapper objectMapper; + private final TenantAssociationMigrationService migrationService; + private final DataSource dataSource; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") + public TenantAssociationManifestJobRunner( + Environment environment, + ObjectMapper objectMapper, + TenantAssociationMigrationService migrationService, + DataSource dataSource) { + this.environment = environment; + this.objectMapper = objectMapper.copy(); + this.migrationService = migrationService; + this.dataSource = dataSource; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!"true".equals(System.getenv("FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true) + || environment.getProperty("firemud.temporal.enabled", Boolean.class, true)) { + throw new IllegalStateException("tenant migration must not start listeners or workers"); + } + String mode = required("firemud.tenant-association-migration.mode"); + requireDatabaseAuthority( + mode, + connectedDatabaseUsername(), + environment.getProperty("spring.flyway.enabled", Boolean.class, true)); + String podNamespace = required("firemud.tenant-association-migration.pod-namespace"); + String targetNamespace = required("firemud.tenant-association-migration.target-namespace"); + if (!podNamespace.equals(targetNamespace) + || !MIGRATOR_SERVICE_ACCOUNT.equals( + required("firemud.tenant-association-migration.pod-service-account"))) { + throw new IllegalStateException("tenant migration Job has the wrong workload scope"); + } + requireJobIdentity(podNamespace, verifiedWorkloadIdentity()); + Path manifestPath = + Path.of(required("firemud.tenant-association-migration.signed-manifest-path")); + Path publicKeysPath = + Path.of(required("firemud.tenant-association-migration.owner-public-keys-path")); + ObjectMapper strictMapper = + objectMapper + .copy() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); + Signed signed = strictMapper.readValue(Files.readAllBytes(manifestPath), Signed.class); + Map trustedKeys = + strictMapper.readValue( + Files.readAllBytes(publicKeysPath), new TypeReference>() {}); + var verified = TenantAssociationManifestVerifier.verify(signed, trustedKeys); + if (!targetNamespace.equals(verified.manifest().targetNamespace())) { + throw new IllegalStateException("signed tenant manifest targets a different namespace"); + } + if ("preflight".equals(mode)) { + LOG.info( + "Tenant association preflight operationId={} manifestDigest={} entries={} namespace={}", + verified.manifest().operationId(), + verified.manifestDigest(), + verified.manifest().entries().size(), + targetNamespace); + } else if ("apply".equals(mode)) { + var applied = migrationService.apply(signed, trustedKeys, targetNamespace); + LOG.info( + "Tenant association applied operationId={} manifestDigest={} readbackEntries={} namespace={}", + verified.manifest().operationId(), + verified.manifestDigest(), + applied.size(), + targetNamespace); + } else { + throw new IllegalArgumentException("unsupported tenant migration Job mode"); + } + } + + static void requireDatabaseAuthority(String mode, String username, boolean flywayEnabled) { + if (flywayEnabled) { + throw new IllegalStateException("tenant migration requires Flyway to be disabled"); + } + String requiredUsername = + switch (mode) { + case "preflight" -> "firemud_game_design_tenant_preflight"; + case "apply" -> "firemud_game_design_tenant_apply"; + default -> throw new IllegalArgumentException("unsupported tenant migration Job mode"); + }; + if (!requiredUsername.equals(username)) { + throw new IllegalStateException("tenant migration DB credential does not match the mode"); + } + } + + String connectedDatabaseUsername() { + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metadata = connection == null ? null : connection.getMetaData(); + if (metadata == null) { + throw new IllegalStateException("tenant migration DB connection is unverifiable"); + } + String username = metadata.getUserName(); + if (username == null || username.isBlank()) { + throw new IllegalStateException("tenant migration DB connection did not identify its user"); + } + return username; + } catch (SQLException failure) { + // Avoid surfacing driver diagnostics that can echo the configured database username. + throw new IllegalStateException("tenant migration DB connection could not be verified"); + } + } + + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { + if (identity == null + || !identity.isService(MIGRATOR_SERVICE_ACCOUNT) + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException("tenant migration certificate has the wrong identity"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> new IllegalStateException("tenant migration certificate lacks a valid URI SAN")); + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java new file mode 100644 index 0000000000..b78237441c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; + +/** Verifies owner approval over a versioned, byte-length-framed manifest preimage. */ +public final class TenantAssociationManifestVerifier { + private static final String DOMAIN = "firemud/legacy-tenant-association-manifest/v1"; + private static final int MAX_ENTRIES = 5000; + + private TenantAssociationManifestVerifier() {} + + public static Verified verify(Signed signed, Map trustedPublicKeys) { + if (signed == null || signed.manifest() == null || trustedPublicKeys == null) { + throw new IllegalArgumentException("approved tenant-association manifest is required"); + } + TenantAssociationManifest manifest = signed.manifest(); + validate(manifest); + String encodedKey = trustedPublicKeys.get(manifest.signerKeyId()); + if (encodedKey == null || encodedKey.isBlank()) { + throw new IllegalArgumentException("manifest signer is not trusted"); + } + byte[] preimage = preimage(manifest); + try { + PublicKey publicKey = + KeyFactory.getInstance("Ed25519") + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey))); + Signature signature = Signature.getInstance("Ed25519"); + signature.initVerify(publicKey); + signature.update(preimage); + byte[] signatureBytes = + signed.ed25519Signature() == null + ? new byte[0] + : Base64.getDecoder().decode(signed.ed25519Signature()); + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signed.ed25519Signature()) + || !signature.verify(signatureBytes)) { + throw new IllegalArgumentException("manifest owner signature is invalid"); + } + String digest = + "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + return new Verified(manifest, digest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("manifest owner signature cannot be verified", ex); + } + } + + /** Exact bytes the offline Game Design owner signs for this manifest version. */ + public static byte[] preimage(TenantAssociationManifest manifest) { + validate(manifest); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + write(output, DOMAIN); + output.writeInt(manifest.schemaVersion()); + write(output, manifest.operationId().toString()); + write(output, manifest.targetNamespace()); + write(output, manifest.signerKeyId()); + write(output, manifest.approvedBy()); + write(output, manifest.approvalReference()); + write(output, manifest.signedAt().toString()); + output.writeInt(manifest.entries().size()); + for (Entry entry : manifest.entries()) { + output.writeLong(entry.legacyAccountTenantId()); + write(output, entry.legacyGameTenantId()); + write(output, entry.canonicalTenantId().toString()); + output.writeLong(entry.sourceGameRowId()); + write(output, entry.accountEvidenceDigest()); + } + return bytes.toByteArray(); + } catch (IOException ex) { + throw new IllegalStateException("in-memory manifest framing failed", ex); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(bytes.length); + output.write(bytes); + } + + private static void validate(TenantAssociationManifest manifest) { + if (manifest.schemaVersion() != 1 + || manifest.operationId() == null + || !valid(manifest.targetNamespace(), 63) + || !valid(manifest.signerKeyId(), 128) + || !valid(manifest.approvedBy(), 256) + || !valid(manifest.approvalReference(), 512) + || manifest.signedAt() == null + || manifest.entries() == null + || manifest.entries().isEmpty() + || manifest.entries().size() > MAX_ENTRIES) { + throw new IllegalArgumentException("manifest scope, approval, or version is invalid"); + } + Set gameKeys = new HashSet<>(); + Set canonicalIds = new HashSet<>(); + Set gameRows = new HashSet<>(); + long previousAccountKey = 0; + for (Entry entry : manifest.entries()) { + if (entry == null + || entry.legacyAccountTenantId() <= previousAccountKey + || !valid(entry.legacyGameTenantId(), 36) + || entry.canonicalTenantId() == null + || entry.sourceGameRowId() <= 0 + || entry.accountEvidenceDigest() == null + || !entry.accountEvidenceDigest().matches("sha256:[0-9a-f]{64}") + || !gameKeys.add(entry.legacyGameTenantId()) + || !canonicalIds.add(entry.canonicalTenantId()) + || !gameRows.add(entry.sourceGameRowId())) { + throw new IllegalArgumentException("manifest entries are malformed or ambiguous"); + } + previousAccountKey = entry.legacyAccountTenantId(); + } + } + + private static boolean valid(String value, int maxLength) { + return value != null + && !value.isBlank() + && value.length() <= maxLength + && value.chars().noneMatch(Character::isISOControl); + } + + public record Verified(TenantAssociationManifest manifest, String manifestDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java index f9a4d6c07c..2d3c2c6c40 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java @@ -3,10 +3,12 @@ import net.firedevops.firemud.gamedesign.dto.GameDto; import net.firedevops.firemud.gamedesign.entity.Game; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface GameMapper { GameDto toDto(Game entity); + @Mapping(target = "canonicalTenantId", ignore = true) Game toEntity(GameDto dto); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index 57bce6b96d..94e35866c9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -2,7 +2,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -18,6 +21,14 @@ public class GameRepository { private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_IDENTITY_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field TENANT_IDENTITY_SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); private static final Field NAME = DSL.field(DSL.name("name"), String.class); private static final Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); @@ -33,22 +44,67 @@ public List findAll() { public Game save(Game game) { if (game.getId() == null) { + if (game.getCanonicalTenantId() != null) { + throw new IllegalArgumentException("Canonical tenant identity is issued by Game Design"); + } + UUID canonicalTenantId = UUID.randomUUID(); Record record = dsl.insertInto(GAME_TABLE) .set(TENANT_ID, game.getTenantId()) + .set(CANONICAL_TENANT_ID, canonicalTenantId) .set(NAME, game.getName()) .set(DESCRIPTION, game.getDescription()) - .returning(ID, TENANT_ID, NAME, DESCRIPTION) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) .fetchOne(); - return toEntity(record); + if (record == null) { + throw new IllegalStateException("Game insert did not return its persisted row"); + } + Game saved = toEntity(record); + GameTenantIdentity persistedIdentity = toTenantIdentity(record); + if (saved == null + || !canonicalTenantId.equals(saved.getCanonicalTenantId()) + || persistedIdentity.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW + || !saved.getId().equals(persistedIdentity.sourceGameId()) + || !saved.getTenantId().equals(persistedIdentity.sourceLegacyTenantId())) { + throw new IllegalStateException("Persisted game tenant identity did not match issuance"); + } + return saved; } - dsl.update(GAME_TABLE) - .set(TENANT_ID, game.getTenantId()) - .set(NAME, game.getName()) - .set(DESCRIPTION, game.getDescription()) - .where(ID.eq(game.getId())) - .execute(); - return findByTenantId(game.getTenantId()); + Condition identityCondition = ID.eq(game.getId()); + if (game.getTenantId() != null) { + identityCondition = identityCondition.and(TENANT_ID.eq(game.getTenantId())); + } + if (game.getCanonicalTenantId() != null) { + identityCondition = + identityCondition.and(CANONICAL_TENANT_ID.eq(game.getCanonicalTenantId())); + } + Record record = + dsl.update(GAME_TABLE) + .set(NAME, game.getName()) + .set(DESCRIPTION, game.getDescription()) + .where(identityCondition) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) + .fetchOne(); + if (record == null) { + throw new IllegalStateException("Game update identity does not match a persisted game row"); + } + return toEntity(record); } public Game findByTenantId(String tenantId) { @@ -58,6 +114,17 @@ public Game findByTenantId(String tenantId) { .fetchOne(this::toEntity); } + public Optional findTenantIdentityByLegacyTenantId(String legacyTenantId) { + return dsl.select( + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(TENANT_ID.eq(legacyTenantId)) + .fetchOptional(record -> toTenantIdentity(record, legacyTenantId)); + } + public Game findByTenantIdForUpdate(String tenantId) { return dsl.selectFrom(GAME_TABLE) .where(TENANT_ID.eq(tenantId)) @@ -72,8 +139,39 @@ private Game toEntity(Record record) { Game game = new Game(); game.setId(record.get(ID)); game.setTenantId(record.get(TENANT_ID)); + game.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); game.setName(record.get(NAME)); game.setDescription(record.get(DESCRIPTION)); return game; } + + private GameTenantIdentity toTenantIdentity(Record record) { + return toTenantIdentity(record, null); + } + + private GameTenantIdentity toTenantIdentity(Record record, String expectedLegacyTenantId) { + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); + Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); + String sourceLegacyTenantId = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); + if (canonicalTenantId == null + || provenanceKindValue == null + || sourceGameId == null + || sourceGameId <= 0 + || sourceLegacyTenantId == null + || sourceLegacyTenantId.isBlank() + || (expectedLegacyTenantId != null + && !expectedLegacyTenantId.equals(sourceLegacyTenantId))) { + throw new IllegalStateException("Persisted game tenant identity provenance is incomplete"); + } + GameTenantIdentity.ProvenanceKind provenanceKind; + try { + provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Persisted game tenant identity provenance kind is unknown", exception); + } + return new GameTenantIdentity( + canonicalTenantId, provenanceKind, sourceGameId, sourceLegacyTenantId); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java new file mode 100644 index 0000000000..5c8faea07e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.util.UUID; + +/** Game Design's provenance-bearing canonical tenant identity sourced from its game row. */ +public record GameTenantIdentity( + UUID canonicalTenantId, + ProvenanceKind provenanceKind, + Long sourceGameId, + String sourceLegacyTenantId) { + public enum ProvenanceKind { + RETAINED_GAME_V30, + NEW_GAME_ROW + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java new file mode 100644 index 0000000000..d434db464b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier.Verified; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Guarded, immutable Game Design owner assertion for an approved legacy tenant manifest. */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class TenantAssociationMigrationService { + private final DSLContext dsl; + private final GameRepository gameRepository; + + public TenantAssociationMigrationService(DSLContext dsl, GameRepository gameRepository) { + this.dsl = dsl; + this.gameRepository = gameRepository; + } + + @Transactional + public List apply( + Signed signed, Map trustedPublicKeys, String exactNamespace) { + Verified verified = TenantAssociationManifestVerifier.verify(signed, trustedPublicKeys); + TenantAssociationManifest manifest = Objects.requireNonNull(verified).manifest(); + if (exactNamespace == null || !exactNamespace.equals(manifest.targetNamespace())) { + throw new IllegalArgumentException("manifest targets a different namespace"); + } + List existing = findByOperation(manifest.operationId()); + if (!existing.isEmpty() || operationExists(manifest.operationId())) { + assertExactReadback(verified, signed.ed25519Signature(), existing); + return existing; + } + + for (Entry entry : manifest.entries()) { + requireExactSource( + entry.legacyGameTenantId(), entry.canonicalTenantId(), entry.sourceGameRowId()); + } + + int inserted = + dsl.execute( + "INSERT INTO legacy_account_tenant_association_operations " + + "(operation_id, manifest_digest, signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, entry_count, schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (operation_id) DO NOTHING", + manifest.operationId(), + verified.manifestDigest(), + signed.ed25519Signature(), + manifest.targetNamespace(), + manifest.signerKeyId(), + manifest.approvedBy(), + manifest.approvalReference(), + manifest.signedAt().toString(), + manifest.entries().size(), + manifest.schemaVersion()); + if (inserted == 0) { + List concurrent = findByOperation(manifest.operationId()); + assertExactReadback(verified, signed.ed25519Signature(), concurrent); + return concurrent; + } + for (Entry entry : manifest.entries()) { + dsl.execute( + "INSERT INTO legacy_account_tenant_associations " + + "(legacy_account_tenant_id, legacy_game_tenant_id, canonical_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + entry.legacyAccountTenantId(), + entry.legacyGameTenantId(), + entry.canonicalTenantId(), + entry.sourceGameRowId(), + entry.accountEvidenceDigest(), + manifest.operationId()); + } + List committed = findByOperation(manifest.operationId()); + assertExactReadback(verified, signed.ed25519Signature(), committed); + return committed; + } + + @Transactional(readOnly = true) + public Optional findByLegacyAccountTenantId(long legacyAccountTenantId) { + if (legacyAccountTenantId <= 0) { + return Optional.empty(); + } + Record row = + dsl.fetchOne( + "SELECT a.legacy_account_tenant_id, a.legacy_game_tenant_id, " + + "a.canonical_tenant_id, a.source_game_row_id, a.account_evidence_digest, " + + "o.operation_id, o.manifest_digest, o.signature, o.target_namespace, o.signer_key_id, " + + "o.approved_by, o.approval_reference, o.signed_at, o.entry_count, " + + "o.schema_version " + + "FROM legacy_account_tenant_associations a " + + "JOIN legacy_account_tenant_association_operations o " + + "ON o.operation_id = a.operation_id " + + "WHERE a.legacy_account_tenant_id = ?", + legacyAccountTenantId); + return Optional.ofNullable(row) + .map(this::map) + .map( + association -> { + requireExactSource( + association.legacyGameTenantId(), + association.canonicalTenantId(), + association.sourceGameRowId()); + return association; + }); + } + + private void requireExactSource(String legacyGameTenantId, UUID canonicalTenantId, long gameId) { + GameTenantIdentity identity = + gameRepository + .findTenantIdentityByLegacyTenantId(legacyGameTenantId) + .orElseThrow(() -> new IllegalStateException("manifest Game Design source is absent")); + if (!canonicalTenantId.equals(identity.canonicalTenantId()) + || !legacyGameTenantId.equals(identity.sourceLegacyTenantId()) + || !Long.valueOf(gameId).equals(identity.sourceGameId())) { + throw new IllegalStateException("manifest Game Design source identity changed"); + } + } + + private boolean operationExists(UUID operationId) { + return Boolean.TRUE.equals( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM legacy_account_tenant_association_operations " + + "WHERE operation_id = ?)", + operationId)) + .get(0, Boolean.class)); + } + + private List findByOperation(UUID operationId) { + List result = new ArrayList<>(); + for (Record row : + dsl.fetch( + "SELECT a.legacy_account_tenant_id, a.legacy_game_tenant_id, " + + "a.canonical_tenant_id, a.source_game_row_id, a.account_evidence_digest, " + + "o.operation_id, o.manifest_digest, o.signature, o.target_namespace, o.signer_key_id, " + + "o.approved_by, o.approval_reference, o.signed_at, o.entry_count, " + + "o.schema_version " + + "FROM legacy_account_tenant_associations a " + + "JOIN legacy_account_tenant_association_operations o " + + "ON o.operation_id = a.operation_id " + + "WHERE o.operation_id = ? ORDER BY a.legacy_account_tenant_id", + operationId)) { + result.add(map(row)); + } + return List.copyOf(result); + } + + private ApprovedAssociation map(Record row) { + return new ApprovedAssociation( + row.get(0, Long.class), + row.get(1, String.class), + row.get(2, UUID.class), + row.get(3, Long.class), + row.get(4, String.class), + row.get(5, UUID.class), + row.get(6, String.class), + row.get(7, String.class), + row.get(8, String.class), + row.get(9, String.class), + row.get(10, String.class), + row.get(11, String.class), + row.get(12, String.class), + row.get(13, Integer.class), + row.get(14, Integer.class)); + } + + private void assertExactReadback( + Verified verified, String signature, List rows) { + TenantAssociationManifest manifest = verified.manifest(); + if (rows.size() != manifest.entries().size()) { + throw new IllegalStateException("manifest operation readback count differs"); + } + for (int index = 0; index < rows.size(); index++) { + Entry expected = manifest.entries().get(index); + ApprovedAssociation actual = rows.get(index); + if (actual.legacyAccountTenantId() != expected.legacyAccountTenantId() + || !actual.legacyGameTenantId().equals(expected.legacyGameTenantId()) + || !actual.canonicalTenantId().equals(expected.canonicalTenantId()) + || actual.sourceGameRowId() != expected.sourceGameRowId() + || !actual.accountEvidenceDigest().equals(expected.accountEvidenceDigest()) + || !actual.operationId().equals(manifest.operationId()) + || !actual.manifestDigest().equals(verified.manifestDigest()) + || !actual.signature().equals(signature) + || !actual.targetNamespace().equals(manifest.targetNamespace()) + || !actual.signerKeyId().equals(manifest.signerKeyId()) + || !actual.approvedBy().equals(manifest.approvedBy()) + || !actual.approvalReference().equals(manifest.approvalReference()) + || !actual.signedAt().equals(manifest.signedAt().toString()) + || actual.entryCount() != manifest.entries().size() + || actual.schemaVersion() != manifest.schemaVersion()) { + throw new IllegalStateException("manifest operation readback differs"); + } + requireExactSource( + actual.legacyGameTenantId(), actual.canonicalTenantId(), actual.sourceGameRowId()); + } + } + + public record ApprovedAssociation( + long legacyAccountTenantId, + String legacyGameTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String accountEvidenceDigest, + UUID operationId, + String manifestDigest, + String signature, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + int entryCount, + int schemaVersion) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java new file mode 100644 index 0000000000..7ff3a9aaac --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Base64; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Game Design's own retained tenant identity provenance. */ +@GrpcService +public class TenantIdentityGrpcService + extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { + private final GameRepository gameRepository; + private final TenantAssociationMigrationService associationService; + private final String workloadNamespace; + + public TenantIdentityGrpcService( + GameRepository gameRepository, + TenantAssociationMigrationService associationService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.gameRepository = gameRepository; + this.associationService = associationService; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveLegacyGameTenantIdentity( + ResolveLegacyGameTenantIdentityRequest request, + StreamObserver responseObserver) { + if (!isAccountPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Account workload identity is required") + .asRuntimeException()); + return; + } + + String sourceKey = request.getLegacyGameTenantId(); + if (sourceKey.isBlank() || sourceKey.length() > 36) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact legacy Game Design tenant key is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = gameRepository.findTenantIdentityByLegacyTenantId(sourceKey); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity is ambiguous or provenance is invalid") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Game Design tenant identity for exact source key") + .asRuntimeException()); + return; + } + GameTenantIdentity identity = resolved.orElseThrow(); + if (identity.canonicalTenantId() == null + || identity.sourceGameId() == null + || identity.sourceGameId() <= 0 + || identity.provenanceKind() == null + || !sourceKey.equals(identity.sourceLegacyTenantId())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity provenance is incomplete") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveLegacyGameTenantIdentityResponse.newBuilder() + .setCanonicalTenantId(identity.canonicalTenantId().toString()) + .setSourceLegacyGameTenantId(identity.sourceLegacyTenantId()) + .setSourceGameRowId(identity.sourceGameId()) + .setProvenanceKind(identity.provenanceKind().name()) + .build()); + responseObserver.onCompleted(); + } + + @Override + public void resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest request, + StreamObserver responseObserver) { + if (!isAccountTenantMigratorPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Account tenant migrator identity is required") + .asRuntimeException()); + return; + } + if (request.getLegacyAccountTenantId() <= 0) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Positive exact legacy Account tenant key is required") + .asRuntimeException()); + return; + } + Optional resolved; + try { + resolved = associationService.findByLegacyAccountTenantId(request.getLegacyAccountTenantId()); + } catch (IllegalStateException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Approved tenant association provenance is invalid") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No approved association for exact Account legacy tenant key") + .asRuntimeException()); + return; + } + ApprovedAssociation association = resolved.orElseThrow(); + if (!workloadNamespace.equals(association.targetNamespace()) + || association.legacyAccountTenantId() != request.getLegacyAccountTenantId() + || association.canonicalTenantId() == null + || association.sourceGameRowId() <= 0 + || association.operationId() == null + || association.accountEvidenceDigest() == null + || !association.accountEvidenceDigest().matches("sha256:[0-9a-f]{64}") + || association.manifestDigest() == null + || !association.manifestDigest().matches("sha256:[0-9a-f]{64}") + || !validSignature(association.signature()) + || association.entryCount() <= 0 + || association.schemaVersion() != 1) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Approved tenant association readback is incomplete") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(association.legacyAccountTenantId()) + .setSourceLegacyGameTenantId(association.legacyGameTenantId()) + .setCanonicalTenantId(association.canonicalTenantId().toString()) + .setSourceGameRowId(association.sourceGameRowId()) + .setAccountEvidenceDigest(association.accountEvidenceDigest()) + .setOperationId(association.operationId().toString()) + .setManifestDigest(association.manifestDigest()) + .setTargetNamespace(association.targetNamespace()) + .setSignerKeyId(association.signerKeyId()) + .setApprovedBy(association.approvedBy()) + .setApprovalReference(association.approvalReference()) + .setSignedAt(association.signedAt()) + .setOperationEntryCount(association.entryCount()) + .setManifestSignature(association.signature()) + .setManifestSchemaVersion(association.schemaVersion()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace != null + && !workloadNamespace.isBlank() + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); + } + + private boolean isAccountTenantMigratorPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace != null + && !workloadNamespace.isBlank() + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-tenant-migrator"); + } + + private static boolean validSignature(String value) { + if (value == null) { + return false; + } + try { + byte[] decoded = Base64.getDecoder().decode(value); + return decoded.length == 64 && Base64.getEncoder().encodeToString(decoded).equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 15cca178a6..b6a7fd1f31 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -47,6 +47,10 @@ server: min-response-size: 1024 firemud: + auth: + grpc: + public-methods: + - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 4de4297c8d..ef3a36676c 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -71,6 +71,9 @@ firemud: path-pattern: /ping/ - method: GET path-pattern: /.well-known/** + grpc: + public-methods: + - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/db/migration/V30.1__canonical_game_tenant_identity.sql b/services/game-design-service/src/main/resources/db/migration/V30.1__canonical_game_tenant_identity.sql new file mode 100644 index 0000000000..4230a0793f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V30.1__canonical_game_tenant_identity.sql @@ -0,0 +1,61 @@ +ALTER TABLE game + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN tenant_identity_provenance_kind VARCHAR(32), + ADD COLUMN tenant_identity_source_game_id BIGINT, + ADD COLUMN tenant_identity_source_legacy_tenant_id VARCHAR(36); + +UPDATE game +SET canonical_tenant_id = gen_random_uuid(), + tenant_identity_provenance_kind = 'RETAINED_GAME_V30', + tenant_identity_source_game_id = id, + tenant_identity_source_legacy_tenant_id = tenant_id; + +ALTER TABLE game ALTER COLUMN canonical_tenant_id SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_provenance_kind SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_source_game_id SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_source_legacy_tenant_id SET NOT NULL; +ALTER TABLE game ADD CONSTRAINT uq_game_canonical_tenant_id UNIQUE (canonical_tenant_id); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_provenance_kind + CHECK (tenant_identity_provenance_kind IN ('RETAINED_GAME_V30', 'NEW_GAME_ROW')); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_source_game + CHECK (tenant_identity_source_game_id = id); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_source_legacy_tenant + CHECK (tenant_identity_source_legacy_tenant_id = tenant_id); + +-- [jooq ignore start] +ALTER TABLE game + ALTER COLUMN canonical_tenant_id SET DEFAULT gen_random_uuid(); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION enforce_game_tenant_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + NEW.tenant_identity_provenance_kind := 'NEW_GAME_ROW'; + NEW.tenant_identity_source_game_id := NEW.id; + NEW.tenant_identity_source_legacy_tenant_id := NEW.tenant_id; + RETURN NEW; + END IF; + + IF NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + RAISE EXCEPTION 'game legacy tenant_id is immutable after canonical tenant identity issuance' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.tenant_identity_provenance_kind IS DISTINCT FROM OLD.tenant_identity_provenance_kind + OR NEW.tenant_identity_source_game_id IS DISTINCT FROM OLD.tenant_identity_source_game_id + OR NEW.tenant_identity_source_legacy_tenant_id IS DISTINCT FROM OLD.tenant_identity_source_legacy_tenant_id THEN + RAISE EXCEPTION 'game canonical tenant identity and provenance are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_tenant_identity_immutable + BEFORE INSERT OR UPDATE ON game + FOR EACH ROW + EXECUTE FUNCTION enforce_game_tenant_identity(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql b/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql new file mode 100644 index 0000000000..3ab664e045 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql @@ -0,0 +1,48 @@ +-- A Game Design owner-approved manifest is the only source of a retained Account +-- numeric tenant key to canonical Game Design tenant UUID association. No row is +-- inferred from matching numeric/text keys or inserted by this migration. +CREATE TABLE legacy_account_tenant_association_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + manifest_digest VARCHAR(71) NOT NULL UNIQUE, + signature VARCHAR(128) NOT NULL, + target_namespace VARCHAR(128) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at VARCHAR(40) NOT NULL, + entry_count INTEGER NOT NULL CHECK (entry_count > 0), + committed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT legacy_tenant_manifest_digest_shape + CHECK (manifest_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT legacy_tenant_signature_shape + CHECK (length(signature) = 88) +); + +CREATE TABLE legacy_account_tenant_associations ( + legacy_account_tenant_id BIGINT PRIMARY KEY CHECK (legacy_account_tenant_id > 0), + legacy_game_tenant_id VARCHAR(36) NOT NULL UNIQUE, + canonical_tenant_id UUID NOT NULL UNIQUE, + source_game_row_id BIGINT NOT NULL UNIQUE REFERENCES game(id), + account_evidence_digest VARCHAR(71) NOT NULL, + operation_id UUID NOT NULL REFERENCES legacy_account_tenant_association_operations(operation_id), + CONSTRAINT legacy_tenant_account_evidence_digest_shape + CHECK (account_evidence_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION reject_legacy_tenant_association_change() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Approved legacy tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER legacy_tenant_association_operation_immutable + BEFORE UPDATE OR DELETE ON legacy_account_tenant_association_operations + FOR EACH ROW EXECUTE FUNCTION reject_legacy_tenant_association_change(); + +CREATE TRIGGER legacy_tenant_association_immutable + BEFORE UPDATE OR DELETE ON legacy_account_tenant_associations + FOR EACH ROW EXECUTE FUNCTION reject_legacy_tenant_association_change(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java new file mode 100644 index 0000000000..bc76dcda40 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -0,0 +1,276 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +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 GameTenantIdentityRepositoryIntegrationTest { + private static final String SERVICE_SCHEMA = "game_design_service"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final org.jooq.Field ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final org.jooq.Field SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final org.jooq.Field SOURCE_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migratesRetainedGamesAndIssuesImmutableProvenanceForNewGames() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + migrate(dataSource, MigrationVersion.fromVersion("29")); + + long retainedAlphaId; + long retainedBetaId; + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + retainedAlphaId = insertLegacyGame(dsl, "legacy-tenant-alpha", "Alpha", "alpha-data"); + retainedBetaId = insertLegacyGame(dsl, "legacy-tenant-beta", "Beta", "beta-data"); + } + + migrate(dataSource, null); + + UUID retainedAlphaCanonicalId; + UUID retainedBetaCanonicalId; + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + var retainedRows = + dsl.select( + ID, + TENANT_ID, + NAME, + DESCRIPTION, + CANONICAL_TENANT_ID, + PROVENANCE_KIND, + SOURCE_GAME_ID, + SOURCE_LEGACY_TENANT_ID) + .from(GAME) + .orderBy(ID.asc()) + .fetch(); + + assertThat(retainedRows).hasSize(2); + assertThat(retainedRows) + .extracting(row -> row.get(TENANT_ID)) + .containsExactly("legacy-tenant-alpha", "legacy-tenant-beta"); + assertThat(retainedRows).extracting(row -> row.get(NAME)).containsExactly("Alpha", "Beta"); + assertThat(retainedRows) + .extracting(row -> row.get(DESCRIPTION)) + .containsExactly("alpha-data", "beta-data"); + assertThat(retainedRows) + .extracting(row -> row.get(PROVENANCE_KIND)) + .containsOnly("RETAINED_GAME_V30"); + assertThat(retainedRows) + .extracting(row -> row.get(SOURCE_GAME_ID)) + .containsExactly(retainedAlphaId, retainedBetaId); + assertThat(retainedRows) + .extracting(row -> row.get(SOURCE_LEGACY_TENANT_ID)) + .containsExactly("legacy-tenant-alpha", "legacy-tenant-beta"); + + retainedAlphaCanonicalId = retainedRows.get(0).get(CANONICAL_TENANT_ID); + retainedBetaCanonicalId = retainedRows.get(1).get(CANONICAL_TENANT_ID); + assertThat(retainedAlphaCanonicalId).isNotNull().isNotEqualTo(retainedBetaCanonicalId); + + migrate(dataSource, null); + assertThat( + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(ID.eq(retainedAlphaId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isEqualTo(retainedAlphaCanonicalId); + assertThat( + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(ID.eq(retainedBetaId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isEqualTo(retainedBetaCanonicalId); + + GameRepository repository = new GameRepository(dsl); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-alpha")) + .contains( + new GameTenantIdentity( + retainedAlphaCanonicalId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + retainedAlphaId, + "legacy-tenant-alpha")); + Game newGame = new Game(); + newGame.setTenantId("legacy-tenant-new"); + newGame.setName("New"); + newGame.setDescription("new-data"); + Game saved = repository.save(newGame); + + assertThat(saved.getCanonicalTenantId()) + .isNotNull() + .isNotEqualTo(retainedAlphaCanonicalId) + .isNotEqualTo(retainedBetaCanonicalId); + assertThat(repository.findByTenantId("legacy-tenant-new").getCanonicalTenantId()) + .isEqualTo(saved.getCanonicalTenantId()); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-new")) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "legacy-tenant-new")); + assertThat(repository.findTenantIdentityByLegacyTenantId("unknown-legacy-tenant")).isEmpty(); + + Game existingGame = repository.findByTenantId("legacy-tenant-new"); + existingGame.setDescription("updated-data"); + Game updatedGame = repository.save(existingGame); + assertThat(updatedGame.getCanonicalTenantId()).isEqualTo(saved.getCanonicalTenantId()); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-new")) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "legacy-tenant-new")); + + Game mismatchedUpdate = new Game(); + mismatchedUpdate.setId(saved.getId()); + mismatchedUpdate.setTenantId("different-legacy-tenant"); + mismatchedUpdate.setName("Must not apply"); + mismatchedUpdate.setDescription("must-not-apply"); + assertThatThrownBy(() -> repository.save(mismatchedUpdate)) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.findByTenantId("legacy-tenant-new").getName()).isEqualTo("New"); + assertThat(repository.findByTenantId("legacy-tenant-new").getDescription()) + .isEqualTo("updated-data"); + + Game mismatchedCanonicalUpdate = new Game(); + mismatchedCanonicalUpdate.setId(saved.getId()); + mismatchedCanonicalUpdate.setTenantId(saved.getTenantId()); + mismatchedCanonicalUpdate.setCanonicalTenantId(UUID.randomUUID()); + mismatchedCanonicalUpdate.setName("Must not apply"); + mismatchedCanonicalUpdate.setDescription("must-not-apply"); + assertThatThrownBy(() -> repository.save(mismatchedCanonicalUpdate)) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.findByTenantId("legacy-tenant-new").getDescription()) + .isEqualTo("updated-data"); + + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(TENANT_ID, "legacy-tenant-renamed") + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.insertInto(GAME) + .set(TENANT_ID, "legacy-tenant-duplicate-canonical") + .set(CANONICAL_TENANT_ID, retainedAlphaCanonicalId) + .set(NAME, "Duplicate") + .execute()) + .isInstanceOf(DataAccessException.class); + + dsl.insertInto(GAME) + .set(TENANT_ID, "legacy-tenant-database-issued") + .set(NAME, "Database issued") + .execute(); + GameTenantIdentity databaseIssuedIdentity = + repository + .findTenantIdentityByLegacyTenantId("legacy-tenant-database-issued") + .orElseThrow(); + assertThat(databaseIssuedIdentity.canonicalTenantId()) + .isNotNull() + .isNotEqualTo(retainedAlphaCanonicalId) + .isNotEqualTo(retainedBetaCanonicalId) + .isNotEqualTo(saved.getCanonicalTenantId()); + assertThat(databaseIssuedIdentity.provenanceKind()) + .isEqualTo(GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW); + assertThat(databaseIssuedIdentity.sourceLegacyTenantId()) + .isEqualTo("legacy-tenant-database-issued"); + assertThat(dsl.fetchCount(GAME)).isEqualTo(4); + } + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, MigrationVersion target) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(SERVICE_SCHEMA) + .defaultSchema(SERVICE_SCHEMA) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", SERVICE_SCHEMA)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private void setSearchPath(Connection connection) throws Exception { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO game_design_service"); + } + } + + private long insertLegacyGame( + DSLContext dsl, String legacyTenantId, String name, String description) { + return Objects.requireNonNull( + dsl.insertInto(GAME) + .set(TENANT_ID, legacyTenantId) + .set(NAME, name) + .set(DESCRIPTION, description) + .returning(ID) + .fetchOne(ID)) + .longValue(); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java new file mode 100644 index 0000000000..3129f3e92e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java @@ -0,0 +1,203 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class TenantAssociationMigrationIntegrationTest { + private static final String SCHEMA = "game_design_tenant_association_proof"; + private static final String ACCOUNT_DIGEST = "sha256:" + "a".repeat(64); + private static final UUID OPERATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void approvedAssociationIsImmutableExactRetryableAndConflictsFailClosed() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + try (Connection connection = dataSource.getConnection()) { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + SCHEMA); + } + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + GameRepository repository = new GameRepository(dsl); + Game game = new Game(); + game.setTenantId("legacy-game-7"); + game.setName("Approved game"); + Game saved = repository.save(game); + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Map trustedKeys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + Signed signed = signed(saved, OPERATION_ID, "legacy-game-7", ownerKey); + String manifestDigest = + TenantAssociationManifestVerifier.verify(signed, trustedKeys).manifestDigest(); + TenantAssociationMigrationService service = + new TenantAssociationMigrationService(dsl, repository); + + var first = + dsl.transactionResult(configuration -> service.apply(signed, trustedKeys, SCHEMA)); + assertThat(first).hasSize(1); + assertThat(first.getFirst().legacyAccountTenantId()).isEqualTo(41L); + assertThat(first.getFirst().canonicalTenantId()).isEqualTo(saved.getCanonicalTenantId()); + assertThat(first.getFirst().manifestDigest()).isEqualTo(manifestDigest); + assertThat(first.getFirst().schemaVersion()).isEqualTo(1); + assertThat(service.findByLegacyAccountTenantId(41L)).contains(first.getFirst()); + assertThat(service.findByLegacyAccountTenantId(42L)).isEmpty(); + + var exactRetry = + dsl.transactionResult(configuration -> service.apply(signed, trustedKeys, SCHEMA)); + assertThat(exactRetry).isEqualTo(first); + assertThat( + dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_association_operations")))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_associations")))) + .isEqualTo(1); + + Signed changedDigest = + signed( + saved, + OPERATION_ID, + "legacy-game-7", + KeyPairGenerator.getInstance("Ed25519").generateKeyPair()); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(changedDigest, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + TenantAssociationManifest changedApprovalManifest = + new TenantAssociationManifest( + 1, + OPERATION_ID, + SCHEMA, + "game-design-owner-2026", + "different-owner@example.test", + "reviewed-change-123", + signed.manifest().signedAt(), + signed.manifest().entries()); + Signed changedApproval = sign(changedApprovalManifest, ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(changedApproval, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(signed, trustedKeys, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("different namespace"); + + Signed absentSource = + signed( + saved, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "not-a-game", + ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(absentSource, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is absent"); + + Signed duplicateAccountKey = + signed( + saved, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "legacy-game-7", + ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(duplicateAccountKey, trustedKeys, SCHEMA))) + .isInstanceOf(DataAccessException.class); + assertThat( + dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_association_operations")))) + .isEqualTo(1); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE legacy_account_tenant_associations SET " + + "account_evidence_digest = ? WHERE legacy_account_tenant_id = ?", + "sha256:" + "f".repeat(64), + 41L)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Approved legacy tenant association evidence is immutable"); + } + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private Signed signed(Game saved, UUID operationId, String sourceKey, KeyPair ownerKey) + throws Exception { + TenantAssociationManifest manifest = + new TenantAssociationManifest( + 1, + operationId, + SCHEMA, + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + Instant.parse("2026-09-26T00:00:00Z"), + List.of( + new Entry( + 41L, sourceKey, saved.getCanonicalTenantId(), saved.getId(), ACCOUNT_DIGEST))); + return sign(manifest, ownerKey); + } + + private Signed sign(TenantAssociationManifest manifest, KeyPair ownerKey) throws Exception { + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(ownerKey.getPrivate()); + signature.update(TenantAssociationManifestVerifier.preimage(manifest)); + return new Signed(manifest, Base64.getEncoder().encodeToString(signature.sign())); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java new file mode 100644 index 0000000000..7547d8610d --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import org.junit.jupiter.api.Test; + +class TenantAssociationManifestVerifierTest { + private static final String ACCOUNT_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void exactApprovedManifestVerifiesAndChangedAssociationCannotReuseSignature() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TenantAssociationManifest manifest = manifest(); + Map trustedKeys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + Signed signed = signed(manifest, ownerKey); + + var verified = TenantAssociationManifestVerifier.verify(signed, trustedKeys); + assertThat(verified.manifest()).isEqualTo(manifest); + assertThat(verified.manifestDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(TenantAssociationManifestVerifier.verify(signed, trustedKeys).manifestDigest()) + .isEqualTo(verified.manifestDigest()); + + TenantAssociationManifest changed = + new TenantAssociationManifest( + manifest.schemaVersion(), + manifest.operationId(), + manifest.targetNamespace(), + manifest.signerKeyId(), + manifest.approvedBy(), + manifest.approvalReference(), + manifest.signedAt(), + List.of( + new Entry( + 42, + "legacy-game", + manifest.entries().getFirst().canonicalTenantId(), + 7, + ACCOUNT_DIGEST))); + assertThatThrownBy( + () -> + TenantAssociationManifestVerifier.verify( + new Signed(changed, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + assertThatThrownBy(() -> TenantAssociationManifestVerifier.verify(signed, Map.of())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + } + + @Test + void duplicateAndUnsortedPairsAreRejectedBeforeOwnerApproval() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TenantAssociationManifest source = manifest(); + Entry first = source.entries().getFirst(); + TenantAssociationManifest duplicate = + withEntries( + source, + List.of( + first, + new Entry(43, first.legacyGameTenantId(), UUID.randomUUID(), 8, ACCOUNT_DIGEST))); + TenantAssociationManifest unsorted = + withEntries( + source, + List.of(new Entry(43, "other-game", UUID.randomUUID(), 8, ACCOUNT_DIGEST), first)); + Map keys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + + assertThatThrownBy( + () -> TenantAssociationManifestVerifier.verify(new Signed(duplicate, ""), keys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ambiguous"); + assertThatThrownBy( + () -> TenantAssociationManifestVerifier.verify(new Signed(unsorted, ""), keys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ambiguous"); + } + + private TenantAssociationManifest manifest() { + return new TenantAssociationManifest( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "dev", + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + Instant.parse("2026-09-26T00:00:00Z"), + List.of( + new Entry( + 41, + "legacy-game", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 7, + ACCOUNT_DIGEST))); + } + + private TenantAssociationManifest withEntries( + TenantAssociationManifest source, List entries) { + return new TenantAssociationManifest( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + entries); + } + + private Signed signed(TenantAssociationManifest manifest, KeyPair keyPair) throws Exception { + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(keyPair.getPrivate()); + signature.update(TenantAssociationManifestVerifier.preimage(manifest)); + return new Signed(manifest, Base64.getEncoder().encodeToString(signature.sign())); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java new file mode 100644 index 0000000000..f363a7aa74 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +class GameDesignServiceApplicationTest { + private static final AtomicInteger MIGRATION_SIDE_EFFECTS = new AtomicInteger(); + + @BeforeEach + void resetMigrationSideEffect() { + MIGRATION_SIDE_EFFECTS.set(0); + } + + @Test + void selectsOneShotModesIndependentlyAndRejectsBothTogether() { + assertThat(GameDesignServiceApplication.selectMigrationMode("true", null)) + .isEqualTo(GameDesignServiceApplication.MigrationMode.ENTITY_BASELINE); + assertThat(GameDesignServiceApplication.selectMigrationMode(null, "true")) + .isEqualTo(GameDesignServiceApplication.MigrationMode.TENANT_ASSOCIATION); + assertThat(GameDesignServiceApplication.selectMigrationMode(null, null)) + .isEqualTo(GameDesignServiceApplication.MigrationMode.NORMAL); + + assertThatThrownBy(() -> GameDesignServiceApplication.selectMigrationMode("true", "true")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be enabled together"); + } + + @Test + void missingFlywaySettingStopsBeforeBeanMigrationSideEffect() { + assertThatThrownBy(() -> startOneShotApplication()) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(0); + } + + @Test + void explicitFalseAllowsApplicationInitialization() { + try (ConfigurableApplicationContext context = + startOneShotApplication("--spring.flyway.enabled=false")) { + assertThat(context.isActive()).isTrue(); + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(1); + } + } + + @Test + void trueOrInvalidFlywaySettingStopsBeforeBeanMigrationSideEffect() { + for (String setting : new String[] {"true", "invalid"}) { + assertThatThrownBy(() -> startOneShotApplication("--spring.flyway.enabled=" + setting)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(0); + } + } + + private static ConfigurableApplicationContext startOneShotApplication(String... args) { + SpringApplication application = new SpringApplication(SideEffectConfiguration.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setLogStartupInfo(false); + application.addInitializers( + new GameDesignServiceApplication.RequireFlywayDisabledInitializer()); + String[] isolatedArgs = new String[args.length + 1]; + isolatedArgs[0] = "--spring.config.location=optional:classpath:/missing-game-design-test.yml"; + System.arraycopy(args, 0, isolatedArgs, 1, args.length); + return application.run(isolatedArgs); + } + + @Configuration(proxyBeanMethods = false) + static class SideEffectConfiguration { + @Bean + Object migrationSideEffect() { + MIGRATION_SIDE_EFFECTS.incrementAndGet(); + return new Object(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java new file mode 100644 index 0000000000..4febcae0b6 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +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.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.Environment; + +class TenantAssociationManifestJobRunnerTest { + @Test + void requiresFlywayDisabledAndExactDatabaseUserForEachMode() { + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "preflight", "firemud_game_design_tenant_preflight", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "apply", "firemud_game_design_tenant_apply", false)) + .doesNotThrowAnyException(); + + for (String[] wrongModeAndUser : + new String[][] { + {"preflight", "firemud_game_design_tenant_apply"}, + {"apply", "firemud_game_design_tenant_preflight"}, + {"preflight", "firemud"}, + {"apply", "firemud_game_design_service"}, + {"preflight", null}, + {"apply", ""}, + {"preflight", " "} + }) { + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + wrongModeAndUser[0], wrongModeAndUser[1], false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB credential does not match the mode"); + } + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "unsupported", "firemud_game_design_tenant_preflight", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unsupported tenant migration Job mode"); + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "preflight", "firemud_game_design_tenant_preflight", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration requires Flyway to be disabled"); + } + + @Test + void readsAndClosesTheActualJdbcConnectionForDatabaseIdentity() throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn("firemud_game_design_tenant_preflight"); + + assertThat(runner(dataSource).connectedDatabaseUsername()) + .isEqualTo("firemud_game_design_tenant_preflight"); + verify(connection).close(); + } + + @Test + void rejectsMissingOrUnverifiableJdbcIdentityWithoutLeakingDriverDetails() throws Exception { + for (String username : new String[] {null, "", " "}) { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn(username); + + assertThatThrownBy(() -> runner(dataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection did not identify its user"); + verify(connection).close(); + } + + DataSource unavailableDataSource = mock(DataSource.class); + when(unavailableDataSource.getConnection()) + .thenThrow(new SQLException("sensitive driver credential diagnostic")); + assertThatThrownBy(() -> runner(unavailableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive driver credential diagnostic"); + + DataSource missingMetadataDataSource = mock(DataSource.class); + Connection missingMetadataConnection = mock(Connection.class); + when(missingMetadataDataSource.getConnection()).thenReturn(missingMetadataConnection); + when(missingMetadataConnection.getMetaData()).thenReturn(null); + assertThatThrownBy(() -> runner(missingMetadataDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection is unverifiable"); + verify(missingMetadataConnection).close(); + + DataSource unverifiableDataSource = mock(DataSource.class); + Connection unverifiableConnection = mock(Connection.class); + when(unverifiableDataSource.getConnection()).thenReturn(unverifiableConnection); + when(unverifiableConnection.getMetaData()) + .thenThrow(new SQLException("sensitive metadata credential diagnostic")); + assertThatThrownBy(() -> runner(unverifiableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive metadata credential diagnostic"); + verify(unverifiableConnection).close(); + } + + @Test + void acceptsOnlyExactDedicatedMigratorCertificate() { + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireJobIdentity( + "dev", peer("dev", "game-design-tenant-migrator"))) + .doesNotThrowAnyException(); + for (GrpcPeerIdentity wrong : + new GrpcPeerIdentity[] { + null, + peer("dev", "game-design-service"), + peer("pr-12", "game-design-tenant-migrator"), + peer("dev", "account-tenant-migrator") + }) { + assertThatThrownBy(() -> TenantAssociationManifestJobRunner.requireJobIdentity("dev", wrong)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong identity"); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static TenantAssociationManifestJobRunner runner(DataSource dataSource) { + return new TenantAssociationManifestJobRunner( + mock(Environment.class), + new ObjectMapper(), + mock(TenantAssociationMigrationService.class), + dataSource); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java new file mode 100644 index 0000000000..be412f3071 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; + +class GameDesignMigrationVersionTest { + private static final Pattern VERSIONED_MIGRATION = Pattern.compile("^V([^_]+)__.*\\.sql$"); + + @Test + void migrationVersionsAreUniqueAndTenantIdentityFollowsBaselineLockBeforeAssociations() + throws Exception { + List versions = allMigrationVersions(); + MigrationVersion baselineLock = + migrationVersion("V30__restricted_entity_digest_baseline_version_lock.sql"); + MigrationVersion canonicalIdentity = + migrationVersion("V30.1__canonical_game_tenant_identity.sql"); + MigrationVersion associations = + migrationVersion("V31__approved_legacy_account_tenant_associations.sql"); + + assertThat(versions).doesNotHaveDuplicates(); + assertThat(versions).contains(baselineLock, canonicalIdentity, associations); + assertThat(baselineLock).isEqualTo(MigrationVersion.fromVersion("30")); + assertThat(baselineLock).isLessThan(canonicalIdentity); + assertThat(canonicalIdentity).isLessThan(associations); + + // Flyway considers both former V30 filenames the same version, so they cannot coexist. + assertThat(migrationVersion("V30__canonical_game_tenant_identity.sql")).isEqualTo(baselineLock); + } + + private static List allMigrationVersions() throws Exception { + Path migrationDirectory = migrationDirectory(); + try (Stream files = Files.list(migrationDirectory)) { + return files + .map(path -> Objects.requireNonNull(path.getFileName()).toString()) + .filter(name -> VERSIONED_MIGRATION.matcher(name).matches()) + .map(GameDesignMigrationVersionTest::migrationVersion) + .toList(); + } + } + + private static MigrationVersion migrationVersion(String filename) { + Matcher matcher = VERSIONED_MIGRATION.matcher(filename); + if (!matcher.matches()) { + throw new IllegalArgumentException("Not a versioned Flyway migration: " + filename); + } + return MigrationVersion.fromVersion(matcher.group(1)); + } + + private static Path migrationDirectory() throws URISyntaxException { + return Path.of( + Objects.requireNonNull( + GameDesignMigrationVersionTest.class + .getClassLoader() + .getResource("db/migration/V30.1__canonical_game_tenant_identity.sql"), + "Missing canonical Game Design tenant-identity migration resource") + .toURI()) + .getParent(); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..02b8b8e9a9 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -0,0 +1,287 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Base64; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import org.jooq.exception.TooManyRowsException; +import org.junit.jupiter.api.Test; + +class TenantIdentityGrpcServiceTest { + private static final String ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String ACCOUNT_MIGRATOR_PEER = + "spiffe://firemud/ns/test/sa/account-tenant-migrator"; + private static final String WRONG_NAMESPACE_MIGRATOR_PEER = + "spiffe://firemud/ns/other/sa/account-tenant-migrator"; + private static final String WRONG_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); + + private final GameRepository repository = mock(GameRepository.class); + private final TenantAssociationMigrationService associationService = + mock(TenantAssociationMigrationService.class); + private final TenantIdentityGrpcService service = + new TenantIdentityGrpcService(repository, associationService, "test"); + + @Test + void approvedAccountAssociationReadBindsExactOwnerAndManifestEvidence() { + when(associationService.findByLegacyAccountTenantId(41L)) + .thenReturn(Optional.of(approvedAssociation())); + + AssociationObserver observer = associationCall(41L, ACCOUNT_MIGRATOR_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(41L, observer.value.getLegacyAccountTenantId()); + assertEquals("legacy-game-7", observer.value.getSourceLegacyGameTenantId()); + assertEquals(CANONICAL_TENANT_ID.toString(), observer.value.getCanonicalTenantId()); + assertEquals("sha256:" + "a".repeat(64), observer.value.getAccountEvidenceDigest()); + assertEquals("sha256:" + "b".repeat(64), observer.value.getManifestDigest()); + assertEquals( + Base64.getEncoder().encodeToString(new byte[64]), observer.value.getManifestSignature()); + assertEquals("reviewed-change-123", observer.value.getApprovalReference()); + assertEquals(1, observer.value.getManifestSchemaVersion()); + verify(associationService).findByLegacyAccountTenantId(41L); + } + + @Test + void associationReadRejectsMissingPeerAndInvalidNumericKeyBeforeOwnerRead() { + assertEquals(Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, null))); + assertEquals( + Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, WRONG_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, ACCOUNT_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, + associationStatus(associationCall(41L, WRONG_NAMESPACE_MIGRATOR_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + associationStatus(associationCall(0L, ACCOUNT_MIGRATOR_PEER))); + verifyNoInteractions(associationService); + } + + @Test + void associationReadFailsClosedForAbsentOrCorruptOwnerEvidence() { + when(associationService.findByLegacyAccountTenantId(41L)).thenReturn(Optional.empty()); + when(associationService.findByLegacyAccountTenantId(42L)) + .thenThrow(new IllegalStateException("corrupt operation")); + assertEquals( + Status.Code.NOT_FOUND, associationStatus(associationCall(41L, ACCOUNT_MIGRATOR_PEER))); + assertEquals( + Status.Code.FAILED_PRECONDITION, + associationStatus(associationCall(42L, ACCOUNT_MIGRATOR_PEER))); + } + + @Test + void exactAccountPeerReadsOwnerSourceAndProvenance() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenReturn( + Optional.of( + new GameTenantIdentity( + CANONICAL_TENANT_ID, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 7L, + "legacy-game-7"))); + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(CANONICAL_TENANT_ID.toString(), observer.value.getCanonicalTenantId()); + assertEquals("legacy-game-7", observer.value.getSourceLegacyGameTenantId()); + assertEquals(7L, observer.value.getSourceGameRowId()); + assertEquals("RETAINED_GAME_V30", observer.value.getProvenanceKind()); + verify(repository).findTenantIdentityByLegacyTenantId("legacy-game-7"); + } + + @Test + void wrongOrMissingPeerNeverReadsOwnerRows() { + assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", WRONG_PEER))); + assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", null))); + assertEquals( + Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", ACCOUNT_MIGRATOR_PEER))); + verifyNoInteractions(repository); + } + + @Test + void blankOrOverlongSourceKeyNeverReadsOwnerRows() { + assertEquals(Status.Code.INVALID_ARGUMENT, status(call("", ACCOUNT_PEER))); + assertEquals(Status.Code.INVALID_ARGUMENT, status(call("x".repeat(37), ACCOUNT_PEER))); + verifyNoInteractions(repository); + } + + @Test + void unknownOrMismatchedSourceFailsClosed() { + when(repository.findTenantIdentityByLegacyTenantId("unknown")).thenReturn(Optional.empty()); + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenReturn( + Optional.of( + new GameTenantIdentity( + CANONICAL_TENANT_ID, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 7L, + "different-source"))); + + TestObserver absent = call("unknown", ACCOUNT_PEER); + TestObserver mismatched = call("legacy-game-7", ACCOUNT_PEER); + assertEquals(Status.Code.NOT_FOUND, status(absent)); + assertEquals(Status.Code.FAILED_PRECONDITION, status(mismatched)); + assertNull(absent.value); + assertNull(mismatched.value); + assertFalse(absent.completed); + assertFalse(mismatched.completed); + } + + @Test + void invalidStoredProvenanceFailsClosed() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenThrow(new IllegalStateException("corrupt source binding")); + + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, status(observer)); + assertNull(observer.value); + } + + @Test + void duplicateRetainedLegacyTenantKeyFailsAsPrecondition() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenThrow(new TooManyRowsException("duplicate retained tenant key")); + + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, status(observer)); + assertNull(observer.value); + assertFalse(observer.completed); + } + + private TestObserver call(String sourceKey, String peerUri) { + TestObserver observer = new TestObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveLegacyGameTenantIdentity( + ResolveLegacyGameTenantIdentityRequest.newBuilder() + .setLegacyGameTenantId(sourceKey) + .build(), + observer)); + return observer; + } + + private AssociationObserver associationCall(long accountTenantId, String peerUri) { + AssociationObserver observer = new AssociationObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest.newBuilder() + .setLegacyAccountTenantId(accountTenantId) + .build(), + observer)); + return observer; + } + + private ApprovedAssociation approvedAssociation() { + return new ApprovedAssociation( + 41L, + "legacy-game-7", + CANONICAL_TENANT_ID, + 7L, + "sha256:" + "a".repeat(64), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "sha256:" + "b".repeat(64), + Base64.getEncoder().encodeToString(new byte[64]), + "test", + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + "2026-09-26T00:00:00Z", + 1, + 1); + } + + private static Status.Code associationStatus(AssociationObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + + private static Status.Code status(TestObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + + private static final class TestObserver + implements StreamObserver { + private ResolveLegacyGameTenantIdentityResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveLegacyGameTenantIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class AssociationObserver + implements StreamObserver { + private ResolveLegacyAccountTenantAssociationResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveLegacyAccountTenantAssociationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index 68245255cb..d689073ada 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -24,9 +24,19 @@ public final class GameplayStageCommandConstants { public static final String JOIN_REQUIRED_CODE = "JOIN_REQUIRED"; public static final String JOIN_REQUIRED_MESSAGE = "Membership is required before PLAY. Run REALMS first, then JOIN ."; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_CODE = "NON_PUBLIC_ENROLLMENT_REQUIRED"; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE = + "Existing game membership is required for this non-public realm."; + public static final String REALM_ACCESS_DENIED_CODE = "REALM_ACCESS_DENIED"; + public static final String REALM_ACCESS_DENIED_MESSAGE = + "This non-public realm is not available to your account."; public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; public static final String TENANT_BILLING_BLOCKED_MESSAGE = "That world is temporarily unavailable for gameplay."; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE = + "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE = + "Public entry to that world is currently unavailable."; public static final String AUTH_UNAVAILABLE_CODE = AuthenticationErrorCodes.UNAVAILABLE; public static final String AUTH_UNAVAILABLE_MESSAGE = "Gameplay authority is temporarily unavailable. Retry PLAY shortly."; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 2f8dab4eac..1df57eea79 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -831,7 +831,7 @@ private Optional validateRuntimeAdmission( && context.gameInstanceId() == selectedRealm.gameInstanceId() && context.characterId() > 0L ? context.characterId() - : requestedCharacterId > 0L ? requestedCharacterId : 0L; + : 0L; GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); @@ -911,11 +911,11 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { + if (!response.getGameplayAdmissionAllowed()) { boolean membershipRequiresExplicitJoin = !response.getMembershipExists() || "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); - if (isPublicProductionRealm(selectedRealm) && membershipRequiresExplicitJoin) { + if (membershipRequiresExplicitJoin && isPublicProductionRealm(selectedRealm)) { GetTenantEntitlementsForRuntimeResponse entitlementResponse = accountClient.getTenantEntitlementsForRuntime( Long.toString(selectedRealm.tenantId()), requestId); @@ -956,6 +956,11 @@ private Optional validateMembershipResponse( Long.toString(requestedCharacterId), null)); } + if (membershipRequiresExplicitJoin) { + return Optional.of( + nonPublicEnrollmentRequiredFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -976,7 +981,7 @@ private Optional validateMembershipResponse( } if (grantError.isPresent() || !grantResponse.getGranted()) { return Optional.of( - worldAccessDeniedFailure( + realmAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } if (!isValidGrant(grantResponse, context, selectedWorld, selectedRealm)) { @@ -1016,12 +1021,34 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( null); } - private boolean isDefinitivePrivateWorldDenial(PlayCommandHandlingResult result) { - return GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE.equals( - result.commandResult().errorCode()); + private PlayCommandHandlingResult nonPublicEnrollmentRequiredFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedRealm.tenantId(), + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "non_public_enrollment_required"); + return failure( + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE, + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE, + "error.play.non-public-enrollment-required", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); } - private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( + private PlayCommandHandlingResult realmAccessDeniedFailure( SessionContext context, String tenantTag, GameplayWorldCatalog.WorldView selectedWorld, @@ -1036,11 +1063,11 @@ private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( selectedRealm.gameInstanceId(), requestedCharacterId, tenantTag, - "public_admission_denied"); + "realm_access_denied"); return failure( - PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, - PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE, - "error.play.public-production-admission-denied", + GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.REALM_ACCESS_DENIED_MESSAGE, + "error.play.realm-access-denied", Map.of(), tenantTag, Long.toString(selectedRealm.gameInstanceId()), @@ -1048,6 +1075,13 @@ private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( null); } + private boolean isDefinitivePrivateWorldDenial(PlayCommandHandlingResult result) { + String code = result.commandResult().errorCode(); + return GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE.equals(code) + || GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE.equals(code) + || GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE.equals(code); + } + private Optional validateEntitlementsResponse( GetTenantEntitlementsForRuntimeResponse response, SessionContext context, @@ -1087,6 +1121,33 @@ private Optional validateEntitlementsResponse( return Optional.empty(); } + private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedRealm.tenantId(), + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "public_admission_denied"); + return failure( + PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, + PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE, + "error.play.public-production-admission-denied", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); + } + private PlayCommandHandlingResult tenantBillingBlockedFailure( SessionContext context, String tenantTag, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 6298193be8..c36421d3e8 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -22,6 +22,8 @@ error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. error.play.join-required=Membership is required before PLAY. Run REALMS first, then JOIN . +error.play.non-public-enrollment-required=Existing game membership is required for this non-public realm. +error.play.realm-access-denied=This non-public realm is not available to your account. error.play.public-production-admission-denied=Public joining is not available for this world. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.admission-pointer-unavailable=Gameplay admission pointer is temporarily unavailable. Retry PLAY shortly. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 7e412b6eaa..85873530a2 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -22,6 +22,8 @@ error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. error.play.join-required=Une adhésion est requise avant PLAY. Consultez d’abord REALMS , puis utilisez JOIN . +error.play.non-public-enrollment-required=Une adhésion existante est requise pour ce royaume non public. +error.play.realm-access-denied=Ce royaume non public n’est pas accessible à votre compte. error.play.public-production-admission-denied=L’adhésion publique n’est pas disponible pour ce monde. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.admission-pointer-unavailable=Le pointeur d’admission au jeu est temporairement indisponible. Réessayez PLAY sous peu. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index c0407afdef..0321efff26 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -8,6 +8,7 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -130,8 +131,8 @@ void setUp() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) .setMembershipLifecycleState("ACTIVE") + .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(evaluatedAtNow()) @@ -141,6 +142,7 @@ void setUp() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") .setGameplayAvailable(true) + .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) .setEvaluatedAt(evaluatedAtNow()) @@ -1729,6 +1731,96 @@ void playRejectsUnavailableCharacterRosterBeforeBinding() { verifyNoGameplayBindingSideEffects(); } + @Test + void playResumeRejectsChangedRosterIdentityWithoutBinding() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-7", + "jwt-token", + null, + 0L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void playRejectsEntityRosterErrorWithoutBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Mockito.doReturn( + ListCharactersByAccountResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playReadsMembershipGrantAndEntitlementBeforeActorRoster() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "preview", "Emberline"), + "PLAY sandbox preview Emberline")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); + order + .verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + order + .verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + order + .verify(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + @Test void playResumeDoesNotPublishSpawnEvent() { SessionContext context = @@ -2347,7 +2439,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( @Test void playPrivateMembershipDenialUsesNonEnumeratingSelectionFailure() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -2355,21 +2447,15 @@ void playPrivateMembershipDenialUsesNonEnumeratingSelectionFailure() { GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") .setTenantId("22") - .setMembershipExists(true) + .setMembershipExists(false) + .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("INACTIVE") - .setMembershipVersion(2L) - .setMembershipAuthorityGeneration(1L) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build()); - PlayCommandHandlingResult result = - handler.handle( - "1", - new TextCommand( - TextCommandType.PLAY, - List.of("sandbox", "preview", "Emberline"), - "PLAY sandbox preview Emberline")); + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) @@ -2417,6 +2503,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { .setGameplayAdmissionAllowed(false) .setMembershipLifecycleState("MISSING") .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build()); @@ -2459,11 +2546,14 @@ void playDeniedDoesNotClearCrossTenantSameSlugBinding() { .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertThat(result.commandResult().errorCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); verifyNoGameplayBindingSideEffects(); @@ -2548,6 +2638,57 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + + @Test + void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setMembershipLifecycleState("INACTIVE") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(3L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.selection-required"); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.characterId() == 0L + && saved.gameInstanceId() == 0L + && saved.roomInstanceId() == null)); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "non_public_enrollment_required"); } @Test @@ -2591,6 +2732,41 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "realm_access_denied"); + Mockito.verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + } + + @Test + void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), @@ -2613,6 +2789,8 @@ void privateOnlyWorldPlayDenialMatchesUnknownAndGrantedAccessStillWorks() { .setMembershipExists(false) .setGameplayAdmissionAllowed(false) .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build(), GetTenantMembershipForRuntimeResponse.newBuilder() @@ -2699,6 +2877,8 @@ void playHiddenRealmInPublicWorldMasksMembershipDenialLikeUnknownSelection() { .setMembershipExists(false) .setGameplayAdmissionAllowed(false) .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build()); @@ -2847,7 +3027,8 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "realm_access_denied"); } @ParameterizedTest @@ -2875,7 +3056,8 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding(String errorCode) { assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "realm_access_denied"); } @Test @@ -2974,6 +3156,65 @@ void playPublicMissingMembershipReturnsJoinRequiredBeforeCharacterRosterLookup() verifyNoGameplayBindingSideEffects(); } + @ParameterizedTest + @ValueSource(strings = {"", "ACTIVE", "UNKNOWN"}) + void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleState) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState(lifecycleState) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + + @ParameterizedTest + @ValueSource(strings = {"MISSING", "INACTIVE"}) + void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleState) { + boolean membershipExists = "INACTIVE".equals(lifecycleState); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(membershipExists) + .setMembershipLifecycleState(lifecycleState) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(membershipExists ? 3L : 0L) + .setMembershipAuthorityGeneration(membershipExists ? 1L : 0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + @Test void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { SessionContext context = @@ -2985,9 +3226,11 @@ void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") .setTenantId("22") - .setMembershipExists(false) + .setMembershipExists(true) + .setMembershipLifecycleState("INACTIVE") .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("MISSING") + .setMembershipVersion(4L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(evaluatedAtNow()) .build()); @@ -3179,6 +3422,200 @@ void playAuthorityFreshnessUsesInjectedClockAtExactInclusiveBoundaries() { } } + @ParameterizedTest + @ValueSource(strings = {"ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE"}) + void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(errorCode).build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo( + "ENTITLEMENT_UNAVAILABLE".equals(errorCode) + ? GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE + : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playBillingDenialMasksMissingPublicMembership() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(false) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.public-production-admission-denied"); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(sessionContextService).save(Mockito.any(SessionContext.class)); + } + + @Test + void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEntityCalls() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = @@ -3191,9 +3628,9 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("not-a-timestamp") .build()); @@ -3222,6 +3659,7 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { "wrong-tenant", "unknown-lifecycle", "inactive-admitting", + "missing-version", "missing-generation" }) void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { @@ -3244,6 +3682,7 @@ void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { case "wrong-tenant" -> response.setTenantId("23"); case "unknown-lifecycle" -> response.setMembershipLifecycleState("UNKNOWN"); case "inactive-admitting" -> response.setMembershipLifecycleState("INACTIVE"); + case "missing-version" -> response.setMembershipVersion(0L); case "missing-generation" -> response.setMembershipAuthorityGeneration(0L); default -> throw new IllegalArgumentException(invalidEvidence); } @@ -3335,6 +3774,74 @@ void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt(Instant.now().toString()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + } + + @ParameterizedTest + @ValueSource(strings = {"target", "version", "stale", "future", "malformed"}) + void unsafeEntitlementSnapshotFailsClosed(String defect) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + String tenantId = "target".equals(defect) ? "23" : "22"; + long entitlementVersion = "version".equals(defect) ? 0L : 1L; + String evaluatedAt = + switch (defect) { + case "stale" -> Instant.now().minus(16L, ChronoUnit.SECONDS).toString(); + case "future" -> Instant.now().plus(1L, ChronoUnit.SECONDS).toString(); + case "malformed" -> "not-a-timestamp"; + default -> Instant.now().toString(); + }; + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(tenantId) + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(entitlementVersion) + .setTenantBillingSequence(0L) + .setEvaluatedAt(evaluatedAt) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + // Membership precedes entitlement validation; neither read permits actor admission on failure. + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + } + @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = @@ -4220,24 +4727,6 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { assertIdentityUnavailableWithoutMutation(result); } - @Test - void playRejectsEntityRosterErrorWithoutBinding() { - SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - Mockito.doReturn( - ListCharactersByAccountResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) - .build()) - .when(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertIdentityUnavailableWithoutMutation(result); - } - @Test void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index d543fe3487..03ed54877a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -177,9 +177,9 @@ void setUp() { .setAccountId("77") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(Instant.now().toString()) .build()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 3e6b8b8582..b14d162140 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -184,9 +184,9 @@ void setUp() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(Instant.now().toString()) .build()); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 9fbc959640..f19e0de765 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -170,7 +170,7 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { ensureTestServicesStarted(); try (GameplayTelnetDriver firstClient = openAdmittedTelnetClient()) {} - accountStub().setGameplayAdmissionAllowed(false); + accountStub().setMembershipInactive(); try (GameplayTelnetScenarios.LoginThenPlayScenario scenario = GameplayTelnetScenarios.loginThenAttemptPlay( @@ -489,7 +489,7 @@ void telnetReconnectAfterRevocationFailsClosed() throws Exception { .anyMatch(response -> response.contains(LookTestFixtures.DESTINATION_ROOM_ID)); } - accountStub().setGameplayAdmissionAllowed(false); + accountStub().setMembershipInactive(); try (GameplayTelnetScenarios.LoginThenPlayScenario scenario = GameplayTelnetScenarios.loginThenAttemptPlay(