diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7031ff3417..9d69e3b49f 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: @@ -374,6 +373,7 @@ jobs: bash ./dev-tools/tests/trust-bootstrap-live-proof-contract.sh bash ./dev-tools/tests/trust-bootstrap-provision-contract.sh bash ./dev-tools/tests/hosted-identity-controller-manifest-contract.sh + bash ./dev-tools/tests/account-workload-namespace-contract.sh bash ./dev-tools/tests/hosted-identity-controller-workflow-contract.sh bash ./dev-tools/tests/worktree-topology-contract.sh bash ./dev-tools/tests/dev-tools-readme-contract.sh @@ -1011,7 +1011,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/build.gradle.kts b/build.gradle.kts index f1e2d36663..b65fe5e93f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -511,7 +511,7 @@ tasks.register("buildDockerImagesSmoke") { } tasks.register("generateDevCerts") { - commandLine("bash", "dev-tools/certs/generate-dev-certs.sh") + commandLine("bash", "dev-tools/certs/ensure-dev-certs.sh") } tasks.register("ensureLocalComposeEnv") { diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index 094a525895..56310ad2aa 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The Account `/auth/bootstrap/join` controller and operation exist locally, but its public Gateway route remains denied, so browser `Join & Play` is still unavailable. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance still uses the partial membership response and does not enforce the emitted lifecycle/generation fields; its independent version/generation issuance baseline reread and fresh replay validation remain unproved. In contrast, Game Session text `PLAY` locally validates the fresh response identity, lifecycle, membership version, authority generation, and evaluation time. Missing or `INACTIVE` public-production membership gets `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` checks; other non-admitting states remain denials. Game Session direct-text `REALMS`/`JOIN` dispatch now invokes the Account writer using its retained scope and request state. These local checks do not establish positive live Account runtime reads, which remain fail closed pending typed caller/target authority, or prove the full direct-text/Telnet flow. The exact connect-token issuance baseline and ADR 0030 admission-lease/replay requirements remain unimplemented or unproved. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. Current route status and proof gaps are recorded in [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../../project-management/implementation-tracking/player-access-and-session.md#capability-status). +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. Public non-browser issuance and dedicated header carriage remain target-only and unavailable. The current browser/mobile response still exposes internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target metadata-only response is implemented; protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch exist, but the public Gateway join route remains denied. Game Session validates supplied membership lifecycle, authority generation, version, and evaluation time in its local `PLAY` response-classification path. That local path returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful composed public `PLAY` is established; the current live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership classification branches with the same fresh entitlement and policy gates, but its independent membership-version and authority-generation issuance rereads remain unproved and live admission is unavailable. The connect-token replay-cache revalidation gaps also remain; the exact ADR 0030 admission-lease commit, PostgreSQL execution, and pending-operation recovery/reconciliation remain incomplete. First-party browser and text target sequences remain distinct: browser bootstrap/discovery -> conditional explicit join -> character selection/creation -> connect token -> WebSocket `LOGIN` -> `PLAY`; text credential-bearing `LOGIN` -> conditional explicit `JOIN` -> character selection/creation -> `PLAY`. Grant-backed private/playtest admission requires existing `ACTIVE` membership plus the current grant, skips `JOIN`, and never creates membership. See [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention), and the route matrix for canonical authority and proof limits. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index 64a64ef86d..a47bd619b2 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted explicit-join decision is target state. Current first-party connect-token issuance and text `PLAY` now require existing membership and do not invoke an implicit membership writer; fresh authoritative missing or `INACTIVE` public-production membership fails closed with `JOIN_REQUIRED`. The obsolete differently named writer RPC and service implementation have been removed rather than retained as compatibility behavior. Explicit `JOIN` / `Join & Play`, the membership transaction, monotonic versioning, durable audit/outbox boundary, and the exact current membership snapshot plus independent `membershipVersion` and `membershipAuthorityGeneration` reread at every connect-token issuance remain incomplete. No complete runtime implementation is claimed by this ADR. +The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. ## Decision Record @@ -24,7 +24,7 @@ The accepted explicit-join decision is target state. Current first-party connect A tenant may deliberately expose one default production realm for public discovery. Joining that game should create a durable Account-owned player membership: the relationship powers the player's game library, later discovery, return-to-game flows, creator membership views, moderation, and account/tenant data handling. -The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. Current admission callers have been corrected to require existing membership and return `JOIN_REQUIRED`, and that writer RPC/service seam has been removed without introducing a compatibility path. The remaining implementation also lacks the accepted explicit-join boundary, target transaction, versioning, and durable audit/outbox contract. +The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. That writer RPC/service seam has been removed without introducing a compatibility path. Local admission response classification uses supplied Account authority and preserves the target distinction between missing/`INACTIVE` eligible public membership, `ACTIVE` but non-admitting membership, and non-public denial; live Account runtime readers still fail before data access and no successful composed public `PLAY` is established. The accepted explicit-join boundary, policy-bound Account transaction, local durable audit/outbox seam, and bounded `PENDING`-intent readback worker now exist; PostgreSQL execution, unknown-commit-outcome reconciliation proof, downstream snapshot-generation, and end-to-end transport proof remain incomplete. ## Decision @@ -88,7 +88,7 @@ This avoids durable rows for casual visits but creates a second class of gamepla - Add explicit browser/mobile join and text `JOIN` flows before first character creation/connect/`PLAY`. - Carry the verified `connectScopeId` through `JoinPublicProductionMembership`, bind the exact `catalogRevision` and `pointerVersion` pair plus the authoritative `allowPublicJoin` result and `entitlementVersion` into the versioned request/policy digest and committed transition evidence, and prove the policy, digest, selector, catalog, and pointer are rechecked at the membership commit gate. Prove that `JOIN_REQUIRED` is emitted only after an authoritative `allowPublicJoin=true` result; `allowPublicJoin=false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and stale or last-known-good entitlement cannot authorize join or restore `INACTIVE` membership. -- Implement the canonical `JoinPublicProductionMembership` operation rather than restoring the removed writer or retaining a compatibility adapter. The obsolete operation has been removed from the current Account proto/service, client, configuration, allowlists, and focused tests; generated references must be regenerated from the canonical contract when explicit `JOIN` is implemented. In the target state, `POST /auth/connect-token` and `PLAY` must require membership and must not write it. +- Implement the canonical `JoinPublicProductionMembership` operation rather than restoring the removed writer or retaining a compatibility adapter. The obsolete operation has been removed from the current Account proto/service, client, configuration, allowlists, and focused tests; generated references must be regenerated from the canonical contract when public explicit-`JOIN` delivery becomes available. In the target state, `POST /auth/connect-token` and `PLAY` must require membership and must not write it. - Prove every `IssueConnectToken` call, including the first call after explicit join, rereads the exact current caller-bound runtime membership snapshot at its Account issuance commit gate, including `membershipLifecycleState`, independent `membershipVersion`, and opaque `membershipAuthorityGeneration`; cached or bootstrap evidence cannot substitute even when its generation appears current. - Commit membership, its `membershipAuthorityGeneration`/`membershipVersion` changes, operation outcome, and exactly one transition audit/outbox event for create or restore atomically; an `ACTIVE` retry must remain event-free, and SQL membership/operation state is authoritative for replay. - Gate every new membership commit on the immediately preceding fresh ADR 0028 entitlement evaluation. Prove that unavailable or unsafe entitlement authority returns `ENTITLEMENT_UNAVAILABLE`, billing denial or a billing grace state that blocks joining returns `TENANT_BILLING_BLOCKED`, and a nonbilling public-production policy denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`; no membership, audit, or outbox record is committed after a failed, stale, future-dated, mismatched, or otherwise invalid evaluation, including evaluation/commit races. Prove that public-production alone can return `JOIN_REQUIRED` or invoke public `JOIN`, while private/playtest/non-production admission requires active membership and its current grant/entitlement and never invokes public join. diff --git a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md index 53c53531ae..c087be5c21 100644 --- a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md +++ b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The global-account and explicit-membership model is target state and is not yet fully implemented or proved. Current registration DTOs, service call sites, fixtures, and persistence still carry legacy `tenantId`/`accounts.tenant_id` assumptions, so registration remains tenant-aware implementation drift rather than evidence that the target global-only registration contract is live. Direct convergence must make registration create only the global account and leave tenant membership to explicit `JOIN`. +The global-account and explicit-membership model has a local implementation, but is not yet fully proved or deployment-ready. Current registration now creates only global account state and a platform-scoped audit outbox record, while `JoinPublicProductionMembership` is the sole local public-production membership writer and records a policy-independent intent before binding exact policy evidence, membership, operation outcome, and tenant-scoped audit/outbox evidence. Legacy migrations and retained-data paths still carry `tenantId`/`accounts.tenant_id` assumptions, so the global-only registration contract must not be read as proof that legacy data is reconciled or safe to deploy. Exact-final-head PostgreSQL validation, pending-operation recovery/reconciliation, and direct text-to-Logging end-to-end proof remain incomplete; direct convergence still requires registration to remain global-only and tenant membership to remain explicit `JOIN`. ## Decision Record @@ -31,8 +31,8 @@ The current implementation still carries legacy `accounts.tenant_id` drift. That - One global platform account owns credentials, platform-wide username and email identity, recovery state, linked external identities, and account-security lifecycle. - Registration creates only the global account. It does not create tenant membership, roles, a profile, a character, an entitlement, or gameplay authority. - Explicit `JOIN` creates the durable account-to-tenant membership for one game according to the accepted admission contract. -- The canonical membership relation enforces exactly one row per `(account_id, tenant_id)` with a database unique constraint. Account serializes `JOIN` on that membership key. An exact retry with the same request ID and digest replays that operation's stored outcome. A concurrent request with a different request ID or digest waits for the first membership-key transition, then records its own durable no-op outcome referencing the canonical membership; it does not replay another operation's stored result, insert another row, or emit another logical membership event. -- Every `JOIN` carries a caller-stable operation ID (`requestId`) and a canonical digest whose preimage includes `operationKind=JOIN`, the authenticated account, verified caller binding, verified target, and other authority-bearing inputs. Account persists those inputs with the operation ID, digest, lifecycle status, and terminal outcome in durable storage before returning a terminal result. An exact retry with the same ID and digest returns that operation's stored outcome; reuse with a different digest is rejected as `IDEMPOTENCY_CONFLICT`; an unresolved or ambiguous operation remains pending and never becomes an implicit success. +- The canonical membership relation enforces exactly one row per `(account_id, tenant_id)` with a database unique constraint. Account serializes `JOIN` on that membership key. An exact retry with the same request ID and digest replays that operation's stored outcome only when the current-policy gate below passes; unavailable or unsafe policy does not permit replay. A concurrent request with a different request ID or digest waits for the first membership-key transition, then records its own durable no-op outcome referencing the canonical membership; it does not replay another operation's stored result, insert another row, or emit another logical membership event. +- Every `JOIN` carries a caller-stable operation ID (`requestId`) and a canonical digest whose preimage includes `operationKind=JOIN`, the authenticated account, verified caller binding, verified target, and other authority-bearing inputs. Account persists those inputs with the operation ID, digest, lifecycle status, and terminal outcome in durable storage before returning a terminal result. Before replaying a stored terminal result, Account performs the current-policy check; unavailable or unsafe current policy fails closed without overwriting or re-executing the stored result, and a later retry under the same policy may replay it. A changed policy or digest is rejected as `IDEMPOTENCY_CONFLICT`; an unresolved or ambiguous operation remains pending and never becomes an implicit success. - The membership transition and its durable audit/outbox event are committed atomically with the same persisted `JOIN` operation ID and digest. An exact retry therefore replays that one stored outcome and cannot create a second membership transition or logical event; a concurrent distinct operation records its own no-op outcome after the canonical row is visible and also emits no transition event. The operation record, membership row, transition evidence, and event must be sufficient to reconcile a lost response without re-executing the join. - Leaving is a distinct operation kind with its own stable operation ID, canonical digest, stored outcome, membership transition, and audit/outbox event. A later rejoin is a new `JOIN` operation and a distinct `INACTIVE` -> `ACTIVE` transition; it must not replay or mutate the earlier leave outcome. `JOIN` is not a general lifecycle repair and cannot restore any state other than `INACTIVE`. - Tenant roles, profiles, characters, tenant-bound purchases, subscriptions, entitlements, grants, and gameplay state are tenant-scoped relationships or records. They must carry and enforce their owning `tenantId` rather than becoming global account attributes. diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 23cd54ce1d..583256daac 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -18,6 +18,7 @@ JWT implementation drift: the current runtime loads and immediately replaces one - [TLS & Certificates](#tls--certificates) - [Authentication & JWT](#authentication--jwt) - [Service Discovery](#service-discovery) +- [Account JOIN Reconciliation](#account-join-reconciliation) - [Observability](#observability) - [Asset Storage](#asset-storage) - [Backup & Restore Variables](#backup--restore-variables) @@ -214,6 +215,19 @@ Player-facing environments (`hobby-self-hosted`, staging, production) must treat --- +## Account JOIN Reconciliation + +These Account-specific environment variables configure the current scheduled, readback-only reconciliation of uncertain `PENDING` public-production JOIN operations. The defaults below are shared by the normal and production Spring profiles. + +| Variable | Purpose and bounds | Default | +| -------- | ------------------ | ------- | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE` | Maximum due operations read back in one job pass; valid range `1..100` | `50` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS` | Positive diagnostic threshold for unresolved attempts; reaching it does not terminalize an operation | `12` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS` | Positive fixed delay between scheduled job invocations, in milliseconds | `30000` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS` | Positive initial delay, in milliseconds, before retrying an unresolved operation. The delay doubles for each persisted unresolved attempt and caps at `max(initial delay, 300000)` ms. | `30000` | + +The attempt threshold only raises diagnostics; it never converts an uncertain `PENDING` operation to a terminal state. Exact readback recovery continues with backoff while the operation remains pending. See [Account Service Configuration: JOIN Reconciliation](../microservices/account-service/configuration.md#join-reconciliation) for the Account-local mapping and consequences. + ## Observability Services are instrumented to create OpenTelemetry spans, but an environment may advertise only a capability level proved end to end under ADR 0017. The collector endpoint can be overridden with the `OTEL_ENDPOINT` environment variable (mapped to the Spring property `otel.endpoint`): @@ -298,12 +312,12 @@ See `../system-architecture-backup-recovery.md` for schedules and retention poli ## Additional Notes -Service-specific settings such as SMTP credentials for the Account Service or `GAME_TICK_DURATION_MS` for the Game Session Service are documented in each service's design README. See the "Environment Variables" sections in: +Service-specific settings remain documented in their service design documents; this catalog also indexes Account's JOIN reconciliation controls above because their diagnostic-only retry threshold needs an explicit operator note. See: -- `../microservices/account-service/README.md#environment-variables` +- [Account Service Configuration: JOIN Reconciliation](../microservices/account-service/configuration.md#join-reconciliation) - `../microservices/game-session-service/README.md#environment-variables` -This catalog covers only shared configuration keys. +This catalog primarily covers shared configuration keys and explicitly indexed service-specific controls. Operational scripts like `dev-tools/restores/restore-cluster.sh` use an optional `FIREMUD_K8S_NAMESPACE` override to target non-default namespaces during restore drills. In normal shared-environment operations, namespace selection should stay aligned with the standard overlay namespace (`firemud`). diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 084cafc2a4..f70abad77d 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -34,7 +34,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Profiles store a display name, bio, game history, and achievements. - Password reset and verification flows. - Subscription tracking with ban management. -- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` currently return `FAILED_PRECONDITION` in `PaymentGrpcService` before dispatch to `PaymentService` or any provider; the generic payment persistence/service/provider substrate remains unsupported. These RPCs are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` currently return `FAILED_PRECONDITION` in `PaymentGrpcService` before dispatch to `PaymentService` or any provider; the underlying generic payment persistence/service/provider and non-exposed purchase-workflow substrate remain unsupported, and these RPCs are not advertised product paths. See [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for current status. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). - Expose Account relationship/projection data for actor discovery and access checks; do not create or own persisted gameplay actors. - gRPC APIs cover authentication, account lifecycle, export/delete, runtime/admission, membership, realm-grant, entitlement, profile, and hosting-billing operations; generic payment scaffolds do not widen that capability boundary. The canonical API inventory is [API Contracts](./api-contracts.md). diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 1654a9d4fa..a728d4e9cc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,21 +54,23 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded Account worker may terminalize only after the exact operation, scope, membership, immutable audit envelope, and version-1 COMMITTED receiver receipt/projection identity are positively proved from the same scoped outbox row. Missing, legacy-unversioned, unsupported-version, or minimized delivery evidence leaves the intent pending with retry diagnostics. Each persisted unresolved attempt doubles its retry delay from the configured initial delay up to `max(initial delay, 300000 ms)`; the diagnostic attempt threshold does not stop readback or authorize JOIN replay or terminalization. Expiry does not authorize a terminal outcome. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. + `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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 only while the retained scope remains valid; current scope validation returns `CONNECT_SCOPE_INVALID` on expiry rather than implementing readback-only recovery of uncertain PENDING outcomes, which remains #2848 work, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Recovery after an unknown database commit outcome remains open under ADR 0025/#2848; exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof remain unclaimed. Game Session's direct-text `REALMS`/`JOIN` dispatch now uses the retained Account-issued scope and invokes that writer locally. The Gateway guard blocks external exposure of `POST /auth/bootstrap/join` pending accepted proof. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance still does not enforce the emitted lifecycle state or generation and relies on `membershipExists`/`gameplayAdmissionAllowed`; its independent issuance baseline, fresh replay validation, and complete lease contract remain unproved. In contrast, Game Session text `PLAY` locally validates the fresh response's account/tenant identity, membership lifecycle, positive membership version and authority generation for an existing member, and evaluation time. It returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh entitlement and `allowPublicJoin` checks; other non-admitting states remain denials. These local checks do not prove positive live Account runtime reads, which remain fail closed pending typed caller/target authority. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. 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 browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. 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 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. 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 vs Target Export Lifecycle -The current `GET /accounts/{accountId}/export` route and current `ExportAccount` implementation are synchronous Account/profile-local exports. They return only the Account-owned local result, have no cross-service required-owner fan-in, and do not satisfy ADR 0050; neither the route nor the current implementation may be described as a complete portable-data export. +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. The target lifecycle is the asynchronous `POST /accounts/{accountId}/exports` operation followed by its stable status and content resources. Target `ExportAccount` gRPC behavior is the protocol equivalent of that lifecycle: Account durably creates or replays one export job, gathers every required owning-service contribution, exposes a versioned manifest with explicit owner outcomes, and makes content available only after the required fan-in reaches its terminal contract. Each initiation uses the already established caller `requestId`; Account computes a canonical, versioned `requestDigest` from the normalized export operation and persists one `export_operation` before fan-in, assigning its stable `exportId`. A retry with the same request identity and matching digest replays that operation and `exportId`, including after a lost response; reusing the request identity with a different digest is an idempotency conflict and cannot create another export. The current local implementation is known drift from this target. @@ -90,20 +92,21 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `IssueAutomationOperatorAuthorizationReference` – target Account-owned typed issuance RPC for the exact Logging & Admin workload mTLS identity and a versioned automation policy. It is a separate automation-specific tenant-scoped authority path, not a human membership or `control-ui` path; until a published schema registry exists, its target-not-routable contract explicitly selects only the `non_moderation` branch, requires schema-declared `action_category` absence, and rejects moderation schemas before issuance. Account validates the `automation_operator` issuance kind, exact authenticated workload binding, policy identity/version, `tenant_generation`, target/scope, action-family schema pair, typed request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`, and issues no user or global-role authority. `controlPlaneRequestId` and `mutationDigest/v1` are the mutation identity and digest only for that non-moderation branch; a future moderation automation path must use dedicated moderation identities, digests, and idempotency and must treat `controlPlaneRequestId` as correlation-only. - `RedeemOperatorAuthorization` – target Account-owned redemption RPC used only by the exact owner workload named in the issued record. The owner presents the exact opaque reference plus the Account-returned `authorizationReferenceFingerprint` transported unchanged through Logging & Admin, its independently derived action family, schema pair, typed target/scope/request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`; Account authenticates the exact mTLS caller and returns the authenticated authority projection, a fresh Account recomputation of `authorizationReferenceFingerprint`, and immutable `authorityEvidenceBundle` only when every value and current authority state still match. The owner compares the forwarded fingerprint with that fresh Account value before treating redemption as successful or authorizing the mutation. Account consumes the reference atomically on successful redemption and durably records the redemption result. Before successful redemption, an exact same-tuple retry may replay that durable result; after consumption, any replayed result is evidence for the same completed redemption only and cannot authorize a new owner attempt. Owner rearm after a terminal result requires fresh Account authorization and a new opaque reference. - `RecoverOperatorAuthorizationReference` – target Account-owned read-only recovery RPC for the exact authenticated Logging & Admin workload. The request repeats the complete immutable typed issuance tuple, actor or automation-policy evidence, and current reservation owner/claim fence; Account returns only the original issuance response or original terminal outcome from its durable record. Durable `NOT_FOUND` is read-only lookup evidence that no matching record was found, never proof for `NOT_EXECUTED_BEFORE_AUTHORIZATION`; that terminal state requires durable phase evidence that Account authorization cannot complete and durable dispatch evidence that no owner-forward call occurred and no owner-forward call can still occur. Until both proofs exist, the operation remains `AUTHORIZATION_PENDING`, non-replayable and non-rearmable. It never issues, extends, rotates, redeems, or semantically recreates a reference. -- `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. -- `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. +- `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The current direct gRPC read requires the verified Social Groups peer and a non-internal caller account subject equal to the requested account before its existing membership check. +- `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The direct gRPC mutation has the same verified Social Groups peer and exact caller-account guard. -- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. -- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current implementation behind this method remains the local legacy export described above. +- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. The current direct gRPC read requires the verified Social Groups peer. +- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The legacy account-ID gRPC method currently fails closed before reading data because it cannot establish that caller/operation binding; the local export substrate is not the canonical route. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. -- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only; the current account-targeted gRPC request is implementation drift. -- `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. +- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only; the current account-targeted gRPC method fails closed before reading data and is implementation drift. +- `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. The current service must fail closed until the pending-deletion workflow, complete provider/transfer clearance, and retained financial evidence are available; its legacy synchronous hard-delete is not an accepted implementation. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. - `RequestPasswordReset` – initiate a password reset email. Public initiation returns the same neutral success for known and unknown normalized email addresses; an unknown address creates no token and schedules no delivery. -- `CompletePasswordReset` – update the password using a token. -- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. +- `CompletePasswordReset` – update the password using a token. The current service conditionally consumes the still-valid token in the same transaction as the account mutation so a concurrent reuse cannot apply a second update; PostgreSQL execution remains a proof gate. +- The `RequestPasswordReset` and `CompletePasswordReset` gRPC handlers currently fail with `FAILED_PRECONDITION` before calling AccountService because no authorized internal caller is configured. The supported public REST reset routes remain available; this gRPC containment does not change their Account-owned token-consumption behavior. +- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the account-ID gRPC `LinkExternalAccount` also fails closed before mutation. The persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. @@ -113,18 +116,18 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`; Game Session text `PLAY` locally validates the response identity, lifecycle, version, generation, and evaluation time before admission. Account's live runtime reader still fails closed before returning positive data until the required typed caller/target authority is implemented, so this local validation is not end-to-end admission proof. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, including the issuance baseline and reread, and consumers must fail closed on exact lifecycle/generation checks. -- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Account producer can emit lifecycle state and `membershipAuthorityGeneration` alongside independent `membershipVersion`, but the current bare request cannot establish the required typed Game Session player context, so the direct gRPC handler fails closed before that producer read. Game Session text `PLAY` locally validates response identity, lifecycle, version, authority generation, and evaluation time; the live Account handler still fails closed, so supplied-response validation is not positive end-to-end admission proof. One fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context. The current tenant-only proto/request lacks both complete alternatives, so the direct gRPC handler fails closed before the underlying producer read; Game Session's older consumer request must be converged before admission can rely on this route. Logging & Admin and `control-ui` callers use the redacted route variants. -- `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. +- `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. The currently exposed `GetRealmAccessGrantForRuntime` request cannot carry that lifecycle-bound typed caller/target evidence and its direct gRPC handler fails closed before reading grant data. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. - `GetTenantEntitlementsCrossTenantSupportSafe` – cross-tenant support-safe entitlement view with redacted, high-level fields only. -- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; the internal gRPC method retains its account-ID request. Unknown public requests create no token and schedule no delivery. -- `VerifyEmail` – confirm an email verification token. -- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; the retained underlying service method remains unsupported substrate and is not a v1 hosting-billing operation or entitlement path. The [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting, not a bearer-token variant; that allowlist is not currently implemented. -- `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. -- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported and cannot create a FireMUD entitlement. Its [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting; that allowlist is not currently implemented. -- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. The RPC returns `success=false` with a `FAILED_PRECONDITION` `ErrorDetail` before service or provider dispatch; its retained underlying service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. +- `RequestEmailVerification` – send an account-scoped verification email. Public REST initiation normalizes the email and returns the same neutral success for known and unknown addresses; an unknown address creates no token or delivery. The legacy account-ID gRPC method fails closed before token creation or delivery because it cannot establish caller-account binding. +- `VerifyEmail` – consume a still-valid verification token in the same transaction as the Account mutation; PostgreSQL concurrent-reuse execution remains unproved. The legacy account-ID gRPC method fails closed before token processing. +- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. The current handler returns `FAILED_PRECONDITION` before service or provider dispatch and is not a v1 hosting-billing or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe; any future internal generic method requires an exact authenticated mTLS workload/method allowlist, not bearer-token authorization. See [Stripe Integration](./stripe-integration.md). +- `CreateSubscription` – target recurring hosting operation under [Subscription Management](./subscription-management.md) and [Stripe Integration](./stripe-integration.md). The current proto lacks caller-stable request identity, resolved billing-owner evidence, and instrument selection, so the handler fails with `FAILED_PRECONDITION` before mutation rather than manufacturing an active subscription. +- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. Its RPC returns `FAILED_PRECONDITION` before service/provider dispatch; the retained provider-mutating method remains unsupported and cannot create an entitlement. Any future internal call requires the exact authenticated mTLS workload/method allowlist described in [Stripe Integration](./stripe-integration.md). +- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. Its RPC returns `success=false` with a `FAILED_PRECONDITION` `ErrorDetail` before service/provider dispatch; the retained underlying method remains unsupported. Hosting refunds use a separately typed operation and durable workflow; marketplace refunds require a separately accepted value-conservation contract. - `GetBalance` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. @@ -168,6 +171,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | +| `GET` | `/accounts/{accountId}/tenant-export` | **Current legacy route, disabled.** Returns `501 NOT_IMPLEMENTED` before tenant/global Account data reads; the account-selected shape cannot satisfy the tenant-admin export contract. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | | `GET` | `/accounts/{accountId}/exports/{exportId}` | **Target-state only.** Read durable portable-data export status, owner contribution state, and the versioned manifest using the same bounded subject/credential branch that initiated the job. | | `GET` | `/accounts/{accountId}/exports/{exportId}/content` | **Target-state only.** Download the completed export artifact using the same bounded subject/credential branch; a security-lock recovery credential authorizes only its exact account/export lifecycle and is never a pending-deletion credential. That security-lock credential is single-use for export initiation and bounded/expiring for status and content access; pending-deletion access remains the separate workflow credential. Losing a response requires retrying the same persisted operation, not minting a second export or reusing the credential for another scope. | @@ -175,7 +179,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/accounts/{accountId}/deletion/cancel` | **Target-state only.** Cancel eligible pending deletion and establish a fresh normal account generation after the dedicated recovery proof. | | `POST` | `/accounts/{accountId}/deletion/billing-settlement` | **Target-state only.** Perform only the necessary billing-settlement action allowed by the pending-deletion workflow. | | `GET` | `/tenant-admin/tenants/{tenantId}/export` | **Target-state only; not currently routable.** Tenant-wide billing-safe export of tenant-owned data for a live `tenantAdmin`; no account subject selector. | -| `DELETE` | `/accounts/{accountId}` | Delete the global account after billing-owner preconditions pass | +| `DELETE` | `/accounts/{accountId}` | **Current route, disabled.** Returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before mutation. The target pending-deletion and retained-data workflow requires full ADR 0043/`DATA-01` authority and proof before enabling deletion. | | Provider-specific callback route (future) | Not yet routable | Link one server-verified provider identity after that provider's complete contract and proof exist; the caller-asserted `/accounts/{accountId}/external` route is unsupported | | `POST` | `/auth/player-bootstrap` | Current endpoint; **target registry-backed behavior:** return a short-lived `player-bootstrap` token for gameplay bootstrap only after Account has atomically established exactly one active issued-token registry record; registry failure fails issuance before the token is exposed, and the token is not the `/auth/login` control-ui session | | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | @@ -193,8 +197,8 @@ 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 without enforcing its emitted lifecycle state or generation, 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/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session direct-text `REALMS`/`JOIN` dispatch is implemented locally against the retained Account-issued scope; the complete text flow remains unproved. Unknown-outcome recovery/reconciliation and Logging receipt receiver/readback remain open, as do first-party browser `Join & Play` and public Gateway route availability. See [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) and the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status) for current flow and proof status. | +| `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/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 | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -257,12 +261,14 @@ The canonical token refresh, replacement, generation, revocation, fencing, logou The canonical membership, entitlement response shape, freshness, and sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This API document retains only the local surfaces and transport consequences: - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. -- Current drift: both methods are listed under Account's gRPC `public-methods` in development and production configuration, bypassing shared bearer validation, and the handlers do not enforce the exact Game Session/World Management workload or typed tenant-bound caller context. The target internal-only boundary remains canonical; readiness requires removal of the bypass plus missing-token, wrong-workload, and cross-tenant negative proof. +- Current status: both methods have been removed from Account's gRPC `public-methods` in development and production configuration, and the handlers admit only the exact Game Session peer. A request from that peer receives an in-band `FAILED_PRECONDITION` (`ErrorDetail`) before Account data access because typed caller/target context is unavailable; wrong-peer requests are denied. Typed caller/target context, positive snapshot behavior, and consumer proof remain unavailable. The canonical target contract remains in [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. - Internal callers must treat missing required owner fields as contract failure and fail closed; Account's REST/OpenAPI and gRPC/proto sources remain the executable API authorities. +The local Account `POST /auth/bootstrap/join` handler does not make the public Gateway route available: that edge route remains denied and target-only, and first-party `Join & Play` is not currently reachable through it. + ## Subject-Binding Rules (Normative) - `GET /tenants/{tenantId}/profiles/{accountId}` and `PUT /tenants/{tenantId}/profiles/{accountId}` are tenant-qualified, caller-subject-bound profile routes. They require live membership and the path `accountId` must equal the authenticated account; global roles do not broaden these routes. Cross-account moderation/support views require separate minimized contracts. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index cfeb4f6035..4fcb57454a 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -28,7 +28,7 @@ The current runtime still uses the shared-HMAC compatibility profile for issuanc ## Service-Specific Variables -Additional variables configure outbound email delivery and payment behavior: +Additional variables configure outbound email delivery, payment behavior, and Account's JOIN reconciliation. The reconciliation environment-variable names, defaults, and bounds are maintained in the central [Environment Variables & Secrets Catalog: Account JOIN Reconciliation](../../infrastructure/environment-and-secrets-catalog.md#account-join-reconciliation); the local properties and runtime consequences are summarized below. | Variable | Purpose | Default | | -------- | ------- | ------- | @@ -53,6 +53,23 @@ Additional variables configure outbound email delivery and payment behavior: Changing any of the three JWT lifetime variables—`FIREMUD_AUTH_JWT_EXPIRATION_MS`, `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS`, or `FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS`—changes the `exp` claim only for newly issued JWTs; already issued JWTs retain their existing `exp`. `FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS` is only the current default TTL for legacy session records whose writer omits an explicit lifetime; it does not change JWT `exp`, issued-token-registry retention, or gameplay continuity. The current control-ui, player-bootstrap, and connect-token writers pass their corresponding JWT lifetimes directly, which is implementation drift if target convergence requires one per-token retention rule. `FIREMUD_ACCOUNT_TOKENS_CONNECT_SCOPE_EXPIRATION_MS` separately controls the discovery selector's `connectScopeExpiresAt`; it is not a JWT lifetime, session-record TTL, registry-retention setting, or gameplay-continuity cap. The cleanup margin is applied when new registry records are admitted; it does not change the expiration of existing JWTs or the immutable anchor of an existing gameplay binding. A larger cleanup margin therefore cannot raise the independent gameplay-continuity cap. The separate Account overrides are current runtime controls with target ceilings and startup/preflight proof obligations recorded above; they do not establish target convergence by themselves. +## JOIN Reconciliation + +`AccountJoinReconciliationJob` invokes the bounded, readback-only reconciler on the configured fixed delay. The environment variables in the central catalog map to these Account-local Spring properties: + +| Spring property | Account-local effect | +| --------------- | -------------------- | +| `firemud.account.join-reconciliation.batch-size` | Caps each due-operation readback page. | +| `firemud.account.join-reconciliation.max-attempts` | Raises a diagnostic threshold for unresolved attempts only. | +| `firemud.account.join-reconciliation.interval-ms` | Sets the fixed delay between job invocations. | +| `firemud.account.join-reconciliation.backoff-ms` | Sets the initial retry delay; persisted attempts scale it according to the central catalog's capped exponential policy. | + +Reaching `max-attempts` never terminalizes an uncertain `PENDING` operation: exact readback continues with capped exponential backoff, and attempt count alone is not evidence of commit or absence. Expiry or unavailable readback likewise does not authorize a membership mutation or an invented terminal outcome. The central catalog owns the initial-delay default and cap semantics. + +Each invocation samples the aggregate number of `PENDING` operations due at its captured time before loading the bounded, stably ordered page. The `account.join.reconciliation.due.backlog` gauge is the last successful aggregate count; `account.join.reconciliation.due.not.selected` is `max(due backlog - batch-size, 0)`, the estimated due work beyond one page's capacity. The aggregate query reads no operation rows and takes no per-account row locks. These gauges have no account, tenant, or request tags. When the count query fails, both numeric gauges retain their last successful values and `account.join.reconciliation.due.backlog.sample.unknown` becomes `1`; it returns to `0` after a successful sample. The existing `account.join.reconciliation.operations{result="failure"}` counter records the count failure, and the bounded page still runs. + +Operators should alert when `account.join.reconciliation.due.not.selected > 0` while `account.join.reconciliation.due.backlog.sample.unknown == 0`; this means a successful sample found more due work than one invocation can read back. A value of `1` for the unknown gauge means the numeric samples are stale and cannot establish that the backlog is clear; the service logs a warning for each over-capacity sample and for each failed count. The aggregate and page queries use the same captured time but are separate reads, so concurrent rescheduling can make the excess an estimate rather than an exact identity of rows skipped. This is observability only: it does not alter page ordering, retry timing, operation state, or membership. + ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f6933d5f25..36bc17b464 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,13 +8,15 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +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. + 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. When a tenant has zero or multiple subscription rows, the entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field). Focused proof covers zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery; it proves only the cardinality/retry guard. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the full entitlement snapshot/freshness contract remain open, including committed status, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Account V29 persists an immutable, unique, non-nil `account_uuid` with provenance and the unchanged numeric source-row id. The repository writes or reads back that identity for Account rows. This is a storage prerequisite only: REST/gRPC authentication outputs and downstream session carriers do not yet use the UUID. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; implementation and proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status), and [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. -The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and successful deletion immediately removes Account-owned rows including payment transactions. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. +The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, active-subscription deletion guards, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, and the tenant export includes excessive global Account fields. The legacy synchronous deletion path is blocked before deleting any row because complete provider/transfer clearance and retained-record handling are absent; this is containment, not an implemented deletion workflow. These gaps conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. Account V22/V23 rewrite retained email values to canonical form and validate a canonical-email check, but compatibility with older binaries is unproved; the retained-data and rollout proof gap is tracked in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). @@ -22,23 +24,27 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account 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. -Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. - -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +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. 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. -The `GetTenantMembershipForRuntime` proto and Account producer shape carry `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The positive live reader remains fail-closed until positive membership data is available. Text `PLAY` validates the exact account/tenant identity, lifecycle, admission, positive membership version and authority generation for an existing member, and evaluation time before binding. It requires `ACTIVE` membership for admission; only `MISSING` or `INACTIVE` membership can yield public `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks pass. Account connect-token issuance and character discovery still rely on the older membership/admission/version/time fields and do not enforce the emitted lifecycle state or authority generation; a cached-success connect-token replay can return before fresh entitlement, membership, or pointer reads. The response still omits `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints`, so these checks do not prove a complete Account authority snapshot or resolve the reader exposure below. -Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Account owns the explicit `JoinPublicProductionMembership` writer and its REST controller/operation; Game Session direct-text `REALMS`/`JOIN` now uses the retained Account-issued scope and invokes that writer locally. The Gateway route guard still blocks external exposure of `POST /auth/bootstrap/join`; first-party `Join & Play` remains unavailable. On a fresh connect-token issuance or cache miss, Account rechecks selected target, pointer, entitlement, membership, and runtime target, but does not revalidate the applicable private/playtest grant or establish the target membership-version/authority-generation issuance baseline. Exact target/pointer evidence is reread before the JOIN transaction, but no proof binds target validity through Account commit; the strict ADR 0025 commit fence remains incomplete. Recovery after an unknown database commit outcome remains open under ADR 0025/#2848, with no background PENDING-operation reconciler. Exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, broader reconnect/cutover consumption of admission-pointer truth, operator-facing pointer tooling, and the target issuance membership-generation snapshot remain incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`; its current response shape and target routing semantics remain distinct. -The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The Account proto and producer response model declares `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; this is not a live runtime snapshot because current Account membership, entitlement, and grant gRPC handlers fail closed before reads when caller/target binding is unavailable. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. + +Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. It does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread at issuance; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. These paths do not create or restore membership. + +Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct text `JOIN` dispatcher is implemented locally; the Gateway guard blocks external exposure of the Account HTTP route and first-party `Join & Play` remains unavailable. A `PENDING` intent persists before entitlement work; unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` with no fabricated policy evidence. The bounded Account worker is readback-only and terminalizes only exact positive operation, scope, membership, and audit evidence; absent or uncertain evidence remains nonterminal with capped diagnostics and backoff, never terminalized by expiry or attempt limit. Registration/JOIN audit outbox records retain one identity through receiver retries, and Account's producer-side receipt validation and verified-projection marker handling are local code; the separate Logging & Admin receiver/readback remains unavailable in this front; no exact PostgreSQL lost-acknowledgement/concurrency or direct text-to-Logging end-to-end proof is claimed. The target membership-generation snapshot at connect-token issuance remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). + +`GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`; broader reconnect/cutover consumption and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` when the tenant has zero or multiple subscription rows; focused cardinality/retry proof does not establish the full entitlement 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 proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. -The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. +The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. + +The credential-granting gRPC `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` methods require the verified exact Game Session peer before invoking Account credential/challenge operations. Legacy profile GET/PUT require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy reads require that peer. Direct account-ID export, external-link, and verification methods deny before reads or mutation. Runtime membership, grant, and entitlement reads deny even the exact Game Session peer until Unit 1B provides typed caller/target binding. Focused negative tests cover the local guards, but composed certificate and consumer proof remains open; REST guards alone do not protect direct gRPC calls. The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. -Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). +Recovery/verification foundations are live. Password-reset and email-verification completion now claim the exact token row with a conditional SQL delete inside the account transaction before changing Account state; a failed or concurrent losing claim cannot mutate the account, and rollback restores the token. Focused local tests execute the single-use and rollback behavior; PostgreSQL concurrent-reuse cases compile but have not executed without Docker. Session revocation, token registry, distributed abuse controls, and end-to-end email-link reachability remain separate gaps under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -Account locally implements `IssueDirectTextConnectScope` for an authenticated caller and the exact Game Session-resolved public-production target from `REALMS`, validating its retained target snapshot and caller binding. Game Session text `REALMS` calls this RPC locally and retains the returned scope in transport context. Account also implements the `JoinPublicProductionMembership` RPC/operation and local HTTP JOIN route, including retained-target and caller-binding validation; Game Session text `JOIN` dispatch is implemented locally under #2898, while first-party `Join & Play` remains unavailable. Direct text-client end-to-end proof for these local capabilities remains unclaimed. Account request retries can resume a committed policy-independent intent across entitlement outages; after an uncertain second-transaction outcome, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. A bounded readback-only Account recovery worker now revisits abandoned `PENDING` intents without the caller; it cannot rerun the raw bearer-bound JOIN request, terminalize from expiry or absence, or prove direct text-client end-to-end behavior. PostgreSQL recovery, concurrency and direct text-client proof remain open. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -51,8 +57,10 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The Logging & Admin receipt receiver, durable deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipt handling are separate #2848 work and are not implemented in this Account core. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. +- **Target state:** global Account registration creates only global account/security state and a platform-scoped audit outbox entry in the same transaction; successful JOIN records a separate tenant-scoped event using its exact committed `tenantId`. Account preserves one stable event identity and envelope across retries. Logging & Admin owns the typed receipt, exact-payload digest, readback, minimized-evidence, and retention contract; see [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Logging & Admin is not a second authority for Account state. +- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The receiver's target exact payload-byte digest validation and durable readback remain unavailable in this front; the producer cannot treat its request/response validation as proof that those separate receiver capabilities exist. After a matching receipt supplies both terminal status and minimized evidence, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. +- JOIN first commits a policy-independent `PENDING` intent; only an available entitlement result binds the policy digest, `allowPublicJoin`, and entitlement version for the membership/outbox/outcome transaction. An expired scope on a retained `PENDING` request returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation. The bounded Account reconciler is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence, while absent or uncertain evidence remains pending with capped diagnostics and backoff. It never reissues an expired scope or terminalizes by expiry or attempt limit. PostgreSQL unknown-outcome/concurrency proof remains open. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN append to the durable outbox and validate matching receipt responses as described above; receipt delivery/readback remains fail-closed until the separate receiver capability is present and proved. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -65,7 +73,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi ## Data Model -- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. This is Account-local storage identity only; authentication outputs and downstream session carriers do not yet use the UUID. +- `account` table stores username, password hash, email, and status flags for the global platform account, plus the immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. This UUID is Account-local storage identity; authentication outputs and downstream session carriers do not yet use it. - Target `profile` relationships are tenant-scoped and keyed exactly by `{accountId, tenantId}`; profile reads/writes require the corresponding membership and exact tenant filter. Any legacy account-only profile shape is implementation drift and must not authorize or expose a tenant relationship. - Target `achievement` relationships are tenant-scoped and keyed exactly by `{tenantId, accountId, achievementId}` (with any additional version/effect identity carried separately); the legacy “account and game” wording/shape is implementation drift because `game` is not an authority identifier. - Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift. @@ -93,7 +101,7 @@ Transitions are explicit: `active` may move to `security_locked`, `deactivated_p The target restriction command commits the immutable category revision, current projection, account authority-generation effect, and idempotent result in one Account transaction. Logging & Admin may submit a digest-bound command for a punitive platform restriction or appeal outcome, but it remains the policy/case/audit owner and never writes Account tables. The current service does not yet prove this separate platform-ban table/command, recovery isolation, monotonic ordering, or end-to-end generation enforcement. -Account deletion is global, not tenant-scoped. A self-service request requires recent authentication, explicit confirmation, and a clear portable-data export option within the defined account scope. `DeleteAccount` must fail with `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER` until billing authority proves that the account has no owned subscription in `pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, or `suspended`, no nonterminal billing-owner transfer naming it as old or proposed owner, and no unresolved customer, subscription, webhook, outbox, cancellation, or provider-reconciliation work. The response returns all safely disclosable tenant and blocker categories. The caller must complete transfer or terminal cancellation and allow every related durable/provider item to reconcile before retrying deletion. The current implementation proves only the nonterminal-subscription subset of this target precondition. +Account deletion is global, not tenant-scoped. A self-service request requires recent authentication, explicit confirmation, and a clear portable-data export option within the defined account scope. `DeleteAccount` must fail with `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER` until billing authority proves that the account has no owned subscription in `pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, or `suspended`, no nonterminal billing-owner transfer naming it as old or proposed owner, and no unresolved customer, subscription, webhook, outbox, cancellation, or provider-reconciliation work. The response returns all safely disclosable tenant and blocker categories. The caller must complete transfer or terminal cancellation and allow every related durable/provider item to reconcile before retrying deletion. The current service instead returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before any row mutation for every existing account; it does not claim that the complete provider/transfer guard, pending-deletion lifecycle, or finite retained-record schedule is implemented. This containment remains in place until those gates are proved. An eligible confirmed request enters `deactivated_pending_delete`, immediately revokes ordinary account and bootstrap authority, and hides normal account/profile surfaces. Only explicit deletion cancellation, export, and necessary billing-settlement routes remain during the published cancellation and retention window. A durable, idempotent cross-service workflow then deletes, anonymizes, tombstones, or schedules policy-allowed retention for each owning domain. Failed work leaves the account pending with retry and operator diagnostics; a durably scheduled billing/provider step is intermediate pending evidence only and never terminal deletion. The account becomes terminal `deleted` only after every required non-retained step has completed and every permitted retained record has been durably finalized under its approved retention policy. @@ -149,7 +157,7 @@ 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. Target behavior creates public-game membership only through explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` require existing membership and recheck applicable grants, entitlements, and the selected runtime target. In the current Account surfaces, 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 as `CONNECT_TOKEN_REJECTED`. World and realm discovery remain available before membership, and none of these Account paths creates or restores membership. Current Game Session text `PLAY` is lifecycle-aware: it validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence; `ACTIVE` is required for admission, and only fresh `MISSING` or `INACTIVE` membership can receive public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks pass. Its remaining outcome mapping is owned by [Authentication](../../system-architecture-authentication.md). The Account-owned JOIN writer/controller is implemented, but the Gateway route guard blocks external exposure; direct text `JOIN` dispatch is also implemented, while first-party `Join & Play` remains unavailable. Durable recovery after an unknown database commit outcome remains open. Non-public or non-visible 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 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. - 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. @@ -186,7 +194,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `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 the opaque generation. Older Account issuance and character-discovery consumers still omit checks for those fields; text `PLAY` validates lifecycle state and authority generation against the fresh response. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. +- `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`. Although the generated proto and response model include `membershipLifecycleState` and the opaque generation, the live gRPC handler rejects before reading and does not return that response. Game Session text `PLAY` validates lifecycle, version, and generation only on supplied-authority paths; for eligible public-production membership, that classification permits `JOIN_REQUIRED` only for missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership remains denied. This unit-level classification does not prove a live Account snapshot or runtime admission. Account issuance and character-discovery consumers also remain incomplete for these fields. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. Detailed capability and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. @@ -278,9 +286,15 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### 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 connect-token issuance consumes membership/admission/version/time evidence and requires existing membership; only missing membership on an eligible public-production target may return `JOIN_REQUIRED`, while an existing non-admitting membership is denied. Character discovery checks membership after fresh entitlement and target checks. The Account response also carries lifecycle and authority-generation evidence, which text `PLAY` validates against exact identity and freshness before binding; its public `JOIN_REQUIRED` gate follows fresh entitlement and `allowPublicJoin` checks as defined in [Authentication](../../system-architecture-authentication.md). The Account-owned explicit public-production JOIN writer and operation controller, including `POST /auth/bootstrap/join`, are implemented locally; the Gateway route guard still blocks external exposure. Game Session direct text `JOIN` dispatch is also implemented locally, but first-party `Join & Play` remains unavailable. The current non-public behavior differs by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when it exists but does not admit gameplay, while 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. The Account JOIN writer uses a policy-bound v1 digest and records membership, operation outcome, and audit outbox evidence in one transaction; recovery after an unknown database commit outcome remains open under ADR 0025/#2848, as do Logging receipt receiver/readback. PostgreSQL exact-final-head proof, direct text-client/end-to-end proof, and the target membership-version/authority-generation baseline reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +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. + +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 still fail closed before reads because their requests cannot prove caller/target binding, so those 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). + +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. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Reconnect flow consumption of admission-pointer truth remains incomplete; replacement cutover flow consumption remains incomplete, and operator pointer tooling is incomplete. -Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. +`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 retention/deletion cleanup and deletion reconciliation remain unimplemented; producer-payload minimization is implemented but does not establish that cleanup. 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. ## Monetization and Notification Domain Notes @@ -288,6 +302,8 @@ Account deletion currently fails closed when `hasRetainedOperation` finds any re Billing provider integration, instrument ownership, payment reconciliation, and the reserved future-marketplace entitlement substrate are canonical in [Stripe Integration Design](./stripe-integration.md). Subscription status lifecycle and plan-change timing are canonical in [Subscription Management Design](./subscription-management.md). +The current virtual-currency gRPC facade returns `FAILED_PRECONDITION` for `GetBalance`, `AddCurrency`, and `SpendCurrency` before touching its existing storage/service substrate. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers likewise return `FAILED_PRECONDITION` before service/provider calls. These are fail-closed containment of unsupported v1 operations, not a completed economy, hosting-billing operation, or entitlement source; their underlying service substrate remains provider-mutating and unavailable for supported use under the [Stripe owner contract](./stripe-integration.md). + Runtime and data consequences remain local to this document: `payment_transaction` is the financial/provider audit record, while `purchase_entitlement` is reserved for a separately accepted future marketplace and is not a v1 hosting-billing authority. Account must not infer gameplay value from payment status alone; a future paid-but-unfulfilled grant would remain non-active and therefore non-authorizing, and its durable operation state would remain visible to reconciliation and deletion guards. Existing donation rows and virtual-currency/premium-hosting code remain implementation substrate unless a supported product contract explicitly admits them; creator donations/tips are deferred. ### Deferred Creator Monetization diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 85c8f1c257..493d0e244c 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -19,7 +19,7 @@ The future direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-crea ## Implementation Status -The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying provider-mutating service methods remain unsupported substrate. Only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. +The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, provider/transfer deletion clearance, retained financial-evidence lifecycle, and end-to-end entitlement enforcement. `DeleteAccount` currently returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` for every existing account before deleting any row; this is containment, not a completed deletion workflow or proof of provider/transfer/active-subscription clearance. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs reject with `FAILED_PRECONDITION` before `PaymentService` or provider invocation. The underlying provider-mutating service and purchase-workflow substrate remain unsupported, not a v1 product path or entitlement source; only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation remain reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). The account-owned wallet contracts are also target state. Per-subscription instrument binding, replacement-before-detach, the single-use transfer proof and database transfer fence, immutable predecessor-provider history, and the audited `cross_tenant_billing_safe` ownership-transfer route remain absent or partial until the corresponding routes and enforcement are implemented; the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) records that coverage drift. @@ -119,7 +119,7 @@ If a future marketplace is separately accepted, it must define disjoint typed op - A fixed product purchase supplies an immutable `product_code`; it does not accept caller-authoritative `amount_cents` or currency. Account resolves the active product, price, currency, and catalog revision from the server-side Stripe product catalog. The resolved values are immutable inputs to the purchase digest and durable `purchase_operation`, and the same values are used for the Stripe `PaymentIntent`, checkout binding, webhook correlation, and reconciliation. - A variable donation uses a separate donation amount path. The caller may supply an amount only within the server-configured minimum, maximum, precision, and currency bounds; Account rejects fixed-product fields on that path and records the accepted bounded amount and server-authoritative currency in the digest and durable operation. A donation amount must never be interpreted as a fixed product price. -1. A future typed purchase or donation operation calls the Account Service with the appropriate fixed-product or bounded-donation variant, authenticated context, optional `tenantId`, and caller request ID. Under the target containment contract, the generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` methods reject before any Stripe mutation; their current provider-mutating implementation remains the drift recorded above. For an accepted future typed operation, Account derives the authoritative account from authenticated context and, before any external Stripe customer or `PaymentIntent` call, commits one durable `purchase_operation` and its webhook-correlation identity bound to the operation type, caller request ID, immutable purchase digest, resolved commercial values, customer-operation reference, and separate stable PaymentIntent idempotency identity. The webhook must resolve through this durable operation identity rather than a provider ID that may not yet have been persisted. +1. A future typed purchase or donation operation calls the Account Service with the appropriate fixed-product or bounded-donation variant, authenticated context, optional `tenantId`, and caller request ID. Under the target containment contract, the generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` methods reject before any Stripe mutation; their current gRPC handlers do so, while the underlying provider-mutating service substrate remains unavailable for supported use. For an accepted future typed operation, Account derives the authoritative account from authenticated context and, before any external Stripe customer or `PaymentIntent` call, commits one durable `purchase_operation` and its webhook-correlation identity bound to the operation type, caller request ID, immutable purchase digest, resolved commercial values, customer-operation reference, and separate stable PaymentIntent idempotency identity. The webhook must resolve through this durable operation identity rather than a provider ID that may not yet have been persisted. 2. The Account Service provisions or reuses the Stripe customer through the same durable intent contract as `billing_customer`: persist the account-keyed provisioning intent and stable customer-provisioning idempotency identity, reconcile provider metadata before retrying after a timeout, lost response, or failed local commit, and leave ambiguous state nonterminal. A generic lookup-or-create flow after an ambiguous attempt is prohibited. Once the customer is confirmed, Account calls Stripe to create the `PaymentIntent` using the purchase operation's distinct stable payment-intent idempotency identity and non-secret provider metadata carrying the durable purchase-operation correlation identity. 3. A `payment_transaction` row is created in `pending` status and linked to the purchase operation, with the returned `payment_intent` ID recorded as `provider_id`. If the provider call may have succeeded but the response or local linkage commit is lost, the operation remains nonterminal and reconciliation uses the same idempotency and provider-metadata identities; it never creates a new logical purchase attempt. 4. The client completes payment using Stripe’s client-side flow (for example, via Stripe.js); Stripe later calls a configured webhook when the intent succeeds or fails. @@ -170,10 +170,10 @@ Stripe integration must preserve tenant isolation while allowing platform-level The Account Service exposes gRPC and REST endpoints for initiating and inspecting billing flows: -- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe, with valid and malformed requests covered by no-dispatch proof. The underlying provider-mutating service method remains unsupported and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. -- `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe; its underlying provider-mutating service method remains unsupported and is not a supported v1 product path. -- `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe and preserves `success=false`; its underlying provider-mutating service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. -- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and explicit instrument-selection input. Account resolves and authorizes the authoritative billing owner server-side, then computes the versioned `requestDigest` from normalized create fields and that resolved owner; neither the owner nor digest is caller supplied. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller `requestId` or instrument-selection input, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. +- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. The RPC returns `FAILED_PRECONDITION` before `PaymentService` or Stripe invocation, so it cannot create a v1 entitlement. The underlying provider-mutating method remains unsupported. Only a separately typed hosting-billing operation may call Stripe. +- `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. The RPC returns `FAILED_PRECONDITION` before service/provider invocation; its retained provider-mutating method remains unsupported and is not a v1 product path. +- `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. The RPC preserves `success=false` and returns a `FAILED_PRECONDITION` `ErrorDetail` before service/provider dispatch. Hosting refunds use a separately typed operation and durable workflow; future marketplace refunds require the accepted value-conservation contract. +- `CreateSubscription` – Target one recurring hosting subscription for an immutable `tenantId` and initial `plan_code`, with caller-stable `requestId`, explicit instrument selection, and Account-resolved billing-owner authorization. Account computes the versioned digest from normalized fields and the resolved owner; neither owner nor digest is caller supplied. Exact retries replay the durable operation and changed intent returns `IDEMPOTENCY_CONFLICT`; provider `subscription_provisioning_request_id` remains a separate identity. The current proto lacks the caller-stable `requestId`, owner-resolution evidence, and instrument-selection input, so the handler fails with `FAILED_PRECONDITION` before local/provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. - Subscription and transaction query APIs – Must be split into explicit tenant-scoped billing-safe, cross-tenant support-safe, and cross-tenant billing-safe variants (no mixed-mode endpoint behavior). Per-tenant caller-bound billing history is visible to `tenantAdmin`; global `platformAdmin`/`billingAdmin` access uses cross-tenant billing-safe variants only. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 598505a693..89199eed50 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -23,7 +23,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist - Track revision history for rollback - Orchestrate cross-service publish workflows and notify downstream services when new versions are available. - Accept branding uploads into the current Game Design persistence boundary and, during publish, export a `manifest.json` and version-scoped objects. No public asset `GET`/download route exists; the target private-candidate/content-addressed export and approved public `/assets/**` delivery let runtime clients load themes and logos without calling this service. -- **Current hosted-route consequence:** the Gateway's coarse `/api/design/**` route currently forwards `/api/design/assets` through `StripPrefix=2` to the live `POST /assets` controller. Because Game Design has no Account hosted-terms/currentness gate, official-hosted asset-upload readiness remains blocked until Gateway denies the route or the exact Account-owned gate is implemented and proved. +- **Current hosted-route consequence:** Gateway currently exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Act as the sole owner of game asset publishing to the S3-compatible object store; **target state:** downstream services and clients read published assets via approved configured delivery URLs and do not write directly to the asset store. In the current first slice, private MinIO/object-store URLs are not public client delivery. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services and are not stored as blobs in the asset store. - When publish workflows need to expose derived domain artifacts outside their owning service storage (for example world navmesh/path graph bundles), Game Design remains the sole object-store writer. Owning domain services hand those artifacts to the publish workflow as explicit inputs; they do not bypass the publish workflow with direct object-store writes. - **Target state:** Runtime discovery of derived artifacts uses the version `manifest.json` attested by `published_release_bundle`. The target canonical attestation shape includes `artifactDigests[]`, `requiredManifestAssetKeys[]`, and `manifestHash`; the current persisted bundle is narrower and lacks those complete target fields, so consumers must not treat current output as complete release proof or depend on undocumented bucket key conventions. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 6f2adfb281..67e405fba6 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -12,7 +12,7 @@ For official hosted deployments, every creator-intent content-bearing mutation e Game Design records only the local committed evidence-binding tuple `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` for a covered operation, where `generation` is Account's material-acceptance generation; it does not copy the Account terms/party catalog. The exact Account party, evidence, and generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, and the boundary requires commit-bound authority/fence or equivalent validation without selecting its mechanism. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority fails closed by aborting the local transaction before any creator mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. An exact durably committed retry replays its stored outcome and local evidence. An uncertain or not-durably-committed attempt first reconciles the original stable identity and obtains durable no-commit proof; it is not blindly redispatched or mutated while indeterminate. Only a permitted fresh attempt performs a fresh commit-bound currentness check. Reusing the same identity with changed normalized payload returns the target application outcome `IDEMPOTENCY_CONFLICT` before mutation. Game Design does not infer signer authority or materiality. -Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. Game Design currently checks only its privileged JWT/tenant access boundary; it does not evaluate Account hosted-terms/currentness authority. Official-hosted asset-upload readiness is therefore blocked until that route is denied or the exact Account-owned gate is implemented and proved. +Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway exposes only `GET /api/design/ping` and `GET /api/design/templates`, not the service-local `POST /assets` or `POST /templates` controllers. Those creator writes currently check only privileged JWT/tenant access and do not evaluate Account hosted-terms/currentness authority. Official-hosted creator-write readiness remains blocked until the exact Account-owned gate is implemented and proved; the Gateway restriction is containment, not a substitute for the owner-side gate. ## Draft Commit and Proposal Semantics (Target State) @@ -104,11 +104,11 @@ Default ports: REST on `8080`, gRPC on `6565`. ### REST - `GET /ping` – basic health check returning `"pong"`. -- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is currently reachable but is not readiness-approved for official-hosted use until the hosted-content gate is implemented and its required proof is validated. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. +- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The current Gateway catalog does not expose `/api/design/assets`; this does not make the service-local controller ready for official-hosted use. Once the hosted-content gate and its required proof are implemented, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `POST /templates` – create a new game template. Its external official-hosted exposure is target-only and must remain unavailable until the hosted-content gate is implemented and its required proof is validated. Once enabled there, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any persistence side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `GET /templates` – list templates for a tenant. -Externally routed Game Design REST paths use the Gateway allowlist prefix (for example `/api/design/assets` and `/api/design/templates`) and are stripped to the service-local paths above before reaching Game Design. Game Design owns validation and authoritative domain/publishing audit behavior for these creator workflows, while Account remains authoritative for hosted-terms/currentness evidence. Logging & Admin may receive a non-authoritative operator-audit projection for actions that enter its ingress; that projection does not transfer publishing-audit ownership. Operator writes for moderation, quota overrides, runtime feature-flag overrides, and tick remediation remain Logging & Admin ingress only and are not part of this bypass-safe creator-write class. +Externally routed Game Design REST paths use the Gateway allowlist prefix and are stripped to the service-local paths above before reaching Game Design. The current inventory contains only `GET /api/design/ping` and `GET /api/design/templates`; future `/api/design/assets` and template-write exposure requires an explicit catalog entry after the owner-side gate is implemented and proved. Game Design owns validation and authoritative domain/publishing audit behavior for these creator workflows, while Account remains authoritative for hosted-terms/currentness evidence. Logging & Admin may receive a non-authoritative operator-audit projection for actions that enter its ingress; that projection does not transfer publishing-audit ownership. Operator writes for moderation, quota overrides, runtime feature-flag overrides, and tick remediation remain Logging & Admin ingress only and are not part of this bypass-safe creator-write class. ```bash curl http://localhost:8080/ping diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..5ab0aa0821 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -8,7 +8,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which is the retained repair source selected by the process-local snapshot for Published/Active binary assets. This source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. -- **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. +- **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The Gateway's explicit read-only Game Design routes do not forward `/api/design/assets` to the live `POST /assets` controller, whose service-local boundary still checks only privileged JWT/tenant access. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved; edge containment is not the owner-side gate. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. - **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..dc935f8208 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -117,7 +117,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** supplied-authority text `PLAY` returns `JOIN_REQUIRED` only for eligible missing or `INACTIVE` public membership; an `ACTIVE` but non-admitting membership returns `WORLD_ACCESS_DENIED`, consistent with the canonical [Authentication admission boundary](../../system-architecture-authentication.md#in-band-play-admission-boundary). Current connect-token issuance does not yet validate the private/playtest realm grant; see [Authentication implementation status](../../system-architecture-authentication.md#implementation-status) for the owner boundary and status. - **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index a2b181c68a..abcc974307 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,9 +12,11 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Current two-token `PLAY ` shorthand recognizes only visible realm names and otherwise treats the name as a character selector; an explicit `PLAY ` retains its realm selector even when unresolved or hidden. Non-public missing or non-admitting membership is first classified as `WORLD_ACCESS_DENIED`; a definitive denial for a selected realm that is not both visible and public-production returns generic `PLAY_SELECTION_REQUIRED`, even when its containing world is publicly discoverable. For a discoverable world, this projection matches the unresolved-realm result; the existing generic projection for a non-discoverable world is retained. A visible public-production target retains its canonical `WORLD_ACCESS_DENIED` outcome, and unavailable authority is not masked. This is current implementation behavior, not a target-contract change; canonical error ownership and discovery policy remain in [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Account owns the target independent issuance-time reread of `membershipVersion` and `membershipAuthorityGeneration`; current proof for that baseline and target validation of connect-token grants for private/playtest scopes remain incomplete (see [Account Runtime and Data](../account-service/runtime-and-data.md#membership-and-entitlement-authority)). +Unless stated otherwise, this document records local protocol consequences; canonical JOIN eligibility, admission outcomes, and exact evidence rules belong to [Authentication](../../system-architecture-authentication.md). The target direct-text flow is public `WORLDS` -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current LOGIN establishes global Account identity without a tenant or membership prerequisite; bootstrap tenant remains routing context. Direct-text `JOIN` is implemented locally as a Game Session command translated to Account's `JoinPublicProductionMembership`; the Gateway blocks external access to Account's HTTP route and first-party browser `Join & Play` remains unexposed. A grant never creates or substitutes membership. -For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. +Current text `PLAY` validates supplied membership identity, lifecycle, admission, version, authority generation, and evaluation time; `ACTIVE` is required for positive admission. Public `JOIN_REQUIRED` classification requires fresh eligible public-production context, entitlement, and `allowPublicJoin`; an active non-admitting member is denied without JOIN advice. The live Account runtime membership, entitlement, and grant readers fail closed before data access because their requests lack typed caller/target binding, so the local supplied-authority branches do not establish a live public `PLAY` or composed `JOIN_REQUIRED`. Current two-token `PLAY ` shorthand recognizes only visible realm names and otherwise treats the name as a character selector; explicit `PLAY ` preserves its realm selector. Definitive denial for a hidden or non-public-production realm matches unresolved explicit-realm selection even inside a publicly discoverable world; non-discoverable worlds retain generic selection-required output without target metadata. Visible public-production denial and unavailable authority remain distinct, under [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive private-grant and entitlement evidence must match exact applicable scope, include positive versions and billing sequence, and be no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Account owns the target independent issuance-time reread of `membershipVersion` and `membershipAuthorityGeneration`; its proof and target validation of connect-token grants for private/playtest scopes remain incomplete. Pending-operation readback and exact PostgreSQL/direct-text proof remain open. + +For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh authoritative `LOOK` remains. This fail-closed behavior does not establish the durable successor protocol or complete either ADR. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -45,7 +47,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, direct-text `JOIN` is available through Account's explicit membership writer, while first-party `Join & Play` remains unavailable. `PLAY` requires fresh, identity-matched membership evidence with positive membership version and authority generation for an existing member; positive admission requires lifecycle `ACTIVE`. A well-formed fresh `MISSING` or non-admitting `INACTIVE` membership can still return `JOIN_REQUIRED` for eligible public-production entry; non-public denial retains the underlying `WORLD_ACCESS_DENIED` classification and follows the discoverability-based player projection described in [Implementation Status](#implementation-status). Positive grant and entitlement snapshots require their exact scope identifiers, positive versions and billing sequence, and evaluation time within 15 seconds and not in the future. Invalid positive evidence returns retryable authority or entitlement unavailable without changing the binding. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – Existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY`; first public-production entry requires explicit `JOIN`. Game Session direct-text `JOIN` dispatch and Account's explicit writer exist locally, but first-party `Join & Play` remains unavailable and the Gateway blocks the external Account route. Current `PLAY` requires fresh identity-matched lifecycle/version/generation evidence and validates positive grant/entitlement scope and freshness; only eligible public `MISSING` or `INACTIVE` membership may reach `JOIN_REQUIRED` after entitlement and public-policy checks. Account's live runtime readers fail closed before reads, so no composed live admission is established. Non-public denial is not converted to public JOIN advice; see [Implementation Status](#implementation-status) and [Authentication](../../system-architecture-authentication.md). Players may use lobby helpers such as `REALMS` and `CHARS` to disambiguate selection. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -70,7 +72,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where target `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; target behavior never resolves a bare `worldSlug` globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Direct-text command implemented; target selector form remains unavailable.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. The target `` uses the same tenant-scoped selector rules as `REALMS`; the current command accepts a bound WORLDS index or the bare world slug of a uniquely resolved current catalog world, not `tenantSlug/worldSlug`. This bare-slug path is implementation drift. | `JOIN demo/demo` (target) | +| `JOIN ` | **Direct-text command implemented locally; target selector form and end-to-end/runtime proof remain incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. Current local input accepts a snapshot-bound `WORLDS` ordinal or a uniquely resolving bare world slug against the current catalog; the latter is implementation drift. The pointer projection lacks `tenantSlug`, so the target stable `tenantSlug/worldSlug` selector is unavailable. PostgreSQL/recovery and full direct-text/Telnet and first-party path proof remain open. | `JOIN 1` (from the current `WORLDS` response) | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | @@ -88,7 +90,7 @@ Selector rules for `PLAY` match the lobby helpers. Target `WORLDS` returns the s The canonical JOIN and membership-admission contract is defined in [Authentication & Authorization](../../system-architecture-authentication.md#normative-target-contract); this section keeps only Game Session's protocol translation and local handling. -The Account membership operation is `JoinPublicProductionMembership`; the direct-text implementation is current and remains the sole membership writer, with Account-owned membership and audit/outbox consequences. Game Session translates `JOIN ` to that operation; it does not create membership locally or use another join writer. The first-party `Join & Play` action remains target-only. +The target Account membership operation is `JoinPublicProductionMembership`; the local Account operation and Game Session translation/scope seam now exist, and there is no current implicit membership writer. The local path does not claim complete direct-text/first-party transport proof, PostgreSQL execution, or pending-operation recovery. Game Session translates `JOIN ` to the sole operation; it does not create membership locally or use another join writer. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the Account-issued scope in the shared Redis lobby record keyed by the stable numeric transport session ID. Atomic per-key compare-and-set preserves that request identity across retries and Game Session replacement. The record contains no raw JWT; the Account scope is bound to exact account/session identity and expires within its bounded lifetime. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. The target contract requires Account to validate that target at the membership commit boundary (see [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative)); the current Account implementation checks the stored scope and target before the membership transaction, and no target-through-commit fence or commit-time target revalidation is proved. A client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. @@ -120,7 +122,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; actionable `JOIN_REQUIRED` is limited to a public-production target where the fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing (`MISSING`) membership or existing `INACTIVE` membership whose `gameplayAdmissionAllowed` is false. Fresh entitlement validation must also confirm gameplay availability and `allowPublicJoin=true`. Current Account proto encodes `membershipAuthorityGeneration` as `uint64`, and text `PLAY` requires it to be positive for an existing member; that representation and positivity check are implementation drift from the target opaque, exact-equality-only semantics owned by [Account Runtime and Data](../account-service/runtime-and-data.md#membership-and-entitlement-authority). A valid non-public missing or non-admitting membership is classified as `WORLD_ACCESS_DENIED`, with the current player-facing result projected to generic selection guidance when its world is absent from public `WORLDS` discovery (see [Implementation Status](#implementation-status)). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. Account owns the required independent issuance-time reread of both membership version and authority generation; the baseline proof and connect-token grant validation for private/playtest scopes remain incomplete under the [Account runtime contract](../account-service/runtime-and-data.md#membership-and-entitlement-authority). +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. On supplied-authority branches, text `PLAY` validates exact account/tenant identity, membership existence and lifecycle, admission permission, membership version, authority generation, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; actionable `JOIN_REQUIRED` is limited to a public-production target where the fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing (`MISSING`) membership or existing `INACTIVE` membership whose `gameplayAdmissionAllowed` is false. Fresh entitlement evidence must match the exact tenant, confirm gameplay availability and `allowPublicJoin=true`, and carry a positive entitlement version and billing sequence. These local classifications do not establish live admission: Account membership, entitlement, and grant readers fail closed before data access. A definitive denial for a selected hidden or non-public-production realm matches unresolved explicit-realm selection even inside a publicly discoverable world; unavailable authority remains distinct. For other membership or grant denials, current `WORLD_ACCESS_DENIED` projects to generic selection guidance when that world is absent from public `WORLDS` discovery. The current proto encodes `membershipAuthorityGeneration` as `uint64` and text `PLAY` requires it to be positive for an existing member; both are implementation drift from the target opaque, exact-equality-only semantics owned by [Account Runtime and Data](../account-service/runtime-and-data.md#membership-and-entitlement-authority). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. For all positive grant and entitlement evidence, freshness means no more than 15 seconds old and not in the future. Account owns the independent issuance-time reread of membership version and authority generation; the baseline proof and connect-token grant validation for private/playtest remain incomplete. See [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) for canonical ordering. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -169,9 +171,9 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. -- `ACCOUNT_MISMATCH` – **target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current implementation's persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – after current routing and authority checks, a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing membership (`membershipExists=false`/`membershipLifecycleState=MISSING`) or existing `INACTIVE` membership (`gameplayAdmissionAllowed=false`); a fresh entitlement response must also confirm gameplay availability and `allowPublicJoin=true`. The selected target must be public production. This is actionable through the implemented direct-text `JOIN`; first-party `Join & Play` remains unavailable, and complete direct-text/Telnet proof remains open. A grant or cached discovery result is not a substitute. Current `PLAY` consumes Account's lifecycle, membership-version, and authority-generation fields and does not infer `INACTIVE` from a boolean alone. Canonical eligibility and ordering remain owned by Authentication. -- `WORLD_ACCESS_DENIED` – current admission classification for a private, playtest, or other non-public target whose membership/admission predicate or existing grant check denies access; no public join action is offered. When the selected world is absent from public `WORLDS` discovery, current `PLAY` projects this definitive denial as generic `PLAY_SELECTION_REQUIRED` without target metadata (see [Implementation Status](#implementation-status)); publicly discoverable worlds retain `WORLD_ACCESS_DENIED`. +- `ACCOUNT_MISMATCH` – **Target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. +- `JOIN_REQUIRED` – canonical actionable advice only for an eligible public-production target after current routing and authority checks, when a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports missing (`membershipExists=false`/`membershipLifecycleState=MISSING`) or existing `INACTIVE` membership (`gameplayAdmissionAllowed=false`). Fresh entitlement must confirm gameplay availability and `allowPublicJoin=true`. `ACTIVE` but non-admitting membership gets no JOIN advice. The implemented direct-text `JOIN` is local; first-party `Join & Play` remains unavailable and direct-text/Telnet proof remains open. A grant or cached discovery result is not a substitute. Account runtime readers currently fail closed before data access, so no composed live `JOIN_REQUIRED` is established; the live membership failure maps to `WORLD_ACCESS_DENIED`. Canonical eligibility and ordering are owned by [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). +- `WORLD_ACCESS_DENIED` – current denial for private, playtest, or other non-public targets whose membership/admission or existing grant check denies access; it offers no public join action. If the selected world is absent from public `WORLDS` discovery, current `PLAY` projects the definitive denial as generic `PLAY_SELECTION_REQUIRED` without target metadata; publicly discoverable worlds retain `WORLD_ACCESS_DENIED` (see [Implementation Status](#implementation-status)). - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. - `INVALID_ARGUMENT` – session ID parsing or other validation failed before the handler reached gameplay state. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7ca506ddb7..aebb96d876 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -10,6 +10,8 @@ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenant `CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. +Both typed receipt responses carry `auditProjectionVersion=1` only when the receiver has durably linked the exact scope-qualified receipt to a distinct `log_events` audit projection in the same transaction. `receiptId` names the durable receipt; `logEventId` names the linked projection, not the receipt row's surrogate. The projection retains bounded identity metadata rather than another payload copy, including after payload minimization. Missing (`0`) or unsupported versions are not evidence of this capability; Account rejects them before marking delivery verified. The version marker never substitutes for the complete envelope, receipt/projection identity, status, and outcome checks above. Enabling version 1 does not attest historical Account outbox IDs or rewrite their unknown projection provenance; recovery requires exact current readback and guarded Account-owned recording. See [Account Runtime and Data](../account-service/runtime-and-data.md#implementation-status). + At this stage, `CreateLogEvent` returns gRPC `UNIMPLEMENTED` before request validation or dispatch, and `ReadLogEventReceipt` has no handler. The target workload-only mTLS/method-allowlist receiver, durable receipt/readback, and runtime proof remain unavailable; the target contract is not an implementation claim. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md index be9c9b0eac..d1718c1a24 100644 --- a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md +++ b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md @@ -35,7 +35,7 @@ Unless explicitly described as current behavior, the sections below define the target Gateway contract. Current implementation facts and gaps are: - Java `CanonicalGatewayRoutesConfiguration` is the current route authority, with environment overrides; the target route catalog and deny-by-default exposure rules still require convergence proof. It currently has no `/assets/**` route or asset-store route ID; published asset delivery remains target-only pending a separate approved public origin/provisioner, and private MinIO is not public delivery. -- **Current Game Design route consequence:** the current coarse `/api/design/**` route forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. That controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate, so official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current Game Design route consequence:** the Java route catalog forwards only `GET /api/design/ping` and `GET /api/design/templates` through `StripPrefix=2`. It does not forward `POST /api/design/assets` or `POST /api/design/templates`; their service-local controllers still lack the Account hosted-terms/currentness gate. Official-hosted creator-write readiness remains blocked until that exact owner-side gate and proof exist. - The current edge implements bounded connect-token handshake classes and replay handling, but this does not prove the complete target replay durability, rotation, or reconnect contract. - **Current drift:** the protected admin `JwtAuthFilter` parses shared-HMAC JWTs through `JwtUtil`. This is current implementation behavior only, is not a player-facing asymmetric-validation capability, and must not be confused with the target receiving-service boundary. - **Target boundary:** On protected admin routes, Gateway requires an `Authorization` header at ingress and forwards it without parsing or validating ordinary JWT contents; consuming services own asymmetric JWKS validation under [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). @@ -57,7 +57,7 @@ Unless explicitly described as current behavior, the sections below define the t - `/ws/game/**` -> Game Session Service. - `/api/admin/**` -> Logging & Admin Service. -- `/api/design/**` -> Game Design Service. +- `GET /api/design/ping` and `GET /api/design/templates` -> Game Design Service in the current Java catalog; additional `/api/design/**` exposure requires an explicit reviewed entry. - `/api/account/**` -> Account Service. - `/api/session/**` -> Game Session Service HTTP control-plane family. - `/api/social/**` -> Social Groups Service. diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 4135413074..736a4bf568 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -62,7 +62,7 @@ An explicit certificate-instance revocation, identity removal, or emergency trus - Spring Cloud Gateway is stateless and sits in the DMZ alongside the TCP Proxy Service. - Target route configuration lives in `routes.yml`, imported by `application.yml` and reloaded on startup. Current code remains Java-owned until that convergence lands. -- **Current hosted-route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. Because Game Design has no Account hosted-terms/currentness gate, official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current hosted-route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates` to Game Design, with `StripPrefix=2`. It does not expose `POST /api/design/assets` or `POST /api/design/templates`; their service-local controllers still lack the Account hosted-terms/currentness gate, so official-hosted creator-write readiness remains blocked until that exact owner-side gate and proof exist. - The target files define the baseline route set for each environment. - Explicitly enabled dev/test route APIs may overlay bounded in-memory changes on one disposable runtime; player-facing environments use only the version-controlled baseline and must fail startup if mutation is enabled. - The default route configuration defines the core service routes required for local Docker Compose environments. diff --git a/design/architecture/microservices/tcp-proxy-service/README.md b/design/architecture/microservices/tcp-proxy-service/README.md index 76e8b857f5..e16f367642 100644 --- a/design/architecture/microservices/tcp-proxy-service/README.md +++ b/design/architecture/microservices/tcp-proxy-service/README.md @@ -24,7 +24,7 @@ When code, tests, and docs diverge, align implementation to this doc set and the | Area | Target behaviour | Current status | Tracked in | | --- | --- | --- | --- | -| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | Direct-text `LOGIN`, `PLAY`, and the Account-backed `JOIN` command are implemented with focused local proof. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target, Game Session `PLAY` validates fresh membership lifecycle/version/generation evidence and evaluates fresh entitlement/public policy before returning `JOIN_REQUIRED`; a text client can then invoke the implemented `JOIN` writer. Full Telnet discovery/bridge and PostgreSQL/recovery proof, manual end-to-end QA, first-party `Join & Play`, and the target connect-token issuance baseline/generation reread remain open. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | +| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | Local `PLAY` response-classification tests exercise supplied Account authority, and the Account JOIN RPC plus direct-text REALMS-scope/JOIN dispatch exist locally. The live Account membership, entitlement, and grant handlers return `FAILED_PRECONDITION` before reading data, which Game Session maps to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. The proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`. PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | | Proxy -> Gateway WebSocket mTLS | TCP Proxy is the WebSocket mTLS client: it presents the dedicated `FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH` and `FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH` identity to the Gateway server, with `FIREMUD_GATEWAY_WS_CA_CERT_PATH` for trust, while Gateway verifies the exclusive environment-bound identity required by [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). This client identity is distinct from TCP Proxy's internal gRPC server mTLS identity and from the separate Telnet server-TLS identity. | TCP Proxy now loads and rotates the dedicated PEM client identity and Gateway CA into one hostname-verifying client shared by gameplay bridges and Gateway readiness, rejects plaintext unless an explicit local/dev/test profile is active, and fails new admission closed after an invalid reload. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the dedicated authenticated Gateway listener, separate Gateway-server/TCP-Proxy-client Secret mounts, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned certificate issuance/projection and live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | | Optional classic-client semantic extensions | Plain text remains universal. MCP/GMCP/Telnet semantic negotiation and package support are deferred, unadvertised, and unsupported in shared, player-facing, and prod-like profiles; an explicit local/development/test profile may enable only the legacy marker/greeting seam for bounded development use. If a future adapter is selected, Game Session owns semantics while TCP Proxy remains a generic bounded bridge. | The current `TCP_PROXY_MCP_ENABLED` marker/greeting seam is implementation drift, not semantic support. Target startup rejects it in shared, player-facing, and prod-like profiles; only explicit local/development/test profiles may enable the marker, and the profile rejection is not yet proved. No interoperability or end-to-end extension proof exists. | [MCP-01](../../decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | | Connection limits and abuse protection | Connection caps, idle timeouts, input size limits, buffering, and generic opaque-marker safety protect the DMZ boundary. TCP Proxy does not parse or maintain classic-client semantic state. Accepted input that exceeds a generic limit or cannot be forwarded under backpressure receives an explicit error/close rather than a keep-open silent discard. | Core limit handling is implemented; tuning and additional metrics may evolve as production behaviour is observed. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | @@ -47,7 +47,7 @@ Public Telnet TLS is configured as one of two mutually exclusive modes: a dedica - `readiness` is traffic-admission safety for new Telnet sessions. The service is ready only when: - the Telnet listener is bound; - the proxy can reach Spring Cloud Gateway’s readiness surface for the gameplay route; and - - the downstream gameplay admission path supports completion through the first `LOOK` for callers with the required existing membership and target-specific visibility/grant authority: `connect -> LOGIN [secret] -> PLAY -> first LOOK`. For an otherwise eligible public-production caller whose `PLAY` returns `JOIN_REQUIRED`, it must also support `JOIN -> PLAY` before `LOOK`; returning `JOIN_REQUIRED` alone is not sufficient readiness. Local command support does not prove end-to-end Telnet readiness. + - the downstream gameplay admission path supports completion through the first `LOOK` for callers with required existing membership and target-specific visibility/grant authority: `connect -> LOGIN [secret] -> PLAY -> first LOOK`. For otherwise eligible public-production callers, readiness must also cover `JOIN -> PLAY -> first LOOK` after `PLAY` returns `JOIN_REQUIRED`; returning `JOIN_REQUIRED` alone is insufficient. Current Account runtime membership/entitlement/grant handlers reject before data reads, so neither composed path is currently established by local command support. - While unready, the proxy must reject new Telnet sessions immediately with an explicit startup/unavailable message and close the connection. It must not silently accept the socket and let the first gameplay command discover startup races later. - Loss of downstream readiness after a session is already established blocks new sessions but does not by itself imply that the proxy process is dead. - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency names `telnetListener` and `gatewayGameplayPath`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index b6e2269f1d..420ef18c3a 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,31 +6,31 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. +The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache. Its handler requests a fresh Account membership read, but Account's live runtime handler returns `FAILED_PRECONDITION` before reading data; Game Session maps that response to `WORLD_ACCESS_DENIED`, so the entitlement and realm-grant reads do not establish a composed live admission path. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. The target requires an independent issuance-time Account reread of `membershipVersion` and `membershipAuthorityGeneration`; the current baseline and replay-revalidation proof remains incomplete under [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for eligible public-production targets, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement/public policy permits joining. Existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` remains denied. Private/playtest targets perform the applicable current realm-grant check. The separate target connect-token grant-validation contract for private/playtest targets also remains unimplemented. The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. -The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). -The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but does not establish the target-required independent issuance-time reread of membership version and authority generation. Its baseline proof remains incomplete, and target private/playtest connect-token grant validation is a separate gap. Current text `PLAY` returns `JOIN_REQUIRED` for an otherwise eligible public-production target with missing or non-admitting `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; the target also requires explicit `JOIN` for `INACTIVE` membership before `PLAY`. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. Private/playtest targets never offer public `JOIN`: current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, and target admission requires existing `ACTIVE` membership plus the exact current realm grant. These local gaps do not change the Authentication-owned admission outcomes. -The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or `INACTIVE` eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining; existing `ACTIVE` membership with gameplay admission disabled remains denied. Direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. +The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). On connect-token replay-cache misses, issuance reads fresh Account authority; a cached `session:connect-token:*` success can bypass fresh entitlement, membership, and pointer rereads. That cache-hit bypass is implementation drift, not fail-closed admission proof. The target requires an independent issuance-time reread of `membershipVersion` and `membershipAuthorityGeneration`; baseline and replay-revalidation proof remains incomplete under [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Private/playtest connect-token grant validation is also incomplete. + +Text `PLAY` does not consult connect-token replay-cache state and requests fresh Account membership evidence (and the applicable grant for non-public targets). The live Account runtime handler currently returns `FAILED_PRECONDITION` before data access; Game Session maps that to `WORLD_ACCESS_DENIED`, so a live snapshot, subsequent entitlement/grant evaluation, or successful composed public `PLAY` is not established. Supplied-authority local branches classify otherwise-eligible public-production missing or `INACTIVE` membership as `JOIN_REQUIRED` after fresh entitlement and public-policy checks; active-but-non-admitting membership remains denied. Direct-text `JOIN` dispatch and the Account writer exist locally, but Gateway blocks first-party browser `Join & Play`; PostgreSQL/recovery and complete Telnet discovery/bridge proof remain open. + +Target direct-text flow is fresh `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/creation -> `PLAY` -> first `LOOK`. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. The target selector is a snapshot-bound ordinal or stable tenant-scoped slug pair; current local behavior supports bound ordinals and uniquely resolving bare world slugs, the latter being implementation drift. The pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` is unavailable. Direct-text/Telnet clients do not reuse first-party WebSocket discovery snapshots. `session_replaced`/`service_restart` preservation and bridge classification remain target-only. Current close recognition, fallback, and shutdown classification remain as recorded in [Operations Implementation Status](./operations.md#implementation-status). `LOGIN ` starts an email challenge; `LOGIN ` supplies the secret immediately. ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. In the current runtime, direct-text `JOIN` is implemented through the Account-owned writer, but hidden default routing is bootstrapped and `WORLDS` is not enforced as a prerequisite; complete Telnet discovery/bridge proof remains open. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped, and current `PLAY` does not create membership when it returns `JOIN_REQUIRED`. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. ## Recommended Telnet Client Flows -These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. Current text `PLAY` validates the lifecycle/version/generation membership evidence and evaluates fresh public entitlement/policy before returning `JOIN_REQUIRED` for an otherwise eligible missing or `INACTIVE` public-production membership; only an existing `ACTIVE` member skips `JOIN`. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. +These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. The `PLAY` handler's lifecycle/version/generation and entitlement classifications are conditional local branches; the live Account membership handler rejects before reading, and Game Session maps that to `WORLD_ACCESS_DENIED`. No live `JOIN_REQUIRED` or successful composed public `PLAY` is established through these handlers. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; current text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED` for missing or `INACTIVE` membership, after which direct text can invoke the implemented Account-backed writer. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. Full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. The live Account membership handler currently rejects before reading, so text reconnect maps that response to `WORLD_ACCESS_DENIED`; local unit classification for supplied missing or `INACTIVE` membership does not establish a live `JOIN_REQUIRED`. Target behavior returns `JOIN_REQUIRED` for missing or `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -43,7 +43,7 @@ These flows describe how Telnet traffic is forwarded into the shared login/sessi Advanced Telnet tools may open more than one window or pane for the same account. The proxy forwards traffic for every TCP connection independently; visible takeover behavior follows [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). - **Two Telnet windows** - - Window A connects, performs fresh `WORLDS` discovery, issues `LOGIN`, performs authenticated `REALMS` discovery, follows the target-only conditional `JOIN` step if it is first public-production entry, conditionally completes `CHARS`/character creation when no valid selected character exists, and enters gameplay with `PLAY`. + - Target Window A connects, performs fresh `WORLDS` discovery, issues `LOGIN`, performs authenticated `REALMS` discovery, follows the conditional `JOIN` step if it is first public-production entry, conditionally completes `CHARS`/character creation when no valid selected character exists, and enters gameplay with `PLAY`. Local JOIN dispatch exists; the complete discovery-first sequence remains target-only. - Window B connects and repeats `WORLDS`, `LOGIN`, and authenticated `REALMS` discovery for the same character, follows `JOIN` only if required by the Authentication flow, conditionally completes `CHARS`/character creation when no valid selected character exists, then issues `PLAY`. Game Session applies the canonical takeover and the old window is disconnected. - If Window A reconnects and logs in again, it in turn takes over from Window B. There is no concurrent split control even though the proxy forwards traffic from both TCP connections. @@ -103,14 +103,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`, but its local text flow supports `LOGIN` -> `PLAY` -> `LOOK` for existing admitting members or `LOGIN` -> `PLAY` (`JOIN_REQUIRED`) -> `JOIN` -> `PLAY` -> `LOOK` when joining is required. It validates Account membership lifecycle/version/generation evidence and, for an otherwise eligible public-production missing or `INACTIVE` membership, fresh entitlement/public policy before returning `JOIN_REQUIRED`; direct text can then invoke the implemented Account-backed writer. Current private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED` and checks the current realm grant; the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains unproved end to end; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Game Session's local `PLAY` branches classify supplied Account membership/lifecycle and entitlement responses, but the live Account membership handler rejects before reading and Game Session maps `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; the live path does not reach `JOIN_REQUIRED` or the later realm-grant check. Direct-text `JOIN` dispatch and the Account writer exist locally, but successful composed public `PLAY` and the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remain unproved; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; - any future adapter-carried attach hint must remain advisory and must not bypass the current conditional `JOIN` path described above or the target discovery-first sequence owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime supports the local Account-backed `JOIN` command and fresh public entitlement/policy gating in Game Session `PLAY`, but still bootstraps hidden default routing and does not enforce `WORLDS`; full target Telnet discovery/bridge and PostgreSQL/recovery proof remain open. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established because the live Account membership handler rejects before reading and Game Session maps that failure to `WORLD_ACCESS_DENIED`. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 81949a723a..62740bc084 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`. Target connect-token issuance requires an independent issuance-time Account reread that captures `membershipVersion` and `membershipAuthorityGeneration` from the same authoritative membership snapshot; this baseline requirement is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its internal non-public missing or non-admitting membership classification is `WORLD_ACCESS_DENIED`. Definitive denial for an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm within a publicly discoverable world; a non-discoverable world retains the generic selection-required response without target metadata. Visible public-production denial and unavailable authority retain their distinct outcomes. Current connect-token issuance retains its Account-owned rejection mapping; its separate private/playtest grant validation remains incomplete. Current issuance has not implemented or proved the required independent membership baseline reread or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` action exists locally, but the Gateway still blocks external `POST /auth/bootstrap/join`; first-party browser `Join & Play` is unexposed. Account runtime membership, entitlement, and grant gRPC handlers fail closed before data access until typed caller/target binding is available. Game Session `PLAY` validates exact identity, lifecycle, membership version, authority generation, admission, and evaluation time on supplied-authority branches. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, and only after fresh entitlement and `allowPublicJoin` checks; active-but-non-admitting membership receives no JOIN advice. Because live Account readers fail closed, these branches do not establish a composed live public `PLAY` or `JOIN_REQUIRED`. Current non-public text `PLAY` internally classifies denial as `WORLD_ACCESS_DENIED`. Definitive denial of an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm even within a publicly discoverable world; a non-discoverable world retains generic selection-required output without target metadata. Visible public-production denial and authority outages remain distinct; Account connect-token issuance retains its distinct rejection mapping and does not validate the applicable private/playtest grant. Account owns the independent issuance-time reread of membership version and authority generation; proof of this baseline, durable replay revalidation, and target connect-token grant validation remain incomplete. The Account JOIN worker uses versioned locked COMMITTED audit/receipt evidence for readback-only recovery: expired-scope retained `PENDING` intents remain retryable and only exact positive prior-commit evidence can terminalize; absent or uncertain evidence remains pending. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Canonical current and target outcomes remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. @@ -314,7 +314,7 @@ These modes are complementary: public browse remains available before authentica ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. -- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery; for a retained `PENDING` operation, an expired scope terminally returns `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. +- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched scope cannot authorize a new JOIN and requires fresh authenticated `REALMS` discovery. For an existing matching `PENDING` operation with an expired retained scope, an exact retry returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the intent remains `PENDING` for readback-only reconciliation of exact prior-commit evidence, including after automatic attempts are exhausted. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: @@ -731,7 +731,7 @@ First-party gameplay admission and reconnect clients should treat the following | `PLAY` | `STALE_TIMELINE` | The selected region, epoch, or lease fence no longer matches current runtime authority | Keep auth state, create no gameplay binding, rediscover the realm and runtime timeline, and retry admission explicitly; never accept an implicit rebind. | | Gameplay command before `PLAY` | `PLAY_REQUIRED` | Client issued a world-scoped gameplay command before lobby admission completed | Keep auth state and route the client back through `PLAY`, `REALMS`, or `CHARS` as appropriate. | -Reconnect sequencing, snapshot reuse, transport-local scope replacement, and resume/takeover behavior are owned by [Reconnection Strategy](./system-architecture-reconnection.md) and [Session Behavior](./system-architecture-session-behavior.md). Authentication's target-state consequence is that each reconnect re-establishes the exact transport authentication path and then uses fresh routing plus one fresh Account membership snapshot before admission; stale selectors, expired scopes, partial membership evidence, and client-supplied authority never authorize fallback. Current runtime deviations from the target flow are recorded in [Implementation Status](#implementation-status), including the unavailable explicit `JOIN` operation. +Reconnect sequencing, snapshot reuse, transport-local scope replacement, and resume/takeover behavior are owned by [Reconnection Strategy](./system-architecture-reconnection.md) and [Session Behavior](./system-architecture-session-behavior.md). Authentication's target-state consequence is that each reconnect re-establishes the exact transport authentication path and then uses fresh routing plus one fresh Account membership snapshot before admission; stale selectors, expired scopes, partial membership evidence, and client-supplied authority never authorize fallback. Current runtime deviations from the target flow are recorded in [Implementation Status](#implementation-status), including incomplete membership lifecycle/generation reread and end-to-end proof for the local explicit `JOIN` operation. Logical character identity is the canonical `characterId` resolved under the caller's tenant and selected playable-state namespace; it is distinct from active gameplay-binding uniqueness. All Redis key formats and Game Session Service APIs must treat `characterId` as the abstract character identifier so sessions bind sockets to characters rather than raw accounts. Canonical target takeover and resume uniqueness is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; its binding value/evidence retains server-derived `playableStateScope`, `{sessionId, gameInstanceId, bindingGeneration}`, with `gameInstanceId` as the active-runtime fence. The existing `{tenantId, gameInstanceId, characterId}` identity is current implementation drift. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 396577b76c..cf5ba1d51e 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,8 +25,8 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` validates fresh Account membership identity, lifecycle, version, authority generation, and evaluation time. Missing or `INACTIVE` public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` but non-admitting member is denied without JOIN advice because Account's explicit JOIN writer cannot repair that state. Policy denial and unavailable/invalid authority remain distinct outcomes. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party `Join & Play`, durable unknown-outcome recovery, and end-to-end proof remain incomplete. -- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy declared for these methods in the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Account runtime membership, entitlement, and grant handlers fail closed before data access because their requests lack typed caller/target binding; this status does not claim successful live public `PLAY`. Game Session `PLAY` validates lifecycle, authority generation, membership version, and evaluation time on supplied-authority branches. Eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Policy denial, invalid evidence, and unavailable authority remain distinct. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party browser `Join & Play` remains blocked at Gateway. Versioned locked COMMITTED audit/receipt readback is the only recovery path for uncertain JOIN outcomes; retained expired-scope `PENDING` intents remain retryable absent exact positive prior-commit evidence. PostgreSQL execution/concurrency, direct text-to-Logging end-to-end proof, and Account's independent issuance-time membership-version/authority-generation reread proof remain open. +- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact caller policies assigned to each method in the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration no longer lists these methods as public gRPC bypasses. Their handlers deny before data access, including for the exact Game Session peer, until the typed caller/target contract is implemented. Missing-token, wrong-workload, and cross-tenant denial proof establish containment, not a working admission path or target snapshot. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. @@ -215,7 +215,7 @@ For every first public-production text entry, the target command sequence is `LO | Game Session Service | `WORLDS` anonymous browse | `public` | Public-production catalog only; no account-specific membership, grant, or character information | | Game Session Service | `WORLDS` authenticated discovery | `pre_tenant_discovery` | No pre-existing tenant role is required. Tenant visibility is derived server-side from membership or public-production visibility plus entitlement state; global roles do not widen gameplay discovery | | Game Session Service | `REALMS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive branch from the authoritative realm mode: public production permits pre-membership discovery; private/playtest requires caller-bound `membershipLifecycleState=ACTIVE`, current membership authority generation/version, and the current Account-owned grant for the exact target. Private/playtest is never classified as public onboarding, never falls back to public discovery, and never uses a grant to repair membership. Hidden/unauthorized targets are omitted; explicit branch failures use `NON_PUBLIC_ENROLLMENT_REQUIRED`, `REALM_ACCESS_DENIED`, `WORLD_ACCESS_DENIED`, `ADMISSION_POINTER_UNAVAILABLE`, `REALM_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE`, or `AUTH_UNAVAILABLE` as applicable. | -| Game Session Service | `JOIN` | `public_production_onboarding` | **Implemented locally; proof incomplete.** Game Session retains the Account-issued scope and submits explicit JOIN to Account, which commits caller-bound membership plus audit/outbox evidence locally. Membership-generation, unknown-outcome recovery/reconciliation, receipt/retention, PostgreSQL runtime, and direct-text end-to-end proof remain open; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | +| Game Session Service | `JOIN` | `public_production_onboarding` | **Implemented locally; runtime/deployment proof incomplete.** Game Session retains the Account-issued scope and submits explicit caller-bound JOIN to Account, which commits membership plus audit/outbox idempotently. Account's bounded readback worker can terminalize only positively proved prior commits; exact unknown-outcome PostgreSQL, membership-generation consumer, audit receipt/retention, and direct-text/first-party end-to-end proof remain open. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). | | Game Session Service | `CHARS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Public discovery may lead to `JOIN_REQUIRED` for missing or `INACTIVE` membership; private/playtest requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. It applies the current `admission_pointer` check to the selected catalog realm, but does not apply `PLAY`'s exact-binding admission lease, binding fence, or binding-ownership gate; character discovery and creation do not require a selected character. Policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and unavailable or invalid authority uses the applicable unavailable/invalid-authority outcome. Missing or non-`ACTIVE` private/playtest membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, and character discovery is not membership repair. | | Game Session Service | `PLAY` | `gameplay_admission` | **Target:** requires an existing caller-bound membership plus any non-public realm grant, current entitlements, and the current admissible realm pointer; `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when the selected target is confirmed as public production and its joining policy denies entry, and only an admissible, publicly visible public-production target whose joining policy permits entry and whose membership is missing or `INACTIVE` returns `JOIN_REQUIRED`; `ACTIVE` membership does not require `JOIN`, and `PLAY` never creates or restores membership. `PLAY` alone performs the final gameplay-binding CAS. First-party `/ws/game/**` also enforces connect-context scope. Unavailable, ambiguous, stale, or otherwise invalid routing returns `ADMISSION_POINTER_UNAVAILABLE`; a deliberately closed realm returns `REALM_UNAVAILABLE`; entitlement authority outage returns `ENTITLEMENT_UNAVAILABLE`. | | Spring Cloud Gateway | `/ws/game/**` (connect-token bootstrap) | `gameplay_admission` | **Implemented but non-promotable until the named Gateway readiness evidence is complete:** carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. This is one canonical WebSocket entry point with mutually exclusive variants. The current `first_party_web` variant accepts exactly the protected cookie for first-party protected-cookie clients, including native or other nonbrowser clients using a cookie jar. The live `GameplayHandshakeFilter` rejects `X-Firemud-Connect-Token` on this public route with `CONNECT_TOKEN_REJECTED` and reason `unsupported_carrier_or_route`, without falling back to the cookie. A future explicitly classified `non_first_party_public` variant may use the header only after its dedicated matrix entry and issuance, replay, signed-context, response, and carrier proof exist; it cannot select or fall back to `first_party_web`. Gateway consumes exactly one supported carrier, strips it, atomically enforces single use using the dedicated replay record/fence, matches the signed connect scope to the request, and emits the signed connect context for Game Session. Non-`101` outcomes use the bounded `CONNECT_TOKEN_MISSING`, `CONNECT_TOKEN_EXPIRED`, `CONNECT_TOKEN_REPLAYED`, `CONNECT_SCOPE_MISMATCH`, `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, `CONNECT_TOKEN_REJECTED`, `POLICY_DENY`, `POLICY_PRESSURE`, `BACKEND_UNAVAILABLE`, `PROTOCOL_MISMATCH`, or `INTERNAL_ERROR` handshake classes. | @@ -225,7 +225,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; applies live realm visibility and runtime entitlement checks, with private/playtest additionally requiring caller-bound `ACTIVE` membership and the applicable Account-owned realm-access grant. Private/playtest is not public onboarding. | | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; this existing-character discovery operation declares `selected_character_requirement: none`, and its target binding and `connect_scope_match` check require the opaque server-issued `connectScopeId` to match the selected route target, alongside live membership, applicable realm-grant, entitlement, and admission-pointer checks. It creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | | Account Service | `POST /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | **Target; not currently routable or implemented.** Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Bootstrap-authenticated Account facade derives `accountId` from the authenticated caller subject, declares `selected_character_requirement: none`, and requires its target binding plus `connect_scope_match` check to match the opaque server-issued discovery `connectScopeId`; existing caller-bound membership, applicable realm visibility/grant, runtime entitlement, and admission-pointer checks precede the retained target delegation to internal Entity Management `CreateCharacter`. Character creation creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | -| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; `target_not_currently_routable` as public ingress.** The explicit Gateway route guard blocks exposure, and the route is absent from publicOpenAPI. Accepts only caller-bound `player-bootstrap`, derives `accountId` from the authenticated subject, and requires the exact opaque server-issued discovery `connectScopeId` to match the selected public-production target. The local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [ADR 0025](./decisions/adr-0025-explicit-open-enrollment-membership.md). | +| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; `target_not_currently_routable` as public ingress.** The explicit Gateway route guard blocks exposure and the route is absent from `publicOpenAPI`. Accepts only caller-bound `player-bootstrap`, derives `accountId` from the authenticated subject, and requires the exact opaque server-issued discovery `connectScopeId` to match the selected public-production target. The local transaction commits membership, operation outcome, and tenant audit outbox together, but policy-digest revalidation does not prove that the exact target remains valid through Account commit; strict through-commit target-validity proof remains incomplete under [ADR 0025's Membership Transaction](./decisions/adr-0025-explicit-open-enrollment-membership.md#membership-transaction). PostgreSQL lost-acknowledgement/concurrency, pending-operation readback, and direct-client proof remain open. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). | | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | @@ -245,7 +245,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `IssueHumanOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus a forwarded `control-ui` token with its exact active Account issued-token registry record; Account rereads current account/token generation, operator roles, role-appropriate assurance, the applicable tenant or target-tenant generation, and required `privileged_control` predicate before issuing the bounded reference | | Account Service | `IssueAutomationOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus current versioned automation policy; no end-user JWT or user impersonation. The current branch is tenant-scoped only, binds the exact current tenant generation, and rejects global-role or `privileged_control` action families | | Account Service | `IssueDirectTextConnectScope` | `internal_workload` | **Implemented locally; end-to-end proof incomplete.** Exact Game Session mTLS and typed caller/target context are required; Account rereads the public-production target and current gameplay entitlement before retaining an opaque short-lived scope. The scope is not caller authority or a JOIN policy decision; see [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) | -| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; proof incomplete.** Account's explicit writer is the sole membership mutation path; the canonical contract and current transaction consequences are defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). Target-only membership-generation snapshot proof, unknown-outcome recovery/reconciliation, audit receipt/retention proof, PostgreSQL runtime proof, and direct-text end-to-end proof remain open. The obsolete implicit membership writer is removed. | +| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; runtime/deployment proof incomplete.** The exact Game Session mTLS workload supplies typed caller-bound player context and `verified_connectScopeId_exact_target`, never an end-user token. Account revalidates `connectScopeId`, `catalogRevision`, `pointerVersion`, and the resolved target before commit, without silent retargeting. Its bounded readback worker can terminalize a retained `PENDING` operation only from exact positive operation, scope, membership, and audit evidence. Membership-generation snapshot/consumer, unknown-outcome PostgreSQL, audit receipt/retention, and direct-text end-to-end proof remain open; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). | | Account Service | `DELETE /tenants/{tenantId}/memberships/me` | `caller_membership_scoped` | Caller-bound membership exit remains available while billing-blocked to any current member role, requires live subject-bound membership, and advances membership authority atomically | | Account Service | `AuthLogout` / `AuthLogoutAll` | `account_scoped` | Accepts `control-ui` (`audience: control-ui`) or `player-bootstrap` (`audience: player-bootstrap`) with registry-backed authenticated account scope. Bounded retries may return no-op success only from a durable committed exact-token tombstone (`AuthLogout`) or durable proof that a prior logout-all superseded the token (`AuthLogoutAll`); registry absence alone is insufficient and the retry exception grants no reusable authorization context | | Account Service | `GET /accounts/{accountId}/deletion` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=deletion_status`; the Account-issued credential is bound to the account and deletion workflow and returns deletion status only | @@ -255,8 +255,8 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /accounts/{accountId}/exports/{exportId}/content` | State-dependent `account_scoped`, `security_lock_export_scoped`, or `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=export_content`; the active branch explicitly requires `applicability.account_state=active` and authoritative `account_state_export_eligible` evidence. The same branch must exact-match the completed operation before downloading its artifact. A cross-account or nonexistent `exportId` is non-disclosing and returns `PERMISSION_DENIED`. Active-account access requires `required_account_export_job_and_outcome`; security-lock access uses the same bounded expiring credential for the export operation after initiation and requires `required_account_recovery_case_export_job_and_outcome`; pending-deletion access remains a separate workflow credential and requires `required_account_deletion_workflow_export_job_and_outcome`. | | Account Service | `POST /accounts/{accountId}/deletion/billing-settlement` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=billing_settlement`; restricted to necessary billing settlement and cannot authorize export or normal billing mutations | | Account Service | `GET/PUT /tenants/{tenantId}/profiles/{accountId}` | `tenant_regular` | Canonical tenant-qualified self-service profile routes require path `accountId` to equal the authenticated caller for every scoped role, including `tenantAdmin`. Membership freshness and scoped-role checks consume the Account owner contract; no administrative or `platformAdmin` cross-account override exists, and legacy `/profiles/{accountId}` is implementation drift only | -| Account Service | `DeleteAccount` (`DELETE /accounts/{accountId}`) | `account_scoped` | Subject-bound to caller `accountId`; `platformAdmin` override only. The route additionally requires billing-deletion clearance for nonterminal subscription, transfer, provider, webhook, outbox, cancellation, customer, and reconciliation work. | -| Account Service | `ExportAccount` (`GET /accounts/{accountId}/export`) | `account_scoped` | **Status: `current_openapi_operator_surface`; current synchronous legacy implementation; not a second target operation.** Its target RPC semantics are protocol-equivalent to the sole canonical `POST /accounts/{accountId}/exports` route. The current Account/profile-local response and legacy `platformAdmin` override are known drift; the target canonical path is caller-subject-only. | +| 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 | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 62c15968da..e585bb6981 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -400,7 +400,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_and_current_PLAY_consumer_validates_membershipLifecycleState_membershipAuthorityGeneration_membershipVersion_and_evaluatedAt; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_INACTIVE_public_production_membership_only_after_fresh_entitlement_and_allowPublicJoin_checks; ACTIVE_non_admitting_membership_is_denied_without_JOIN_advice; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_entitlement_and_grant_handlers_fail_closed_with_FAILED_PRECONDITION_before_reads_until_typed_caller_target_binding_exists; Game_Session_PLAY_validates_supplied_membershipLifecycleState_membershipAuthorityGeneration_membershipVersion_and_evaluatedAt_and_classifies_missing_or_INACTIVE_eligible_public_membership_as_JOIN_REQUIRED_and_ACTIVE_non_admitting_membership_as_denied_without_JOIN_advice; live_composed_membership_reads_and_successful_public_PLAY_are_not_established; live_membership_failure_maps_to_WORLD_ACCESS_DENIED; connect_token_local_missing_or_INACTIVE_public_membership_branches_require_fresh_positive_entitlement_and_allowPublicJoin_while_live_reads_remain_unavailable; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_and_membership_version_issuance_rereads_remain_unproved; PostgreSQL_execution_and_bounded_pending_operation_readback_proof_remain_incomplete - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support @@ -1185,9 +1185,9 @@ routes: implementation_status: known_drift: - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only - - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - bounded_Account_readback_reconciler_is_implemented_locally_but_PostgreSQL_runtime_unknown_outcome_and_concurrency_proof_remain_unavailable - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only - - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable + - direct_text_to_Logging_end_to_end_proof_unavailable - service: game-session-service route: PLAY scope: tenant @@ -2014,9 +2014,10 @@ routes: implementation_status: known_drift: - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only - - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - bounded_readback_reconciler_has_no_executed_postgresql_unknown_outcome_or_concurrency_proof - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only - - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable + - direct_text_and_first_party_end_to_end_runtime_deployment_proof_unavailable + - connect_token_issuance_baseline_proof_incomplete - service: account-service route: DELETE /tenants/{tenantId}/memberships/me scope: tenant diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1e6c8c7718..029da17661 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -22,7 +22,7 @@ The current Vite build emits the `web-client` artifact and its reserved `fronten The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and Account `POST /auth/logout` and `/auth/logout-all` are target-only and unavailable. The current logout fallback clears local reconnect state and relies on bounded credential expiry; it does not establish Account revocation or generation advancement, Gateway revocation or an edge deny/replay fence, Game Session binding termination, or downstream reconciliation. Edge replay/deny enforcement is claimed only when the Gateway revoke path is implemented and reachable. -Direct-text `JOIN` is implemented locally; first-party `Join & Play` remains unavailable until its route, post-join snapshot, and token-issuance proof are complete. Current text `PLAY` requires a fresh admitting `ACTIVE` membership, while eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` after fresh entitlement and public-policy checks. Target `JOIN` creates missing or restores `INACTIVE` membership; `PLAY`, character creation, and connect-token issuance never do so implicitly. Returning members and private/playtest callers still require their applicable current membership, grant, entitlement, and routing checks. Complete browser/Telnet flow, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This concise frontend status follows [Authentication & Authorization](./system-architecture-authentication.md#implementation-status), which owns the current and target contract. +Detailed current capability and proof status for player access, admission, and reconnect flows is tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). Direct-text `JOIN` dispatch and the Account writer exist locally, but Gateway blocks first-party `POST /auth/bootstrap/join`; Account runtime readers fail closed before data access. Supplied-authority `PLAY` branches classify eligible public-production missing or `INACTIVE` membership as `JOIN_REQUIRED` after fresh entitlement and public-policy checks, while active-but-non-admitting membership is denied. These local branches do not prove a live Account snapshot, successful public `PLAY`, or browser JOIN. Connect-token replay revalidation and its independent membership-version/authority-generation baseline remain unproved; private/playtest grant validation is also incomplete. Complete browser/Telnet flow, PostgreSQL/recovery, and first-party route/token proof remain open. The protected-cookie handshake, logout, and related requirements remain normative targets rather than end-to-end proof; logout currently relies on bounded credential expiry and does not establish Account/Gateway revocation, generation advancement, binding termination, or downstream reconciliation. This status follows [Authentication & Authorization](./system-architecture-authentication.md#implementation-status), the canonical owner. ### Persisted actor entry UX boundary (PLAYER-01) @@ -41,7 +41,7 @@ The frontend keeps the target `PLAY` gate separate from the target `Join & Play` - **`PLAY` gate:** enable only after fresh selected-target routing/pointer evidence, entitlement, caller-bound `membershipLifecycleState=ACTIVE`, any required realm grant, and a valid current character all pass. `PLAY` never creates or restores membership. - **`Join & Play` gate:** enable only for the selected public-production realm when the fresh public-joining policy is `allowPublicJoin=true` and caller-bound membership is missing or `INACTIVE`; it invokes the explicit Account join route and waits for the post-join snapshot before character discovery, creation, connect-token issuance, or `PLAY`. -These are target-only frontend gates. The current frontend has no complete first-party `Join & Play` route; it must not expose that browser action until the explicit endpoint and issuance reread are implemented and proved. Direct-text `JOIN` is a separate implemented Game Session/Account path. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. +These are target-only gates. The current frontend must keep missing or non-admitting membership unavailable and must not expose an actionable Join route until the required issuance reread and complete runtime/deployment proof are available. The local explicit join endpoint and Account writer now exist, but their presence does not clear this UI readiness gate. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. ## Implementation Notes @@ -98,7 +98,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - Target first-party clients use one of two explicit gameplay flows: - **Returning member:** `POST /auth/player-bootstrap` -> bootstrap discovery -> bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with the discovery-provided `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This flow requires the selected existing caller-bound membership and does not call `/auth/bootstrap/join`. - **First join:** `POST /auth/player-bootstrap` -> public-production discovery -> `POST /auth/bootstrap/join` -> rerun public-production realm discovery -> use the new complete `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` snapshot for bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with that new snapshot's `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This public-production, non-grant snapshot intentionally omits both `playtestLifecycleId` and `playtestStateGeneration`; private/playtest snapshots include both fields. `/auth/bootstrap/join` may create missing membership or restore `INACTIVE` membership and must commit it against the exact `{catalogRevision, pointerVersion}` pair before the post-join discovery, character discovery, character creation, or connect-token issuance; no later step may create membership implicitly. The join transition emits one audit/outbox event for create or restore; an `ACTIVE` retry is event-free. - - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed complete current supported behavior. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` requires fresh lifecycle/version/generation evidence and, for eligible public-production missing or `INACTIVE` membership, fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`. Existing `ACTIVE` membership with gameplay admission disabled remains denied. Current returning-member behavior may proceed when the existing live membership/character checks pass, but the target exact issuance baseline/generation/version reread and durable replay revalidation remain unproved. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. Complete first-party browser, Telnet, PostgreSQL/recovery, and downstream proof remain open. The target descriptions remain the behavior to implement. + - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not proof of complete current support. Direct-text `JOIN` exists locally; first-party browser `Join & Play` remains unavailable because Gateway denies its target-only route. Account runtime readers fail closed before data access, so Game Session supplied-authority `PLAY` branches do not establish live admission: only eligible public-production missing or `INACTIVE` membership can classify as `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks, while `ACTIVE` but non-admitting membership remains denied. The separate Account connect-token path has its own rejection mapping; the independent issuance baseline/generation/version reread and durable replay revalidation remain unproved. Complete browser/Telnet end-to-end, PostgreSQL/recovery, and downstream proof remain open. The target descriptions remain the behavior to implement. - For every `POST /auth/connect-token` issuance, including the first issuance immediately after explicit join and both returning-member and grant-backed private/playtest flows, the service must independently validate the scalar `membershipVersion` returned by `GetTenantMembershipForRuntime` for the selected `{accountId, tenantId}` and the `membershipAuthorityGeneration` from that same authoritative membership snapshot. It must compare both values independently with the selected admission baseline, bind the scalar `membershipVersion` and generation into the connect-token issuance/binding evidence, and fail closed when either value is missing, stale, mismatched, unavailable, or assembled from another snapshot; a current grant never substitutes for the membership-version validation. - Browser and mobile-browser clients receive the short-lived `Firemud-Connect-Token` HttpOnly cookie used by the `/ws/game/**` handshake; first-party native-mobile clients using a cookie jar remain cookie-only. This protected-cookie path is the current supported path to bare `LOGIN`. Explicitly classified non-first-party/public non-browser clients are target-only and unavailable until their dedicated issuance route is fully registered and proven; the conditional target carrier is protected secure storage plus `X-Firemud-Connect-Token`, not a fallback for the current cookie path. The client then opens `/ws/game/**` and completes gameplay authentication by issuing `LOGIN` over the WebSocket channel using the already-verified bootstrap/connect context; Game Session must validate the complete context, including the direct `realmId`, before using any field for `LOGIN`, `PLAY`, or scope comparison. The browser never prompts for or replays Telnet-style `LOGIN [secret]` credentials, as described in [Authentication & Authorization](./system-architecture-authentication.md#login-and-session-flow). - Browser transport constraints matter: a browser WebSocket cannot set arbitrary custom handshake headers the way Telnet smart clients, Mudlet integrations, or server-side clients can. The first-party browser flow therefore uses the `Firemud-Connect-Token` cookie set by `POST /auth/connect-token` with `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/ws/game`, and `Max-Age` no longer than the connect-token TTL. The React client must not read or persist the connect token itself; it only consumes non-secret response metadata such as `expiresAt`, `tenantId`, `realmId`, `realmSlug`, and `gameInstanceId`. Query parameters must never carry connect tokens or other authentication credentials; non-secret bootstrap discovery selectors such as `connectScopeId` may be sent as query parameters. Clients must obtain a fresh token after any failed attempt that may have consumed it. After Account has durably committed an issuance result or Gateway has consumed its token, any new token issuance requires a new `requestId`; the old `requestId` may only reconcile that same request while its outcome is `PENDING` or otherwise indeterminate and never mints a replacement token. @@ -108,10 +108,10 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - The target canonical player logout order is: stop reconnect attempts, capture the current `player-bootstrap` token into the pending-revocation slot, ask Account to durably commit the exact-token `PENDING` intent and immediately advance the exact-token issuance fence to `PENDING_LOGOUT` in that same durable step, then send gameplay `LOGOUT` and close the gameplay socket, ask Gateway to deny the gameplay-connect `jti` and clear the HttpOnly cookie, and finally ask Account to invalidate the underlying token and commit the `COMMITTED` tombstone. Account must establish the durable issuance fence before socket closure or any racing `/auth/connect-token` issuance can succeed; every issuance path rejects the fenced lineage rather than returning a usable late credential. Once `PENDING` is durable, Account must reject racing issuance, refresh, rebind, installation, and every unrelated reconciliation for that token lineage; only the exact matching Account lifecycle reconciliation may complete or abort that pending logout operation. `PENDING` is never success and remains resumable through that exact Account operation until terminal completion. If Gateway revoke is unavailable, Account must not report the edge deny/clear outcome as confirmed; clear only local reconnect/client state and rely on the bounded token lifetime; Gateway mitigation must not be reported as full logout when Account is unavailable or its fence is unconfirmed. The browser never directly clears the HttpOnly gameplay cookie; only a server response can clear that cookie. The target Gateway revoke call uses a two-second per-attempt timeout, at most two retries, and 250 ms then 500 ms backoff where time remains, but every request timeout and backoff is capped by the remaining five-second total deadline. This Gateway controller budget is independent and non-nested: it is not shared with or added to Account's revocation budget. Account revocation retains its separate policy of at most five attempts, a five-second timeout per attempt capped by a 30-second overall deadline, and full-jitter exponential backoff starting at 250 ms and capped at four seconds. The controller tracks Account PENDING, Gateway denial/clearing, and Account COMMITTED finalization as separate outcomes. It enters terminal `LOGGED_OUT_REVOKED` only after Account confirms the exact-token fence/Bootstrap-token revocation and Gateway confirms denial/clearing of the gameplay-connect token. Because Gateway gameplay-connect denial and cookie clearing are not currently routable, the current runtime cannot reach `LOGGED_OUT_REVOKED`; current logout flows terminate as `LOGGED_OUT_REVOCATION_UNCONFIRMED`. Account-only confirmation remains `LOGGED_OUT_REVOCATION_UNCONFIRMED` with edge revocation explicitly unconfirmed until Gateway confirms or the known gameplay-connect acceptance window ends; expiry closes that bounded edge risk but is reported as token-window expiry, not confirmed server revocation. Retry exhaustion, an unconfirmed Account result, or bootstrap-token expiry likewise remains `LOGGED_OUT_REVOCATION_UNCONFIRMED`, stays locally logged out, and requires a fresh `POST /auth/player-bootstrap` before any later gameplay flow. The frontend may retry only while the captured credential remains valid and its local retry deadline remains open. At the earlier of signed token expiry or that deadline, it wipes the raw credential and stops frontend retries while retaining only the opaque server-side logout handle and non-secret operation state needed to observe Account's durable reconciliation. Browser or process loss likewise destroys the memory-only credential and ends frontend retries, but neither local expiry nor frontend loss cancels the durable Account `PENDING` operation: Account's persisted operation and opaque logout handle are the authoritative revocation proof, and Account's reconciler continues exact-token revocation without the raw token. A raw credential may never be reused for gameplay/bootstrap calls, and retaining it in memory never extends its signed lifetime. Local clearing or process termination is not confirmed server revocation. - Logout invalidates the local bootstrap/connect-token request epoch and aborts every in-flight bootstrap, discovery, join, character, and connect-token request owned by that epoch. A late response is ignored for all client state transitions, but abort and epoch invalidation cannot guarantee that a late `Set-Cookie` was not already committed by the browser. The server-side logout issuance fence is therefore authoritative: Account rejects bootstrap or connect-token issuance that races a durable `PENDING` or `COMMITTED` logout for the same account/token lineage, and Gateway rejects a connect token whose deny/revocation fence wins before consumption. Where a logout response reaches the browser after the old issuance, the server must also return an explicit clearing or deny response so the late cookie cannot remain usable. The client must never treat ignored local state or local cookie clearing alone as proof of server revocation. - A server must reject an expired `Firemud-Connect-Token` cookie as `CONNECT_TOKEN_EXPIRED`, never fall back to a stale cookie, query parameter, or unapproved header, and return a clearing `Set-Cookie` response where the HTTP surface can do so. The browser cannot inspect the HttpOnly value; it discards the failed handshake attempt and obtains a fresh connect token only from a still-valid bootstrap session. If the bootstrap token is expired or revoked, the client restarts `POST /auth/player-bootstrap` and discovery instead of treating the expired cookie as a recoverable gameplay credential. - - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Direct-text `JOIN` is already implemented locally through the same Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` validates lifecycle/version/generation evidence and, for eligible public-production missing or non-admitting membership, requires fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`; current connect-token issuance receives the same membership fields but still has replay-cache and issuance-baseline proof gaps. The frontend must not advertise the unavailable first-party browser repair path or treat stale token authority as a fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. + - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and target bootstrap actions, but does not itself carry gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, first-party `Join & Play` may create missing or restore `INACTIVE` Account-owned membership before character creation and connect-token issuance; connect-token issuance never creates membership implicitly. Direct-text `JOIN` is implemented locally, while first-party browser `JOIN` remains unavailable because Gateway denies its target-only route. Account runtime membership/entitlement/grant reads deny before data access until typed caller/target binding is available. Game Session `PLAY` retains lifecycle/generation/version validation; `JOIN_REQUIRED` is limited to confirmed eligible public-production missing or `INACTIVE` membership after fresh entitlement and policy checks, and an `ACTIVE` but non-admitting membership is denied without JOIN advice. No successful public `PLAY` or browser `JOIN` availability is established. The independent membership-version/authority-generation issuance reread, replay-cache revalidation, runtime/deployment, PostgreSQL, and end-to-end proof remain open. The selected target must come from canonical discovery and may be public production or an explicitly authorized alternate realm such as a playtest fork. - Gameplay admission has three separate applicability modes. For public-production onboarding, discovery may precede membership, but only explicit `JOIN`/`Join & Play` creates missing membership or restores `INACTIVE` membership; `gameplay-connect`, trusted TCP Proxy admission, and `PLAY` are applicable only after that commit. For returning membership, those transports and `PLAY` require the existing caller-bound membership and current authority checks and do not perform onboarding. For a grant-backed private or playtest realm, missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`; those targets require the applicable grant and the existing caller-bound `ACTIVE` membership plus its current membership authority generation, never use public `JOIN`, and never create membership or treat the grant as a substitute for membership. The trusted TCP Proxy is only a transport trust path and does not replace the mode-specific downstream checks; a `gameplay-connect` token and `PLAY` command likewise do not establish membership or grant eligibility. - The client must treat `connectScopeId` as an opaque short-lived selector, not as a stable saved identifier. For non-grant public production, the discovery snapshot bundle is `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`; private/playtest snapshots contain the same fields plus the applicable `playtestLifecycleId` and `playtestStateGeneration`. If reconnect or retry reports `CONNECT_SCOPE_MISMATCH`, it must discard the entire bundle and all derived connect-token metadata, rerun bootstrap discovery, complete target-only `Join & Play` and required character discovery/creation when applicable, and obtain a new selector and connect token rather than reusing any old bundle field or guessing a replacement target from cached `tenantId` or `realmSlug`. `ADMISSION_POINTER_UNAVAILABLE` likewise requires fresh discovery before retry rather than substitution from cached target fields. - - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` validates lifecycle/version/generation and evaluates fresh public entitlement/policy before returning `JOIN_REQUIRED` for an otherwise eligible missing or `INACTIVE` public-production membership. Current returning-member success therefore reflects the live existing-membership path, not proof of the target issuance baseline/generation reread or replay revalidation. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. + - Returning players with an existing Account-owned membership use browser bootstrap, discovery, and `POST /auth/connect-token` in the target before `PLAY`; the target skips membership creation only after a fresh check confirms `ACTIVE` membership and exact authority/version evidence. A valid current character is also required before connect-token issuance or direct `PLAY`; otherwise, realm-scoped character discovery or creation follows. Target behavior requires a missing or `INACTIVE` membership to take the explicit `Join & Play` path and forbids connect-token issuance or `PLAY` from creating/restoring membership implicitly. Current Account runtime reads deny before data access until typed caller/target binding is available, so this documentation does not claim successful returning-member `PLAY`. Game Session retains lifecycle/generation/version checks; the independent issuance-time membership-version/authority-generation reread, replay-cache revalidation, PostgreSQL/recovery, and end-to-end proof remain open. The resulting membership powers subsequent “my games” and return flows only after those current authority checks pass. - After connectivity loss while the in-memory `player-bootstrap` token survives, the client may request a fresh connect token, reconnect the WebSocket, then replay `LOGIN` and `PLAY` without prompting for credentials again only when the complete discovery snapshot is present and unexpired, and a fresh authoritative read confirms `membershipLifecycleState=ACTIVE`, the exact current `membershipAuthorityGeneration`, the independently current `membershipVersion`, and a valid current character for the selected target. A full page reload loses that memory-only token and must restart at `POST /auth/player-bootstrap`, then rerun discovery before requesting a connect token; the architecture defines no hidden refresh credential. `WORLDS`, `REALMS `, and `CHARS [realm]` remain optional discovery helpers only while the complete snapshot remains unexpired and those current membership, generation, version, and character checks pass; otherwise the client must rerun the full discovery/join/character path. Shared state restores session context only. Game Session must revalidate continuation authorization, the active binding and its fence, revocation state, and the current server-resolved target authority before resuming; Redis key presence or fresh backend-token rebinding is not authorization. First-party reconnects must not prompt the browser to replay Telnet-style `LOGIN [secret]` credentials after bootstrap has been re-established. - **Admin and creator UIs** @@ -127,14 +127,14 @@ All new frontend features that interact with protected APIs should reuse the sha - `AUTH_TOKEN_EXPIRED` – Clear in-memory auth state, redirect to login, and show a “Session expired” message. - `AUTH_SESSION_REVOKED` – Clear in-memory auth state, redirect to login, and show a security-focused message (for example, “You were signed out because your account security changed.”). - - `JOIN_REQUIRED` – Preserve in-memory authentication when fresh routing, authority, entitlement, and public policy permit an otherwise eligible public-production request but membership is `MISSING` or non-admitting `INACTIVE`; keep character discovery/creation, connect-token issuance, and `PLAY` blocked until the direct-text or first-party owner flow completes. The frontend must not expose the unavailable first-party browser `Join & Play` action, but the implemented direct-text `JOIN` path is distinct and may be used by text clients. Do not retry admission automatically or create membership implicitly. Private/playtest text `PLAY` currently returns `WORLD_ACCESS_DENIED` for missing or non-admitting membership, while the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Target `PLAY` behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED`, remains separately gated by the current grant, and never uses public `JOIN` as a fallback; keep the current endpoint outcomes distinct in the UI. + - `JOIN_REQUIRED` – In target behavior, this is the next step only after fresh routing, entitlement, and public policy checks confirm otherwise eligible public-production membership is missing or `INACTIVE`; an `ACTIVE` but non-admitting membership is denied without JOIN advice. The current Account runtime reads deny before data access, and Gateway keeps first-party `POST /auth/bootstrap/join` denied and target-only, so the frontend must not present this as an available browser repair or claim successful public `PLAY`. Keep character discovery/creation, connect-token issuance, and `PLAY` blocked unless current authority checks pass; do not retry automatically or create membership implicitly. Direct-text `JOIN` is implemented locally, but end-to-end proof remains open. Private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; Account connect-token issuance retains its distinct rejection mapping. Target private/playtest admission remains gated by the current grant and never uses public `JOIN` as a fallback. - `AUTH_UNAVAILABLE` – Keep in-memory auth state and show a retriable authentication-service availability message for ordinary API calls when authority availability is `UNAVAILABLE` for live membership, registry, or another required non-routing, non-entitlement authority. Reachable invalid pointer evidence uses `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out pointer authority uses `AUTH_UNAVAILABLE`; entitlement authority outage uses `ENTITLEMENT_UNAVAILABLE`. None may be relabeled as a billing block. An unavailable authority is not equivalent to missing or non-admitting membership and must not produce `JOIN_REQUIRED`. Block only the affected authority-dependent or billing-unsafe mutation, including gameplay-admission mutations, until authority recovers; billing-safe operations that remain permitted under `TENANT_BILLING_BLOCKED` remain available unless they independently require the unavailable authority. Retry only idempotent reads, or mutations carrying the same stable request idempotency key that the service durably deduplicates, with at most one automatic retry inside a five-second total deadline and bounded backoff. The dedicated logout controller uses its separate bounded logout/revocation budget and is excluded from this generic retry rule. Never replay an unkeyed or non-idempotent mutation, and do not convert this infrastructure failure into logout. - `ENTITLEMENT_UNAVAILABLE` – Preserve authentication state and show a retriable entitlement-availability message when entitlement authority is `UNAVAILABLE` or the required fresh Account entitlement evaluation cannot be established. Block only the affected admission, capacity, or other entitlement-dependent operation; retry under the same idempotency and bounded-backoff rules as `AUTH_UNAVAILABLE`. Do not relabel the outage as `TENANT_BILLING_BLOCKED`, `AUTH_UNAVAILABLE`, or `JOIN_REQUIRED`, and do not use stale entitlement state unless the exact bounded same-binding continuity contract applies. - `TENANT_BILLING_BLOCKED` – Keep the user logged in, mark the denied admission, capacity, or mutation operation as billing-blocked in UI state, and show a prominent billing banner. This is not a blanket tenant gameplay shutdown: preserve connected sessions, eligible same-session resume, permitted `past_due` gameplay, and billing-safe operations such as viewing invoices or updating payment details; `grace` preserves connected sessions and same-session resume but denies first-time public join, first/new gameplay bindings, new instances, scale-out, and quota growth. Apply this code only when authoritative Account evidence explicitly denies that operation; `ENTITLEMENT_UNAVAILABLE` takes precedence when entitlement authority cannot be obtained, while `AUTH_UNAVAILABLE` remains the corresponding non-entitlement authority outage. Neither unavailable result may be converted into a billing block. - `ADMISSION_POINTER_UNAVAILABLE` – Keep the current auth state for reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence, show a retriable gameplay-admission unavailable message, rerun bootstrap discovery or reconciliation, and only then retry lobby admission with bounded backoff; never substitute a cached tenant or runtime target. Unreachable or timed-out pointer authority is `AUTH_UNAVAILABLE` instead. - Target-state `REALM_UNAVAILABLE` – Keep the current auth state when the resolved realm pointer is complete and `CLOSED`, create no gameplay binding, and wait for fresh discovery or an authoritative availability change rather than fast-looping retries. This is distinct from reachable invalid pointer evidence (`ADMISSION_POINTER_UNAVAILABLE`) and unreachable or timed-out pointer authority (`AUTH_UNAVAILABLE`). - `CONNECT_CONTEXT_INVALID` – Keep the current auth state, force gameplay reconnect flow (`connect-token` refresh + new socket + `LOGIN`), and block `PLAY` retries on the current socket. - - `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. The current frontend still has no actionable first-party browser join repair because `Join & Play` is unavailable; target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. +- `CONNECT_SCOPE_MISMATCH` – **Current limitation:** Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. Do not expose an actionable current repair until the required issuance reread and runtime/deployment proof are complete; the local join route/writer and text dispatch already exist. **Target behavior:** Complete `Join & Play` when the newly selected public target requires membership, perform required character discovery/creation, request a fresh connect token only from the newly returned bundle, and retry on a new socket. Client rule for discovery-issued selectors: @@ -156,7 +156,7 @@ These handshake classes are edge-handshake outcomes, not gameplay text-protocol ### Current Implemented Browser Reconnect Behavior -Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but first-party missing or non-admitting membership remains unavailable/non-actionable because `Join & Play` and the target issuance reread are not implemented; this does not describe the separate implemented direct-text `JOIN` path. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. +Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but missing or non-admitting membership remains unavailable/non-actionable until the required issuance reread and runtime/deployment proof are complete. The local explicit join route/writer and Game Session text dispatch now exist. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. ### Target-Only First-Party Browser Reconnect Sequence diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index bce80338a6..116b09b690 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -11,7 +11,7 @@ Gateway does not validate ordinary REST or admin JWTs; the consuming Account, ad Unless otherwise noted, this document describes target-state gateway behavior. Current rollout and implementation boundaries are: - The target-state declarative `routes.yml` catalog has not yet converged as the implemented route authority. The current authority is the Java `CanonicalGatewayRoutesConfiguration`, with route-specific environment overrides `FIREMUD_GATEWAY_ROUTE_SESSION_URI`, `FIREMUD_GATEWAY_ROUTE_ADMIN_URI`, `FIREMUD_GATEWAY_ROUTE_DESIGN_URI`, `FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI`, and `FIREMUD_GATEWAY_ROUTE_SOCIAL_URI`. These are distinct from the `FIREMUD_SERVICES_*` service-discovery variables used by other microservices. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md#service-discovery). -- **Current Game Design route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. The controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate; official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current Game Design route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. - The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain is a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Gateway carries its non-secret domain pin in `FIREMUD_GATEWAY_REPLAY_DOMAIN`, which must equal exactly `gateway-connect-token-replay-v1` and is rendered as the fixed `{gateway-connect-token-replay-v1}` hash tag. Startup, target preflight, and migration/reset tooling must reject any other value and prove the same tag across Gateway instances and shared Coordination Redis readback. The current `GameplayHandshakeFilter` still writes only a legacy replay marker through the generic Cache-bound client; it has no browser-deny, readiness, or replay-fence writer. This is migration-only drift: before target admission, the named Coordination client/ACL must be cut over, the legacy state must be inventoried and read back under quarantine, the target contract must be verified, and legacy markers must be retained or explicitly cleaned only after their original acceptance windows expire. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index bb9a7e209e..3038cd0283 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -22,6 +22,10 @@ Implementation status and execution evidence belong in the owning trackers or PR FireMUD separates **global identity** from **per-game state** so that one person can participate in multiple games without data leakage between tenants. +Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. Current implementation and proof status are recorded in the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). + +The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Focused proof requirements for this boundary are owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); current implementation and proof status are recorded in the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status). + - **Platform account (`accountId`)** – A global identity record managed by the Account Service. Each human player has a single platform account, which is the subject of authentication and JWT issuance. - **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. diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index e5acbe2be1..814b001f14 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -529,7 +529,7 @@ Gameplay authentication is transport-specific. Credential-bearing Telnet and oth The receiver token is the exact `game-session-account-delegation` JWT profile with audience `account-service`; it is an Account-issued private backend credential, never a client gameplay credential. Its registry and rotation rules do not define the active gameplay-session lifetime or the bounded continuity/reconnect cache lifetime. If the Account response is lost during credential-bearing text login, Game Session retries with the same `requestId` and exact request digest. Account resumes matching pending work or returns the stored committed result/terminal outcome; it must not mint a second token merely because the first response was not observed. A confirmed binding-CAS conflict or superseded binding causes Game Session to keep the candidate unusable and issue Account's idempotent retire request for that exact operation and token identity. An ambiguous timeout instead remains fail-closed and provisional while Game Session reconciles the expected binding generation plus operation identity against the authoritative binding: it retires the candidate only after proving that the CAS did not commit, and completes installation or the canonical superseded outcome when the committed operation is found. Account performs bounded orphan cleanup after the operation's lease/expiry horizon; an orphan registry record is never sufficient to make a gameplay binding admissible. Proof must cover Account success followed by response loss, confirmed binding-CAS conflict, ambiguous CAS reconciliation for both committed and uncommitted outcomes, retry with the same request ID, retry with a conflicting digest, and cleanup/reconciliation after each cross-service failure window. The protocol uses ordered durable evidence, idempotent owner-side operations, and fail-closed provisional state; it does not claim a cross-store transaction. -After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Direct-text `JOIN` is implemented through the Account-owned writer, and current text `PLAY` validates fresh membership lifecycle/version/generation plus public entitlement/policy before returning `JOIN_REQUIRED`; full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. First-party `Join & Play` remains target-only and unavailable. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). +After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current admission, implementation, and proof status is recorded by [Authentication](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Session recovery/takeover is authorized by the gameplay binding plus current Account identity, membership, entitlement, and revocation authority; it does not require the previous backend token registry record to remain valid. When transport-specific reauthentication is required, the client must complete the applicable fresh credential/bootstrap and connect-context steps before backend calls resume. A missing or expired prior token therefore causes replacement or reauthentication, not acceptance of stale token state. > 🔗 See [Authentication & Authorization](./system-architecture-authentication.md) and [Reconnection Strategy](./system-architecture-reconnection.md) for detailed JWT format and session flow. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 53868c0ff9..79d693e202 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -Current implementation capability and proof status for player access, admission, and reconnect flows is tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). The target protocol flow, carriage, ordering, admission, authentication, reconnect, and delivery requirements below remain normative. +Current implementation capability and proof status for player access, admission, and reconnect flows is tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). The target protocol flow, carriage, ordering, admission, authentication, reconnect, and delivery requirements below remain normative; this bridge forwards the owned text sequence and does not independently claim successful live Account-backed `PLAY` or `JOIN`. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Direct-text `JOIN` is implemented locally through Account's explicit membership writer, while first-party `Join & Play` remains target-only. Current text `PLAY` validates the fresh Account membership lifecycle/version/generation evidence; for an otherwise eligible public-production target with missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`, with outage or policy denial winning. The complete browser sequence and full Telnet discovery/bridge proof remain incomplete. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` must validate exact account/tenant identity, freshness, consistent `ACTIVE`/`INACTIVE` lifecycle, and positive membership-version and membership-authority-generation values; missing membership is exact `MISSING` evidence with zero versions and no admission. Public `JOIN_REQUIRED` follows only missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership remains denied. Current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so supplied-authority classification is not proof of live admission; composed text/browser proof and connect-token issuance status remain with those owners. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current direct-text runtime has a lifecycle-state predicate and validates membership version/generation; `CHARS` and character creation use the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current connect-token issuance still does not prove the target independent issuance baseline/generation reread or private/playtest grant check, and a replay-cache hit can bypass fresh authority reads. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Account runtime, supplied-authority `PLAY`, and connect-token issuance implementation and proof status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so this target sequence is not live composed admission proof. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: text `PLAY` validates fresh membership lifecycle/version/generation evidence, and for an otherwise eligible public-production target with missing or non-admitting membership it evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public policy denial takes precedence. Direct-text `JOIN` is implemented locally through the Account-owned writer, but full Telnet discovery/bridge proof remains open; first-party `Join & Play` remains unavailable. Current text `PLAY` uses `WORLD_ACCESS_DENIED` for missing or non-admitting membership on a non-public target (private/playtest) and checks its current realm grant. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). In particular, `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` after the applicable routing, authority, fresh-entitlement, and public-policy gates pass. Preserve authentication and use the implemented direct-text `JOIN` writer or the target first-party `Join & Play` action; first-party `Join & Play` remains unavailable and full direct-text/Telnet completion is unproved. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE`, and the earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates must pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this supplied-authority classification does not establish live admission; current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -80,7 +80,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - Clients connect using TCP/Telnet and are handled by a dedicated **TCP Proxy Service**. - For local development and explicitly private compatibility networks, the TCP Proxy Service listens on port `2323` by default. This plaintext/default port is not a public player-facing contract; public deployments must select one of the TLS modes below. The port and the Spring Cloud Gateway WebSocket URL can be adjusted with the `TCP_PROXY_PORT` and `GATEWAY_WS_URL` environment variables described in the [TCP Proxy Service configuration](./microservices/tcp-proxy-service/configuration.md#environment-variables). `GATEWAY_WS_URL` should always be set explicitly by deployment config; local Compose smoke also sets it explicitly to the canonical in-stack target. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md) for general configuration guidance. Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. -Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; explicit-join and membership-reread gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). +Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist; lifecycle/generation reread and end-to-end runtime/deployment proof gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` retains `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on these non-public (private/playtest) targets; an eligible public-production request remains `JOIN_REQUIRED`. It also requires the current realm grant, while connect-token grant validation remains implementation drift. The separate current Account connect-token mappings are recorded in the implementation status above and are not text-protocol outcomes. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. Direct-text `JOIN` is implemented locally through the Account-owned writer; the full Telnet discovery/bridge reconnect proof remains open. First-party `Join & Play` remains target-only. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session currently suppresses private retained-context replay and renders a fresh authoritative `LOOK` and configured prompt on the reconnect path; it does not treat a connect context alone as replay authorization. Current deliberate `LOGOUT` fails closed with `LOGOUT_UNAVAILABLE` without terminating the binding until the durable episode fence exists. The target permits private context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Generation/termination enforcement, live Telnet proof, and a safe private replay path remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Current admission-reader containment and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status): Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. A supplied-authority `JOIN_REQUIRED` classification does not establish live admission. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits Game Session to present bounded semantic recent context only after fresh admission and when exact binding and episode evidence permit, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); current Game Session suppresses private retained-context reads on reconnect. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads remain suppressed on reconnect and after attempted `LOGOUT`, while fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement and live recovery proof remain incomplete, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces and first-party `Join & Play` remains unavailable, so their complete first-join/reconnect proof is not established. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; direct-text `JOIN` is implemented locally and current `PLAY` applies fresh membership lifecycle/version/generation plus fresh public entitlement/policy before `JOIN_REQUIRED`, while full Telnet bridge proof remains open. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. @@ -277,7 +277,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d - Buffers active input while the client remains connected and discards it if the TCP connection drops; the proxy never replays Telnet commands after a disconnect. - Telnet clients keep a sticky connection to the TCP Proxy Service; reconnection and session recovery are handled as described in [Reconnection Strategy](./system-architecture-reconnection.md). - Retained-edge upstream rebind is not an actual client-facing disconnect: Spring Cloud Gateway retains the client or proxy-facing gameplay WebSocket while performing ADR 0013's bounded rebind of a rebindable Game Session upstream, then closes with `1013/backend_unavailable` if recovery exhausts its window. Game Session revalidates the existing continuation binding, authorization, revocation, and target authority under the [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) contracts; it does not require fresh `LOGIN`, `JOIN`, or `PLAY`, and this hidden rebind does not trigger retained-context restoration or a fresh `LOOK`. -- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. After fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, Game Session currently suppresses private retained-context reads on reconnect and after attempted `LOGOUT`, then renders a fresh authoritative `LOOK` after accepted `PLAY`; strict generation-fence enforcement and live recovery proof remain incomplete. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. +- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Only after fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, may Game Session restore retained semantic context when its binding and episode evidence permit, followed by a mandatory fresh authoritative `LOOK`. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads remain suppressed on reconnect and after attempted `LOGOUT`, while fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement and live recovery proof remain incomplete. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, non-positive, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer positive generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. - The proxy defines a `NotifyDisconnect` gRPC event so the Game Session Service can react quickly when Telnet clients drop. This stream is best-effort and **at-least-once**, and Game Session treats it as an idempotent, advisory hint rather than a source of truth for session liveness. Consumers key handling off `{proxyConnectionId, disconnectSequence}` so late or duplicate events are safe to ignore. The behaviour-level contract for this stream is summarised in the **NotifyDisconnect Behavioral Contract** section of [Reconnection Strategy](./system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary), while the TCP Proxy Service design’s **Service Interactions** section remains canonical for message fields, retry windows, and envelope context. - Metrics are exported at `/actuator/prometheus` and tracing data is sent to the collector configured by `OTEL_ENDPOINT`. See [Logging & Monitoring](./system-architecture-logging-monitoring.md). - Environment-specific tuning guidance for the TCP Proxy Service (connection caps, envelope budgets, and production hardening) is documented in the TCP Proxy Service design under **Tuning TCP Proxy for Different Environments**. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 74996ce42b..93af0314a4 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,8 +10,8 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current text `PLAY` uses the fresh Account fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; positive admission requires `ACTIVE`, and an otherwise eligible public-production missing or non-admitting membership is classified as `JOIN_REQUIRED` only after fresh entitlement permits public joining. Entitlement outage or public policy denial takes precedence. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable and full Telnet/browser reconnect proof remains open. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/reread remains unproved. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current text `PLAY` behavior. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. -- **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission, implementation, and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; token issuance persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). +- **Runtime authority checks** – `PLAY` attempts membership and tenant-entitlement checks before fresh entry or resume/takeover, but its local classification uses supplied authority and does not prove positive live checks. Account's runtime readers fail closed before data reads until typed caller/target binding is available; see [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift). - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,18 +78,18 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its conditional `JOIN` procedure; ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Direct-text `JOIN` is implemented locally through the Account-owned writer; full Telnet discovery/bridge reconnect proof, including PostgreSQL/recovery evidence, remains open. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. -- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the first-party join endpoint remains unavailable in the current runtime. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure. Ordering, membership classification, and direct-text scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; current browser/runtime implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current non-public membership/admission denial from the available `membershipExists` and `gameplayAdmissionAllowed` fields remains `WORLD_ACCESS_DENIED`; current text `PLAY` also checks the current realm grant, while current connect-token grant validation remains incomplete. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live membership-read failure maps to `WORLD_ACCESS_DENIED`; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. Direct-text `JOIN` is implemented locally, but complete Telnet discovery/bridge and PostgreSQL/recovery proof remain open; first-party browser/mobile bootstrap/connect-token and `Join & Play` surfaces remain partial and target-only. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the live membership-read failure to `WORLD_ACCESS_DENIED`. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Direct-text `JOIN` is implemented when an otherwise eligible public-production request requires membership; current `PLAY` gates `JOIN_REQUIRED` on fresh entitlement/public policy and current lifecycle evidence. Full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. -- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. Current first-party browser/mobile bootstrap/connect-token surfaces are partial and the complete flow, including `Join & Play`, remains target-only. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). `PlayCommandHandler` has focused unit response-classification coverage using supplied Account authority, but live Account membership/entitlement/grant RPCs fail before data access and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`; no live `JOIN_REQUIRED` or successful composed public `PLAY` through these handlers is established. Local direct-text REALMS-scope/JOIN dispatch and the Account RPC exist, but the public Gateway JOIN route remains denied; PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. A local browser bootstrap JOIN facade exists, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied; the full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Direct-text `JOIN` is implemented locally, and current `PLAY` applies fresh membership lifecycle/version/generation plus fresh public entitlement/policy before `JOIN_REQUIRED`; complete Telnet bridge and recovery proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that live membership failure to `WORLD_ACCESS_DENIED`; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 798879e1ce..de06574560 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -9834,6 +9834,7 @@ plus scoped tick pause/resume used for rollback safety. | payload_digest | [string](#string) | | | | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | +| audit_projection_version | [int32](#int32) | | Version 1 attests the receipt/projection link. Positive delivery evidence also requires a COMMITTED receipt and matching receiver identities for the exact scoped outbox row, not payload replay. Zero or unsupported versions cannot verify delivery or historical producer provenance. | @@ -9977,6 +9978,7 @@ plus scoped tick pause/resume used for rollback safety. | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| audit_projection_version | [int32](#int32) | | Same version-1 receipt/projection evidence rule as CreateLogEventResponse: a COMMITTED receipt with receiver identities matching the exact scoped outbox row; it is never payload replay proof. Zero or unsupported versions cannot verify delivery or historical producer provenance. | diff --git a/design/product/user-journeys/operators.md b/design/product/user-journeys/operators.md index 972414e97c..63888c4ad2 100644 --- a/design/product/user-journeys/operators.md +++ b/design/product/user-journeys/operators.md @@ -17,7 +17,7 @@ The journeys below keep target operator behavior primary. Current and target bou - **Moderation ingress:** Current report creation uses the physically reachable internal service-to-service `CreateReport` seam, which remains unsupported and unproved. Public/player report ingress is currently unavailable until its caller-bound contract exists. The target report and operator-write contracts are defined in the [Logging & Admin API status](../../architecture/microservices/logging-admin-service/api-contracts.md#implementation-status) and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). - **Safety and appeals:** The target fixed categories, owner-local enforcement, and bounded appeal case are defined in [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md). Current category persistence, owner commands, player notices, and appeal workflow are not implemented or proved. Account is the target enforcement owner for `platform_access_ban` and separately owns the current `security_locked` foundation plus target `account_security_lock` security/recovery; the separate punitive platform-ban enforcement is not current proof. Logging & Admin owns moderation appeals, while Game Session and Social & Groups remain target enforcement owners for their categories. - **Redis/PostgreSQL recovery:** Current recovery uses the fail-closed operator fallback with affected workloads fenced; the durable controller-backed Redis reset and PostgreSQL restore/reopen sequence is target-only. See [Redis Reset & Recovery](../../architecture/system-architecture-redis-reset-and-recovery.md#current-operator-fallback), [Backup & Disaster Recovery](../../architecture/system-architecture-backup-recovery.md#recovery-controller-continuation), and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). -- **Grant revocation:** Current Account grant persistence and internal lookup can support a grant-backed admission read, but target expiry, revision/tombstone mutation, tenant-admin and break-glass commands, and active-binding ejection are not implemented or end-to-end proved. The target grant contract is canonical in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Current text `PLAY` still consumes the existing membership/admission fields; non-public missing or non-admitting membership remains the current `WORLD_ACCESS_DENIED` path. Target denial of discovery, reconnect, and `PLAY`, together with termination of affected fork bindings, applies after grant expiry/revocation only once that target enforcement is implemented; unrelated account access remains available. Expiry and lifecycle automation remain gaps. +- **Grant revocation:** Current Account grant persistence and internal lookup exist, but the live membership, entitlement, and grant readers fail closed with `FAILED_PRECONDITION` before Account data reads pending typed caller/target binding. Game Session's local text `PLAY` membership and grant branches have supplied-authority unit coverage only; a live membership-read failure maps to `WORLD_ACCESS_DENIED`, and composed grant-backed admission is not proved. Current connect-token grant validation is also incomplete. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owning runtime status. Target expiry, revision/tombstone mutation, tenant-admin and break-glass commands, and active-binding ejection are not implemented or end-to-end proved. The target grant contract is canonical in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Target denial of discovery, reconnect, and `PLAY`, together with termination of affected fork bindings, applies after grant expiry/revocation only once that target enforcement is implemented; unrelated account access remains available. Expiry and lifecycle automation remain gaps. - **Session termination:** Gameplay takeover, `LOGOUT`, and transport idle-close handling are current; Account control-plane revocation/logout, full expiry convergence, and post-logout replay cleanup remain partial. Target termination distinguishes logout from suspension and closes revoked active sockets so the affected session cannot resume; see the [Player Access and Session tracker](../../project-management/implementation-tracking/player-access-and-session.md#capability-status) and [Session Behavior](../../architecture/system-architecture-session-behavior.md#active-socket-auth-revocation). - **Realm lifecycle and replacement:** Target operator diagnostics distinguish preparation, pre-activation failure, termination, and cleanup completion while retaining the stable playable-state namespace alongside the active runtime. World Management lifecycle state and epoch remain admission authority; Temporal reports coordination progress. A failed preparation is not proof of cleanup, and termination is complete only after every owner in the cleanup attempt's frozen required-owner snapshot at its frozen ownership-registry revision acknowledges cleanup. Current operator readback remains partial; see [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). - **Script-transition operations:** Game Session currently persists the pin and exposes convergence reads but does not yet provide the target append-only request-idempotent history or direct history read; the live handoff lacks `scriptPinEpoch` and cannot yet reject same-version work from an older epoch; and Automation does not yet persist and propagate the captured `(pluginActivationEpoch, lifecycleRevision)` pair through every plugin work/status/handoff/retry/replay/recovery surface. These target history/readback and exact-fence capabilities remain unimplemented and unproved. Use [Scripting & Automation: Control Plane Operations](../../architecture/system-architecture-scripting-control-plane-operations.md), [Scripting & Automation: Rollout and Rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md), and the [Scripting & Automation: Observability Contract](../../architecture/system-architecture-scripting-observability-contract.md) for the canonical checks, epoch distinction, notification recovery, and sequencing. Current operator-visible gaps also include stale executor `ONLOAD_RUNNING` work not yet being reclaimed or terminalized; for current stale-readiness incidents, use the admin-authorized read-only patch-status and drain diagnostics, keep the readiness barrier in force, and do not infer reclaim, terminalization, or replay from age. The target Automation readiness-owner fenced path remains unimplemented; see [Stale `onLoad` execution](../../architecture/system-architecture-scripting-operations-cookbook.md#stale-onload-execution) for the current-safe response. diff --git a/design/product/user-journeys/players.md b/design/product/user-journeys/players.md index 50659a67c6..b93580f704 100644 --- a/design/product/user-journeys/players.md +++ b/design/product/user-journeys/players.md @@ -41,7 +41,7 @@ These journeys define observable product behavior and user-facing outcomes; tech ## Implementation Status -The target journeys below are primary. Current runtime status is concise: explicit `JOIN` / `Join & Play` and the complete realm-scoped character gate remain unimplemented; existing credential-bearing clients may still use direct `LOGIN` -> `PLAY` when they already have usable membership and a character. Connect-token issuance and text `PLAY` require existing membership and return `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership. Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. +The target journeys below are primary. Current runtime status is concise: the local Account `JOIN` writer and Game Session text dispatch, along with the global-only registration seam, are implemented, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied. The complete realm-scoped character gate remains unimplemented, and direct-text/first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and downstream lifecycle/authority-generation admission proof remain incomplete. `PlayCommandHandler` has focused unit response-classification coverage with supplied membership and entitlement evidence, but live Account runtime membership, entitlement, and grant RPCs return `FAILED_PRECONDITION` before data reads; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. This does not establish live `JOIN_REQUIRED` or successful composed public `PLAY` through those handlers. Account `/auth/connect-token` retains separate Account-owned public membership/policy and non-public enrollment/access outcomes; they are not text `PLAY` outcomes (see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift)). Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. Current gameplay supports room views, movement, foundational inventory/container/equipment commands, and room-local `SAY`, `WHISPER`, and `TELL`. Guild chat and mail remain deferred target behavior and are not current player-runtime capabilities. The shared current communication path includes metadata-only whisper observers and recipient-side delivery for generic WebSocket and Telnet clients; broader audible scopes and first-party/MCP-aware presentation remain gaps. The target player-facing report ingress is not currently available; current support is limited to an internal service-to-service report-persistence seam, not player ingress. @@ -109,7 +109,7 @@ Player → Account bootstrap/discovery → [Join & Play when public membership i → connect-token issuance → Gateway WebSocket handshake → bare LOGIN → PLAY ``` -Target-state example text-client transcript (explicit `JOIN` is not implemented in the current runtime): +Target-state example text-client transcript (the local `JOIN` seam exists; complete transport end-to-end proof remains incomplete): ```text WORLDS @@ -138,7 +138,7 @@ LOGIN PLAY [realm] [character] ``` -Target-state example first-time public production join (explicit `JOIN`/`Join & Play`, including `POST /auth/bootstrap/join`, is not implemented in the current runtime): +Target-state example first-time public production join (the local Account `JOIN`/`Join & Play` operation exists; complete transport and production proof remains incomplete): ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a6adb142da..fa892f09f5 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -183,6 +183,12 @@ Entry format: - Expected pattern: enable `set -o pipefail` before captured validation pipelines and verify the terminal build result and test reports; a log sink's success is not the validation process's success. - Outcome: the failed build was identified from its terminal report, not reported as passing. After the fixture correction, the guarded complete rerun passed; no production check or negative assertion was weakened. +- `2026-10-03`: Assert fresh initialization before testing idempotence + - Context: the Compose mTLS certificate contract checked private authority-directory permissions only after running setup twice. + - Observation: the second call repaired the first call's incorrect permissions, so the passing contract masked a broken fresh-initialization postcondition. + - Expected pattern: assert the first-call postconditions before any verification or idempotence rerun, then separately prove the rerun preserves the valid fixture. + - Outcome: setup now restores owner-only authority permissions after generation, and the focused contract independently proves the first-call boundary and repeated-call preservation. + - `2026-10-03`: Native process handles may be scoped to the launching agent - Context: Gameplay tried to transfer an already-running full CLI command's native process handle to a read-only sentinel. - Observation: the sentinel received `Unknown process id`, while the launching agent could still read the same live process. Shared filesystem access did not imply shared process-handle access; the review was neither restarted nor canceled. @@ -190,6 +196,12 @@ Entry format: - Current status: the launching Gameplay agent retained the live CLI wait. Whether cross-agent process handles are supported in other execution environments is unverified. - Reconsideration trigger: revisit if a future harness requires cross-platform handle portability or a canonical watcher fix is verified. +- `2026-10-03`: A merge preview needs positive conflict evidence, not a marker-only filter + - Context: a read-only parent-forwarding inventory used this checkout's older three-argument `git merge-tree` and searched only for standard conflict markers. + - Observation: the inventory incorrectly called the merge clean; the actual isolated no-commit merge reported six documentation conflicts. The preview's `changed in both` records and command outcome had not been inspected. + - Expected pattern: verify the installed command's supported mode, inspect its complete conflict records and exit outcome, and treat an isolated actual merge as authoritative. Missing matches from a marker filter do not prove a conflict-free merge. + - Outcome: the claim was retracted before publication, and the documentation intersections are being resolved explicitly while both unique patches remain preserved. + - `2026-10-03`: A terminal Hosted notification needs prompt owner consumption - Context: the exact-head #2898 Hosted review finished with five findings, but Gameplay delayed consuming the sentinel result while handling parent CI; adjudication and the public checkpoint followed about eleven minutes later. - Observation: an active watcher does not guarantee prompt adjudication. Its reassuring handoff wording cannot replace checking the attributable result and raw findings. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index e047f01134..9bceb6cf4d 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 17 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–17 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. Cycle 17 exposed the concrete public-registration membership bypass of disabled public joining; AA-1.1/AA-1.2 now state the live gap, and a containment/deployment decision is pending because coherent global registration also needs platform-scoped durable audit. The optional external-provider product summary now matches ADR 0049. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 191c024fa7..4dadf1f083 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -149,7 +149,7 @@ No implementation-blocking import override is active. Record an override here wi ### Packet 2: Identity, Authority, And Security -Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`, but `POST /auth/bootstrap/join` is target-state and not implemented; current text `PLAY` and connect-token issuance require existing caller-bound membership and return canonical `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership, while the obsolete implicit membership-writer RPC/client/service seam has been removed. The target admission contract retains `JOIN_REQUIRED` for policy-permitted missing or `INACTIVE` membership. `WORLD_ACCESS_DENIED` is reserved for another reachable authoritative world/tenant denial and is mutually exclusive with `JOIN_REQUIRED`. A realm grant never substitutes for membership, and the connect-token membership-version plus membership-authority-generation reread remains a gap. The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims: the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) records the missing tenant-scoped roles, switching controls, and implementation state, while its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section records focused evidence and remaining proof gaps. +Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`. The target admission contract remains owned by [Authentication](../../architecture/system-architecture-authentication.md#login-and-session-flow). Implementation and proof status belong to [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status), including [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof). The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices. Packet 2 count reconciliation: the 31 reviewed decisions are covered by the checked dispositions for ADRs 0020-0050, excluding the historical service-scan alias. The Packet 2 disposition contains exactly those 31 reviewed decisions; the alias is navigation-only and is not a checked disposition row. diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index 4886445561..c1be33d38b 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -94,11 +94,11 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | Key | Primary capability | Secondary capabilities | Question -> current choice | Status | I/R | Sources / explicit ADR | Strongest alternative | ADR recommendation | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `AUTH-01` | `AA-3.1` | `AA-2.1`, `AA-3.3`, `SF-1.2` | What identifies gameplay selection/admission and controller ownership? Stable `worldSlug`/`realmSlug` and snapshot-bound ordinals are lobby selectors. Selection/admission resolves the authoritative gameplay binding `{tenantId, realmId, gameInstanceId, characterId}` plus the applicable pointer/fence, `playableStateNamespaceId`, and server-derived scope evidence; `gameInstanceId` remains the active-runtime fence/value, and slugs and ordinals never grant authority. Separately, the single-controller uniqueness key is exactly `{tenantId, playableStateNamespaceId, characterId}`; `gameInstanceId` is not part of controller uniqueness. | `accepted-explicit` | H/hard | `AU § Contract Decisions (Normative)`; `MT § Identity & Tenant Model`; [ADR 0168](../../architecture/decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [Session Behavior](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) | Opaque handles for every selection, durable slug authority, fresh-catalog ordinal reuse, or per-instance controller identity. | Human review revised and superseded ADR 0005 on 2026-07-21. ADRs 0122 and 0132 continue to own stable playable-state namespaces and namespace-scoped controller transfer. | -| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. Explicit `JOIN` remains unimplemented, so that text `PLAY` result is not an actionable recovery flow. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | +| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. Implementation status and proof gaps are tracked in the [Player Access and Session tracker](../implementation-tracking/player-access-and-session.md#current-status). | | `AUTH-03` | `AA-1.3` | `AA-1.2`, `AA-1.5`, `AA-2.3`, `SF-1.3`, `SF-2.2` | Who owns identity, revocation, entitlements, and gameplay bindings? Account owns durable account, token, revocation, membership, entitlement, and the single issued-token registry authority; JWT-presenting registry-backed control-plane, bootstrap, and admission operations perform exactly one registry lookup, while Game Session owns gameplay bindings and derives typed execution context and Gateway has only bounded edge checks. The dedicated `gameplay-connect` artifact remains outside the issued-token registry and uses its own single-use replay fence. | `accepted-explicit` | H/hard | [ADR 0022](../../architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); `AU § Responsibility Split`; `OV § Authentication Modes and Boundaries`; `RM § Notes on Movement and Moderation Contracts` | Introduce a dedicated IAM service, make Gateway the general identity authority, or use TTL-only tokens. | Affirmed by human decision; ADR 0022 records one writer per authority and separates accepted design from revocation/session implementation gaps. | | `AUTH-04` | `SF-1.3` | `AA-1.2`, `PO-1.1`, `PO-2.1`, `PO-4.4` | How are protected routes authorized? One machine-readable route policy governs strict token profiles, explicit tenant/cross-tenant scopes, generated completeness checks, and runtime denial of unclassified routes; services retain domain checks. | `accepted-explicit` | H/hard | [ADR 0023](../../architecture/decisions/adr-0023-central-route-authorization-governance.md); `AU § Auth Middleware Algorithm (Normative)`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Admin Entry Points and Traffic Surfaces` | Service-local role checks, Gateway-only authorization, or a general-purpose external policy engine. | Revised and accepted by human decision; policy/proof upkeep is an accepted security tradeoff and current enforcement gaps are explicit. | | `AUTH-05` | `SF-1.3` | `SF-1.2`, `SF-1.1`, `GR-1.1`, `PO-3.2` | How is internal player delegation trusted? Concrete mTLS workload identity and exact method caller allowlists authorize the trusted gameplay service; unsigned typed `PlayerExecutionContext` carries validated scope, while mutations retain operation-specific idempotency. | `accepted-explicit` | H/hard | [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); `AU § Gameplay Player Execution Context Contract (Normative)`; `SE § Gameplay Workload Trust`; `GR § TLS Requirements` | Per-RPC signed/replay-guarded attestations, signed attestations without replay storage, or generic backend JWTs carrying player identity. | Revised and accepted by human decision after two-sided adversarial review; the current first-party trust domain explicitly accepts allowlisted-intermediary impersonation risk to avoid universal hot-path attestation cost. | -| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The obsolete implicit membership-writer seam has been removed, explicit `JOIN` is not implemented, and the connect-token membership-authority-generation reread remains a gap. For private/playtest targets, target text behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED` and requires existing `ACTIVE` membership plus the applicable grant. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | +| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** Game Session's local supplied-authority `PLAY` classification validates lifecycle, authority-generation, membership-version, and evaluation time; it returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, and denies an `ACTIVE` but non-admitting membership without JOIN advice. Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful public `PLAY` is established; live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but its independent membership-version and authority-generation issuance rereads remain unproved. The obsolete implicit membership-writer seam has been removed; Account's explicit `JOIN` operation and direct-text dispatch/scope seams exist locally, while the public Gateway JOIN route remains denied. Full PostgreSQL, pending-outcome recovery, and direct text-to-Logging proof remain open. For private/playtest targets, the target contract requires existing `ACTIVE` membership plus the applicable grant and never offers public `JOIN`; see the linked ADR and Authentication status for detail. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | | `AUTH-07` | `AA-1.2` | `AA-2.1`, `PO-1.1`, `PO-1.2`, `EA-3.3` | Can global roles grant gameplay authority? No: global roles cannot admit or elevate gameplay, staff join as ordinary players unless given explicit tenant-scoped gameplay capabilities, and the target has no impersonation or hidden observation. | `accepted-explicit` | H/hard | [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); `AU § Role Model`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Moderation, Restriction, and Appeal Authority (Canonical)` | Global-role gameplay bypass, audited time-bounded impersonation, or read-only live observation. | Revised and accepted by human decision; current global `platformAdmin` to in-game `ADMIN` classification is implementation drift, while support remains on purpose-built control-plane and diagnostic surfaces. | | `TENANT-01` | `AA-3.3` | `AA-3.1`, `AA-3.2`, `AR-3.2`, `GR-2.1`, `GR-1.1` | How is a realm admitted? A Game Session-owned route is `OPEN` on exactly one instance or explicitly `CLOSED`; atomic pointer versions govern new/renewed bindings, while active source sessions end through bounded drain rather than per-action revalidation. | `accepted-explicit` | H/hard | [ADR 0027](../../architecture/decisions/adr-0027-single-realm-admission-target.md); `MT § Realm Catalog and Admission-Pointer Contract`; `VR § Realm Routing Contract For Player-Addressable Realms`; `OV § Design-Time vs Runtime World Data` | An instance-placement pool behind one realm, mutable latest-version lookup, or client-selected instance. | Revised and accepted by human decision; one shared world scales inside one instance, while explicit realms represent separate worlds and implementation must converge on tenant-qualified atomic CAS and cutover bookkeeping. | | `TENANT-02` | `AA-1.5` | `PO-3.1`, `PO-3.2`, `SF-2.2`, `GR-1.3` | Shared services, PostgreSQL, Coordination Redis, Cache/Rate-Limit Redis, and cluster capacity are the only supported normal multi-tenant topology; logical tenant scoping, authorization, quotas, and service ownership provide isolation. The environment-wide incident and recovery blast radius is accepted. A demonstrated future hard-isolation requirement uses a separately reviewed complete environment, not a hybrid selectively dedicated tenant data plane. | `accepted-explicit` | H/med | [ADR 0041](../../architecture/decisions/adr-0041-shared-tenant-infrastructure-with-full-environment-isolation-gate.md); `MT § Data Separation per Service`; `MT § Tenant Configuration & Scaling`; `OV § Multi-Tenancy Enforcement` | Dedicated tenant clusters, databases, Redis partitions, or a hybrid shared/dedicated routing tier. | Human review completed 2026-07-19; `revised`. | diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index a00f87064b..2309011d8a 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -32,13 +32,15 @@ The 23 original family sections remain the top-level corpus map, but 5B is now p 4. Update **only the alignment index** for section/subunit status, main PR, completion evidence, and routed obligations. The index keeps the three 5B subunit rows under the two-document tracking model; record their evidence and routed work in the planned **Evidence / routed work** column. Record the whole-5B synthesis as a non-row evidence line associated with those three rows, never as an aggregate 5B status row. The index must not become a PR-shaped ledger. A split implementation PR is linked from the relevant subunit evidence rather than creating a PR section. Keep detailed finding evidence with the relevant review/PR artifacts, not a second live section-status ledger. Any future semantic boundary change must update both maintained documents before assigning new subunits or PRs. 5. A section is complete only when its refreshed source list and material handoffs have been assessed, valid findings are fixed or explicitly owned elsewhere, and the current review has tapered. For 5B, completion additionally requires all three subunit terminals plus a tapered whole-5B synthesis. Record each subunit's reviewed/allocated source count, evidence, and routed work in the index; record synthesis evidence on its non-row line. At final closeout, compare the union of the refreshed section and subunit lists with the [allocation](./design-capability-allocation.md): every allocated source must be reviewed in an owning section, explicitly handed off by heading, or listed as an exemption with a reason. Merging one PR alone does not establish section or subunit completion. +When Overseer closes broad discovery for a section by explicit judgment before taper, record that as a discovery stop, not section completion or merge readiness. Before handing off the section, reconcile each accepted finding and relevant tracker gap against current behavior: implement unsafe exposed paths in their owning boundary, or assign substantial pre-v1 work to a concrete owner and successor with dependency and activation gate. A tracker link alone does not remediate a live defect. Record deliberately deferred features with their containment, reason and revisit trigger; keep unexecuted PostgreSQL, cross-service and deployment proof attached to the applicable readiness gate. Preserve the difference between whole-corpus coverage, implemented capability and exercised proof in the index and owning trackers. + ## Starting manifests These recovered manifests are starting review prompts, not frozen inventories or old completion claims. Refresh each when its section starts. Historical statements about what is currently implemented or unresolved must be verified before use. Numbered paths below are review inputs; heading-scoped consumers and adjacent sections remain handoffs rather than duplicate owners. ### 1A -Unit 1A's substantive boundary is the following 28 identity, membership, entitlement, billing, and hosted-terms sources: +Unit 1A's substantive boundary is the following 29 identity, membership, entitlement, billing, and hosted-terms sources: 1. `design/architecture/service-responsibility-matrix.md` 2. `design/architecture/system-architecture-overview.md` @@ -68,6 +70,7 @@ Unit 1A's substantive boundary is the following 28 identity, membership, entitle 26. `design/architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md` 27. `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` 28. `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` +29. `design/architecture/microservices/account-service/README.md` Review Account's sole authority for global identity, credentials, explicit membership, entitlement, Creator Party and terms evidence; account-global versus tenant-scoped records; public versus private/playtest access; strict and continuity entitlement freshness; authentication path separation; role versus gameplay authority; hosted creator mutation currentness; changed-terms decline and prior-rights continuity; and payment evidence versus runtime entitlement. Unit 1A consumes 5A token/authority primitives and hands gameplay binding to 1B and operator reference execution to 6C. Refresh for material 5A, 6C, 1B, 5B/5D, 3A, or billing/provider changes. Repository licence/terms files remain legal-policy handoffs rather than technical authority sources. 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 62c98d61e5..f1dbda8587 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 @@ -12,6 +12,8 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b 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. +The Gateway Java catalog now omits external Game Design asset and template writes, containing the previously reachable service-local controllers at that edge. Those controllers still lack Account currentness/evidence binding, and direct service-local or future creator ingress is not ready for official-hosted use. The route restriction is not Game Design gate proof. + ### Script and plugin transition reconciliation Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index a998941ac4..57052f75f1 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -154,6 +154,8 @@ The fixed `develop` environment is a separate `dev-demo-cluster`, not a PR previ Gateway is a curated public edge with explicit route inventory and deny-by-default behavior, not permissive service fan-out. Canonical route families include `/api/session/**`, `/api/admin/**`, `/assets/**`, WebSocket gameplay, Telnet, and `gateway.v1` management. The current public session HTTP inventory is only `GET /api/session/ping`; remaining session/admin routes are privileged external contracts. Gateway blocks `/api/{public-family}/internal/**`, and undocumented paths under the explicit families are denied rather than forwarded by a coarse family matcher. The canonical namespace is `/api/{service}/**`, not the obsolete `/admin/...` examples. +The current Java catalog narrows Game Design's external inventory to `GET /api/design/ping` and `GET /api/design/templates`; it does not forward creator `POST /api/design/assets` or `POST /api/design/templates`. Focused route-predicate tests cover this static containment across profiles. This does not implement the Account-owned hosted-content gate in Game Design or prove full route-catalog/matrix convergence. + Owner-side enforcement is part of the boundary: Game Session enforces the documented public/internal/operator split, and Logging & Admin exposes only published privileged routes behind its own authorization. Gateway route configuration, route predicates/filters, owner controllers, fixtures, and docs are intended to describe the same inventory. Gateway management uses the canonical `gateway.v1` package and shared in-band application-error conventions; it does not replicate service authorization policy locally. New public routes must be added to the explicit inventory with owner-side enforcement. Spring Cloud Gateway's current dynamic route-management surfaces remain ephemeral overrides layered over the Java-owned baseline in `CanonicalGatewayRoutesConfiguration`; the released declarative catalog/import, complete mutation-profile gating, private-listener/mTLS/network-policy proof, shared persistence, multi-pod convergence, route-change auditing, readiness enforcement, route-input allowlists, and restart persistence remain unimplemented or unproven. Hosted Helm renders `prod` without dynamic-mutation configuration, but the Java-owned player-facing routes remain. This route-management lifecycle is not a production control plane; target ownership and protocol remain in [Gateway Configuration](../../architecture/microservices/spring-cloud-gateway/configuration.md) and [Gateway Architecture](../../architecture/system-architecture-gateway.md). 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 d093a24b12..0d43a9f1c5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,11 +8,15 @@ This is a non-normative implementation tracker for player access and session. Ca The storage-only UUID prerequisite now persists an immutable, unique, non-nil Account UUID with provenance and the unchanged numeric source-row id through V29. Game Session V11 adds nullable Account UUID evidence to the gameplay command ledger and repository round-trip while preserving retained numeric Account IDs; historical commands receive no inferred UUID. No producer or session carrier supplies or consumes these UUIDs, and this storage work does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused PostgreSQL repository and migration cases are present but skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN writing and direct text dispatch, durable Account audit outbox handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `POST /auth/bootstrap/join` controller/operation exists locally, but the Gateway guard still blocks its external exposure. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receipt receiver persistence/readback remains unproved under #2940. First-party `Join & Play`, recovery after an unknown JOIN commit outcome, PostgreSQL runtime proof, and direct text-client end-to-end proof remain unavailable or unclaimed; the membership-version and authority-generation baseline reread at connect-token issuance also remains incomplete. Current `PLAY` and connect-token issuance remain partial, with membership and realm-grant authorities separately owned by Account. Namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and the terminal post-logout `resumeContextGeneration` fence remain incomplete; current private replay is suppressed fail-closed. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +The Account JOIN worker's positive audit evidence includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. Retained legacy IDs without that marker remain unresolved. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver persistence/readback remains unproved under #2940. + +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and producer-side typed receipt validation, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable. The bounded Account JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize, while absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end proof, and Account's independent connect-token issuance-time membership-version/authority-generation reread proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and durable post-logout `resumeContextGeneration` fencing remain incomplete. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. 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. -Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +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). + +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. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. @@ -22,6 +26,27 @@ Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. +## Unit 1A Section-Exit Dispositions + +Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, not by two dry cycles. The current Account correction belongs to #2848; this table distinguishes contained live paths from substantial pre-v1 successors and proof gates. A successor or tracker owner is not evidence that exposed behavior is safe, and none of these rows makes the PR merge-ready. + +| Open item | Owner and concrete next slice | Exit or activation condition | +| --- | --- | --- | +| Direct Account gRPC runtime/profile/presence/export/link/verification reads and mutations | Account `AA-1.1`–`AA-1.3`, current #2848 correction | Exact workload and caller-subject guards, or explicit method denial before read/mutation; negative missing-peer/cross-account proof and composed certificate/CI proof. Game Session runtime read consumers remain unavailable until Unit 1B supplies the typed caller/target contract. | +| Generic payment, donation, refund and deferred virtual-currency RPCs | Account `AA-1.4`, current #2848 containment; later Account billing/economy successor | Unsupported methods deny before service/provider/balance work. Re-enable only for a supported product operation with exact workload authority, provider identity and negative mutation proof; a future economy requires its own accepted product contract. | +| Recovery-token reuse and JOIN abandoned `PENDING` intents | Account `AA-1.2`/`AA-1.3`, current #2848 correction | Atomic single-use reset/verification claims and bounded JOIN readback reconciler require executed PostgreSQL concurrency, lost-acknowledgement, no-duplicate and unresolved-outcome proof. Expiry or absent evidence never terminalizes a pending JOIN. | +| Verification and password-reset email-link reachability | Account `AA-1.3` delivery/confirmation successor and Platform edge handoff | Shipped verification links use GET while Account implements bearer-protected POST completion; shipped reset links point to a non-Account route. Token claims remain guarded, but email-based recovery/verification is not end-to-end proved. Before treating these flows as usable, provide an explicit web-client/edge confirmation handoff or matching handler, align public-route authentication without a state-changing GET shortcut, and execute link-to-completion proof; deployment-specific URL overrides alone need reachability proof. | +| Account deletion and retained financial/provider data | Account `AA-1.3` plus `DATA-01`, named pre-v1 pending-deletion/retention successor after this containment | Every current `DeleteAccount` entry denies before mutation. Enable only after the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, approved finite schedules, restore/replay and no-mutation/terminal proof exist; no partial synchronous substitute or invented TTL. | +| Portable account export and tenant-admin export | Account `AA-1.3`/ADR 0050 pre-v1 export successor | The legacy account/profile read is explicitly local and not a complete portable export; the account-targeted tenant export is disabled because it exposes global fields. Enable canonical asynchronous subject export and tenant-only admin export only with owner contributions, live authority, redaction, audit and retry proof. | +| Profile tenant qualification; membership lifecycle/generation, grants, roles, delegation and JOIN abuse limits | Account `AA-1.1`/`AA-1.2` authority successor, then Unit 1B consumer | Current profile route is self-bound and membership-checked; no tenant-qualified or delegated route activates until live generation/role/grant authority, caller binding and audit proof. Unit 1B must consume the exact snapshot and prove stale-generation/private-grant/character negatives before admission readiness. | +| Issued-token registry, deterministic replay, reset/logout revocation and authentication abuse controls | Account `AA-1.3` issuer/recovery successor; Game Session `AA-2.2`/`AA-3.3` consumer in Unit 1B | Current password/email-OTP login remains available but is not registry, replay, reset-revocation or graduated-throttle complete. Before claiming those properties, implement the single-record registry, atomic issuance/replay, revocation and Account-owned limiter/outage proof; Unit 1B handles logout/reconnect consumption. Do not infer safety from OTP challenge caps or a prior binding. | +| Login-factor changes, provider linking, TOTP, safety/appeal, account switching and signing-key rotation | Account `AA-1.3` security successors | Login-factor `PUT` and unverified linking are denied; other unimplemented features are not offered as supported authority. Each activates only after its Account-owned recent-reauth/provider/security-state or validator-convergence contract and negative proof, not because this corpus section was reviewed. | +| Hosting billing owner, provider lifecycle, current-row entitlement snapshot and strict new-binding rules | Account `AA-1.4`/`AA-1.5` billing-and-entitlement successor; Unit 1B consumer | Subscription creation is disabled and zero/ambiguous rows fail retryably. Select the initial billing-owner source/consent, then prove durable provider reconciliation, one current row and complete freshness/evidence before paid hosting or new commitments activate. Exact-binding last-known-good reconnect stays undecided; no fallback is authorized. | +| Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | +| Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | + +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Its first whole-unit review has not begun; the Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. + ## Packet 4 Status and Proof Gaps - `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. @@ -33,16 +58,16 @@ 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); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [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); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql); [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); [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. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The 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. Account V29 and `AccountRepository` persist or read back the immutable unique non-nil UUID with provenance while retaining the numeric source-row id; focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled. This UUID remains storage-only and is not used in authentication outputs or downstream session carriers. 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.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current JOIN commits membership, operation outcome, and audit outbox atomically; global-only registration no longer creates membership. The strict ADR 0025 target/pointer commit gate and durable target fence remain unimplemented. Terminal replay revalidates remote scope/target/entitlement after commit or rollback without rewriting the stored outcome, but retained JOIN/scope deletion or minimization and recovery after an unknown database commit outcome remain open. V27's restrictive FK retains scopes referenced by pending or terminal JOINs; expired unreferenced scopes are swept. The cached successful connect-token path can bypass fresh authority rereads, and current-authority/postcondition revalidation, membership-authority generation propagation, and private/playtest issuance grant validation remain gaps. Subscription locking does not lock the joined billing-owner Account. PostgreSQL runtime and direct-text end-to-end proof are unclaimed; the row-lock regression skips locally without Docker. Gateway public JOIN exposure and first-party Join & Play remain unavailable. Audit-delivery recovery beyond the local outbox boundary, target five-field grant codec producer/consumer and admission propagation, monotonic grant outcomes/tombstones, expiry, tenant-scoped roles, and delegated management remain open. See [Authentication](../../architecture/system-architecture-authentication.md), [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md). | -| `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, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | -| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [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); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql); [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); [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. A verified terminal minimized receiver receipt now compacts Account's producer payload while retaining audit identity and digest; cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The 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. Account V29 and `AccountRepository` persist or read back the immutable unique non-nil UUID with provenance while retaining the numeric source-row id; focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled. This UUID remains storage-only and is not used in authentication outputs or downstream session carriers. 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.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. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rereads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to the verified caller/scope and policy evidence. It atomically persists membership, terminal operation outcome and tenant audit outbox evidence, but it does not guarantee that the exact Game Session target/catalog/pointer remains valid through Account commit: the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks only the subscription row, not its joined billing-owner Account; JOIN separately locks the caller Account and operation record. Terminal replay performs remote scope/target/entitlement checks outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting the stored outcome, while the PostgreSQL row-lock regression is Docker-skipped locally. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are now swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. The Account-owned worker rechecks only exact positive operation/scope/membership/audit evidence before terminalizing; expired scopes on retained `PENDING` intents remain pending and return retryable `AUTH_UNAVAILABLE`, with no scope reissue or terminalization for expiry, attempt limit, absent, or uncertain evidence. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unclaimed; do not mark ADR 0025 complete. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target gets retryable `AUTH_UNAVAILABLE`, while unbound private selectors keep the generic hidden projection. Text `PLAY` still requires admitting membership before its applicable Account-owned realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [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. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025/#2848. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID, and focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID, and focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this work does not complete AA-2.1, first-party `Join & Play`, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject `stateScope` values other than exact `SHARED` or `ISOLATED`. Account-owned public-production JOIN writing and Game Session direct text JOIN dispatch are implemented locally, with lifecycle-aware PLAY admission; first-party `Join & Play`, direct text-client end-to-end proof, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this work does not complete AA-2.1, first-party `Join & Play`, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject `stateScope` values other than exact `SHARED` or `ISOLATED`. Account-owned public-production JOIN writing and Game Session direct text JOIN dispatch are implemented locally. Expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence may terminalize, and absent or uncertain evidence remains readback-only and pending. The live Account membership/grant/entitlement runtime readers still fail closed before data access, so first-party `Join & Play`, direct text-client end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, complete authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -65,9 +90,9 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now 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. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. On a fresh connect-token issuance or cache miss, issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; a cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not revalidate the applicable non-public grant, so that target grant-validation proof remains a gap. 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 are implemented locally with the policy-bound v1 digest and atomic membership/audit-outbox evidence; the current Gateway guard still blocks external exposure. Game Session's direct text `JOIN` dispatch is also implemented, but first-party `Join & Play` and direct text-client end-to-end proof remain unavailable. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025/#2848. The target membership-version and authority-generation baseline reread at connect-token issuance 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). +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). -Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. +Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Every current `DeleteAccount` entry fails closed before account or financial-row mutation; provider and transfer clearance, retained-data handling, and active-subscription disposition remain prerequisites for a future deletion workflow. The Account-authorized request flow forwarded to Game Session remains target-state, not live or proved; affected operator paths remain gated. Current Game Session `/sessions*` lifecycle routes are owner-local/internal, with direct owner edge exposure denied. The canonical authorization-reference and durable owner-execution contracts are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md), [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). @@ -147,7 +172,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, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session direct text `JOIN` scope dispatch is implemented locally under #2898, while first-party `Join & Play` remains unavailable. Readback-only recovery of uncertain `PENDING` outcomes after scope expiry remains #2848 work; this revision's scope validation is not proof of that recovery. Logging receipt receiver/readback remain #2848/#2940 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, 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. - **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. @@ -156,15 +181,14 @@ Account authority proof covers account-first tenantless bootstrap authentication - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. - Signup-time login-mode selection and authenticator-app TOTP enrollment/management are not implemented; the live credential contract remains password plus email OTP. Richer MFA policy for elevated users is also future work. - Tenant membership currently persists admission permission rather than the designed tenant-role set; Account JWT issuance does not emit tenant `scopedRoles`, and realm grants have no expiry or tenant-admin management surface. -- The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. +- The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; Current `past_due` gameplay/public-join eligibility matches the accepted policy; the missing snapshot fields and freshness gates above, not this allowance, are the gaps. Durable `purchase_entitlement` fulfillment/revocation is also absent. - Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials, while public non-proxy `/ws/game/**` requires a verified connect-token context and bare `LOGIN`. - Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. - Private first-party replay is currently suppressed even if retained transcript rows remain. A safe eligible replay path and terminal `resumeContextGeneration` fence are not implemented; `LOGOUT_UNAVAILABLE` must not be mistaken for a completed logout. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. -- Account deletion currently removes payment and subscription rows after the active-billing precondition, while the canonical data-rights design retains billing/audit records for settlement and compliance. -- Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on #2848 JOIN receipt and unknown-outcome reconciliation. No universal retention duration is selected. +- Every current Account deletion entry fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation; deletion does not currently remove payment or subscription rows, and no active `hasRetainedOperation` check governs the path. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, provider/transfer clearance, and approved finite schedules remain named pre-v1 requirements. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are also unimplemented; safe disposition of retained terminal receipts and unknown outcomes depends on #2848 and the Account retention workflow under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md). The canonical data-rights design retains billing/audit records for settlement and compliance. No universal retention duration is selected. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. - The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. @@ -178,7 +202,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including the implemented `/auth/bootstrap/join` controller and local JOIN RPC; public Gateway exposure remains blocked, leave remains target-only, and Game Session direct-text JOIN dispatch is implemented locally while first-party `Join & Play` remains unavailable | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including local `JoinPublicProductionMembership` and `POST /auth/bootstrap/join`; Gateway exposure remains blocked, direct-text JOIN dispatch is local, and leave remains target-only | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index dfa5d621ff..642a7f6e1e 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout termination/generation fencing, and broader client consumption are not yet proven. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, but focused recovery proof for this suppression boundary remains incomplete. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. @@ -22,7 +22,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; durable logout termination and strict generation fencing remain incomplete. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`. Durable `resumeContextGeneration` termination/fencing and focused recovery proof remain incomplete. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, but current gameplay-role classification translates global `platformAdmin` and legacy global `god` inputs into gameplay roles contrary to ADR 0026, while payload/policy surfaces retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Remove global-role inputs from presence/capability resolution, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | @@ -49,9 +49,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` enters directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. `PlayCommandHandler` has focused unit response-classification coverage for supplied membership and entitlement/policy responses. In live composition, Account runtime membership, entitlement, and grant readers fail closed before data access; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so successful composed public `PLAY` and live `JOIN_REQUIRED` are not established. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and producer-side typed receipt validation/verified-projection marker are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, and reconnect freshness. The bounded Account worker reads back abandoned JOIN `PENDING` intents, but this does not prove runtime/recovery outcomes. Connect-token membership-authority-generation reread remains incomplete; focused Account unit coverage exercises missing-membership and policy-denial mappings. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation @@ -61,8 +61,8 @@ The current admission gaps are explicit `JOIN`, realm-scoped discovery/character ### Transcript, History, and Room Views -- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage, but the first-party connect-context replay handler currently ignores that eligibility and may replay retained rows; durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). -- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. The handler-side eligibility check owns the post-logout suppression fix; post-logout first-party replay still contradicts canonical termination behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. +- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; durable episode termination is not implemented. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. Local read suppression does not prove durable `resumeContextGeneration` termination/fencing or live recovery behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. - Current behavior: Game Logic composes ordinary floor-free `LookResult` data from World Management and Entity Management; Game Session enforces access and renders the result. Current request/proto evidence carries no causal-floor evidence, so target propagation and participant proof remain gaps linked to [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). `LOOK`, `QUICKLOOK`, movement refresh, localization, brief/color handling, and bounded error mapping are covered. The current renderer also writes disposable legacy cache values; reads remain authoritative/uncached, and this incomplete scope plus ten-minute TTL does not prove the target causal-floor/freshness contract. Combat-sensitive brief-on-move and broader world-content localization remain incomplete. ### Communication, Social, and Presence 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 c59b53b226..ebd5c70052 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The realm catalog, admission-pointer reads, bootstrap/connect-scope flow, runtime projections, and bounded direct-text [REALMS-to-JOIN handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) have local implementation. Game Session retains caller-bound Account scopes and JOIN request IDs in shared Redis, binds browse ordinals to snapshots, and invokes Account's explicit join writer; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#join-translation-and-status) own the local translation. Focused unit proof exists; the Docker-gated Redis cross-instance/retry proof was skipped locally, and full direct-text/Telnet and first-party `Join & Play` proof remains open. The current pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable; current unique bare-world-slug resolution is implementation drift from the target prohibition on bare `worldSlug` resolution. Routing remains partial: explicit `CLOSED`, consumer-wide revision convergence, canonical `{tenantId, realmId}` addressing, atomic prepared-cutover execution, and bounded active-session drain remain gaps. Public/grant policy lacks expiry, monotonic mutation outcomes/tombstones, and tenant-admin management; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for the canonical JOIN and local protocol contracts. +The realm catalog, admission-pointer reads, bootstrap/connect-scope flow, runtime projections, and bounded direct-text [REALMS-to-JOIN handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) have local implementation. Game Session retains caller-bound Account scopes and JOIN request IDs in shared Redis, binds `WORLDS` ordinals to their catalog snapshot, and uses the shared `DirectTextOrdinalSelectionResolver`; current numeric selectors fail closed when their snapshot is stale or changed. The pointer projection lacks `tenantSlug`, so the stable target `tenantSlug/worldSlug` selector is unavailable; current unique bare-world-slug resolution is implementation drift from the target prohibition on global bare `worldSlug` resolution. Focused unit proof exists; the Docker-gated Redis cross-instance/retry proof was skipped locally, and full direct-text/Telnet and first-party `Join & Play` proof remains open. Account runtime membership, entitlement, and grant handlers deny before data reads until the typed caller/target binding exists, so there is no composed live admission proof. Routing remains partial: explicit `CLOSED`, consumer-wide revision convergence, canonical `{tenantId, realmId}` addressing, atomic prepared-cutover execution, and bounded active-session drain remain gaps. Public/grant policy lacks expiry, monotonic mutation outcomes/tombstones, and tenant-admin management; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for canonical contracts. ## Packet 4 Status and Proof Gaps @@ -55,11 +55,11 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; `PLAY` admits only an exact safe active snapshot and returns actionable `JOIN_REQUIRED` only when a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing (`MISSING`) membership or existing `INACTIVE` membership. Fresh entitlement validation must also confirm gameplay availability and `allowPublicJoin`. Other non-admitting lifecycle states remain denials. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. Game Session's direct-text `JOIN` path now retrieves the retained REALMS scope/request state and invokes that Account writer; this local invocation and writer do not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account's explicit public-production membership writer and Game Session direct-text JOIN invocation are implemented locally; first-party browser JOIN remains blocked at Gateway. Game Session validates lifecycle, membership version, authority generation, caller/target identity, and freshness on supplied-authority PLAY branches, and recommends public JOIN_REQUIRED only for missing or INACTIVE membership after fresh entitlement and allowPublicJoin checks. An ACTIVE but non-admitting membership is denied. The proto's uint64 generation and incomplete Account issuance reread/private-grant validation remain implementation gaps; live Account readers fail before data access, so composed admission is unproved. Canonical admission rules belong to [Authentication](../../architecture/system-architecture-authentication.md#implementation-status); Account and Game Session implementation/proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. -The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. +The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, terminal-outcome recovery, and direct text-to-Logging proof remain unproved. Account's bounded readback-only worker for abandoned JOIN `PENDING` intents is implemented, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and complete pending-operation recovery/reconciliation remain open. This is distinct from the browser/WebSocket bootstrap snapshot. Gateway and Game Session preserve and validate `worldSlug`, `realmSlug`, `connectScopeId`, `connectRequestId`, `pointerVersion`, and resolved target in first-party connect context. The durable bootstrap shell stores the selector identity and is the reconnect/login/`PLAY` fallback when transient registry state is absent. Generic websocket bootstrap preserves an incoming complete bundle, repairs a runtime-only shell only from one complete current pointer, and collapses ambiguous or incomplete authority to no bundle. If a reused shell had a bundle and the repaired incoming shell does not, it is a real route change: the `BOOTSTRAP_ROUTE_CHANGED` path clears authenticated/gameplay state instead of preserving the older route. @@ -83,7 +83,7 @@ Remote followup persistence and projection use one normalized `{playableStateSco ### Realm-Scoped Playable State -Tenant membership and character ownership do not imply a shared gameplay namespace. Each realm carries explicit `stateScope` and `characterCreationPolicy`; shared-state realms use a tenant-live `playableStateKey`, while isolated realms, including playtest forks, use an instance-local key. `CHARS` is a realm-local roster with explicit creation policy. The scope-aware roster contract is used by bootstrap character discovery, `REALMS`, `CHARS`, `PLAY`, and `TELL`; isolated realms cannot read or mutate the tenant's production roster through tenant-wide or bare-character shortcuts. +Realm-local character discovery and creation use the selected realm's state scope and creation policy across bootstrap, `REALMS`, `CHARS`, `PLAY`, and `TELL`; isolated realms must not reach the tenant's production roster. Entity still uses legacy `playableStateKey` resolution, so stable namespace isolation remains partial and unproved. The target identity and shared-versus-isolated rules belong to [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#realm-state-model) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). For persistent/shared mutating smoke, this namespace boundary would be the mutation boundary, but the required restricted-synthetic verifier and proof remain unavailable. The bounded run-owned Compose mutation/teardown boundary is implemented, but persistent/shared identity/namespace/fence isolation remains unproved. Follow the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) for the boundary contract. @@ -95,13 +95,13 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet end-to-end proved. The evidence records focused proof for the local Account JOIN writer and direct-text scope/request handoff in addition to sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the full `WORLDS`, `REALMS`, `JOIN`, `CHARS`, and `PLAY` sequence, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, complete separated-revision consumer convergence, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. +The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet end-to-end proved. The evidence records focused proof for the local Account JOIN writer and direct-text scope/request handoff in addition to sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, and logout handling (the recorded `LOGOUT_UNAVAILABLE` case fails closed and does not prove successful logout activation), tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the full `WORLDS`, `REALMS`, `JOIN`, `CHARS`, and `PLAY` sequence, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, complete separated-revision consumer convergence, or bounded active-session drain. First-party bootstrap and local protocol proof do not establish selected-realm `PLAY`: the `Entity.ListCharactersByAccount` request and response still lack stable namespace proof; see the [Entity Management runtime/data status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). Account's bounded PENDING readback worker does not establish PostgreSQL/lost-acknowledgement proof or terminal-outcome recovery. These are historical validation facts; the decision review did not rerun them. ## Active Gaps - 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. Full end-to-end proof, PostgreSQL runtime 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. +- 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 deny before data reads, and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. Focused direct text-to-Logging end-to-end proof remains open. - 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 ff0e360ab7..aa66a4f2b4 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 @@ -39,8 +39,8 @@ These links add decision provenance and shared-runtime consequences only; capabi The following current-state findings refine the existing partial/drift status; owner documents retain the target contract details: -- `SF-1.2` / `SF-2.1`: Account creation requires a caller-provided tenant and writes an admission-enabled membership, while legacy defaults/backfill fabricated tenant membership. Global registration and explicit public-membership joining are not implemented; retained-data disposition/mapping and focused migration proof remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). -- `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` while allowing the same global account to have one profile in each tenant. Its named preflight fails closed on retained duplicate tuples without rewriting them. The PostgreSQL cases for cross-tenant reuse, same-tenant rejection, and retained-duplicate migration failure compile but were Docker-skipped, so runtime database proof and any required retained-row disposition remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +- `SF-1.2` / `SF-2.1`: Account's current implementation includes global registration and explicit public-membership `JOIN` locally (see #2847). PostgreSQL execution, pending-operation recovery, retained-row disposition, and direct text-to-Logging end-to-end proof for the registration/JOIN path remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +- `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` and its named preflight fails on retained duplicates without rewriting them. Cross-tenant reuse, same-tenant rejection, and retained-duplicate PostgreSQL cases compiled but were Docker-skipped; database proof and any required retained-row disposition remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history. Runtime entitlement reads require exactly one explicit subscription row for the tenant; zero or multiple rows return retryable `ENTITLEMENT_UNAVAILABLE`. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-2.1`: Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows with per-family deleted counts and oldest-expired-row lag. The cleanup now matches the current credential issuer/validator's process-local clock for timezone-less rows, but cross-node timezone normalization and retained-row conversion remain open. Six focused cleanup unit cases executed locally; seven PostgreSQL integration cases passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. Atomic token consumption, session revocation, and complete ADR 0163 retention classes, horizons, blockers, holds, and cross-service proof remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). This tracker records owner-local status only and does not alter the normative retention contract. @@ -119,7 +119,9 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries -Logging & Admin's typed `CreateLogEvent` RPC is present but currently returns gRPC `UNIMPLEMENTED` without invoking the legacy generic `log_events` writer, so it is not an available ingress. Target account-audit receipt/readback persistence and focused receiver proof remain unimplemented; the normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Account-creation audit delivery remains partial: the producer is still a post-commit best-effort effect rather than the target owner-local outbox, and it does not establish receiver durability or receipt confirmation; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for its current implementation, proof, and gap status. Account logging for payment uses the separate existing `LogEvent` RPC and persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. +Account's readback-only JOIN recovery requires an explicit version-1 COMMITTED receipt/projection marker plus nonblank receiver identities from the exact scoped outbox row. The Account front stays closed until the Logging receiver child supplies and proves that capability. Historical COMMITTED rows without the marker remain unverified even after receiver deployment; exact current readback and guarded evidence recording are a separate retained-data activation gate, not an inferred upgrade. + +Logging & Admin's typed `CreateLogEvent` RPC is present but currently returns gRPC `UNIMPLEMENTED` without invoking the legacy generic `log_events` writer, so it is not an available ingress. Global registration and explicit JOIN append Account-owned audit outbox entries in their local transactions, but durable receiver receipt/projection and exact readback are supplied by the separate child; delivery and recovery remain gated until that capability and PostgreSQL/end-to-end proof are established. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the separate existing `LogEvent` RPC and persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). diff --git a/dev-tools/README.md b/dev-tools/README.md index 4b113c1f64..699f4efdb2 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -45,7 +45,7 @@ The `pr-review`, `report-worktree-pr-topology.sh`, and `maintenance/cloc-report. - `restores/` – restore, state-reset, and external-credential validation helpers; see `restores/README.md` for the script map. - `smoke/` – shared smoke defaults and the run-owned Compose claim/capability helper. - `seed/` – local and test data seeding helpers. -- `tests/` – contract tests for repo-owned tooling. +- `tests/` – contract tests for repo-owned tooling, including [account-workload-namespace-contract.sh](tests/account-workload-namespace-contract.sh) for offline Account Helm namespace binding and `extraEnv` preservation/collision proof. - `validation/` – repo policy and static validation scripts used by Gradle and CI. The documentation lock is sourced from the unpinned direct roots in `config/docs/requirements.in` and generated into `config/docs/requirements.txt` with the repository Python version and `pip-compile --allow-unsafe --generate-hashes --index-url=https://pypi.org/simple --output-file=config/docs/requirements.txt config/docs/requirements.in`. The existing lock seeds compilation and preserves satisfying package pins unless you explicitly request an upgrade. When the installed pip-tools version mis-serializes its default index options into an unsupported header, set `CUSTOM_COMPILE_COMMAND` to that exact command so the generated header remains parseable. Keep the source roots and lock hashes in sync; do not edit lock hashes manually. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index 9a5b79dd34..5d019e9f67 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,9 +7,10 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. The Account, Game Session, and Entity Management leaves support the canonical local Compose gameplay proof, while the remaining local Compose services may use the shared development leaf. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. -- Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. -- `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. -- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, Entity Management, and World Management receive distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. This is local Compose wiring only; hosted deployments continue to use their separate certificate issuer. The remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. -- The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last. Ordinary `docker/docker-compose.override.yml` remains the plaintext local debugging profile. Hosted certificate provisioning is separate: hosted runtime namespaces receive cert-manager-issued standalone workload leaves and never mount the local CA private key. -- `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. +- When the complete generic bundle already exists, the generator validates the CA/key pair, shared client/server leaves and key pairs, trust, purposes, local SANs, and `dev-*` aliases. Invalid existing material fails closed without changing or rotating the CA or issued leaves; diagnose it or deliberately back up/discard the generated set before reissuing. The cleanup helper removes only its listed files and known workload/projection paths, preserving and reporting unexpected files and symlinks. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. Workload keys remain mode `0600`; `ensure-dev-certs.sh` changes permissions only in its ignored local runtime projection. Hosted preview and dev-demo use issuer-projected runtime leaves, not this local signing path. +- Standalone hosted runs keep the legacy shared bundle for other gRPC workloads and use eight cert-manager-issued `firemud-grpc-` runtime-facing leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. Runtime namespaces contain no CA private key; missing or invalid issuer-projected leaves fail closed. +- Default `dev-tools/certs/ensure-dev-certs.sh` validates the local CA and shared material, then prepares the canonical local Compose entrypoints with distinct Account, Game Session, and Social Groups workload identities under the ignored `local-runtime/` projection. It contains runtime-facing material only, never `ca.key`; the host CA key remains mode `0600`. +- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the canonical smoke fixture beneath the active run-owned Compose state directory. The authority directory remains host-only with mode `0700`, and its CA private key remains mode `0600`; each of eleven Java application containers gets a read-only `/app/certs` mount with only its leaf key, certificate, and public CA. Account, Game Session, Entity Management, Social Groups, and World Management get distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. Other services use the shared local development leaf. Retain the fixture while its exact Compose project may restart, and remove it only after that project is torn down. +- The ordinary `docker/docker-compose.override.yml` and local-images profile use the default local mTLS projection; the three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last to use their separate run-owned smoke fixture. Hosted certificate provisioning is separate and never mounts the local CA private key. +- `dev-tools/certs/clean-dev-certs.sh` removes only its listed top-level files and known workload-leaf/runtime-projection paths, removing directories only when empty; unexpected files and symlinks are preserved and reported. diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 3139c39eb0..1d939ed51d 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" # Remove generated certificates so tooling can start from scratch without # deleting the tracked helper scripts in dev-tools/certs/. @@ -12,11 +12,75 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "Refusing symlinked $description; preserving it: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + +refuse_symlink_path "$CERT_DIR" "certificate directory" if [ ! -d "$CERT_DIR" ]; then echo "No certificate directory at $CERT_DIR" exit 0 fi +removed_any=false +preserved_any=false + +report_preserved() { + echo "Preserving unexpected certificate entry: $1" >&2 + preserved_any=true +} + +remove_known_file() { + local path="$1" + if [[ -L "$path" ]]; then + report_preserved "$path (symlink)" + elif [[ -f "$path" ]]; then + rm -- "$path" + removed_any=true + elif [[ -e "$path" ]]; then + report_preserved "$path (not a regular file)" + fi +} + +report_directory_contents() { + local directory="$1" + local path + while IFS= read -r -d '' path; do + report_preserved "$path" + done < <(find "$directory" -mindepth 1 -print0) +} + +remove_empty_directory() { + local directory="$1" + if [[ -L "$directory" ]]; then + report_preserved "$directory (symlink directory)" + elif [[ -d "$directory" ]]; then + if rmdir -- "$directory" 2>/dev/null; then + removed_any=true + else + preserved_any=true + echo "Preserving non-empty or inaccessible certificate directory: $directory" >&2 + report_directory_contents "$directory" + fi + elif [[ -e "$directory" ]]; then + report_preserved "$directory (not a directory)" + fi +} + generated_files=( ca.crt ca.key @@ -32,16 +96,70 @@ generated_files=( dev-cert.cnf ) -removed_any=false for filename in "${generated_files[@]}"; do - if [ -e "$CERT_DIR/$filename" ]; then - rm -f "$CERT_DIR/$filename" - removed_any=true - fi + remove_known_file "$CERT_DIR/$filename" done +workloads=(account-service game-session-service social-groups-service) +workload_dir="$CERT_DIR/workloads" +if [[ -L "$workload_dir" ]]; then + report_preserved "$workload_dir (symlink directory)" +elif [[ -d "$workload_dir" ]]; then + for workload in "${workloads[@]}"; do + remove_known_file "$workload_dir/$workload.crt" + remove_known_file "$workload_dir/$workload.key" + done + remove_empty_directory "$workload_dir" +elif [[ -e "$workload_dir" ]]; then + report_preserved "$workload_dir (not a directory)" +fi + +runtime_root="$CERT_DIR/local-runtime" +runtime_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) +if [[ -L "$runtime_root" ]]; then + report_preserved "$runtime_root (symlink directory)" +elif [[ -d "$runtime_root" ]]; then + profiles=(default "${workloads[@]}") + for profile in "${profiles[@]}"; do + profile_dir="$runtime_root/$profile" + if [[ -L "$profile_dir" ]]; then + report_preserved "$profile_dir (symlink directory)" + continue + elif [[ ! -d "$profile_dir" ]]; then + if [[ -e "$profile_dir" ]]; then + report_preserved "$profile_dir (not a directory)" + fi + continue + fi + + if [[ "$profile" != "default" ]]; then + leaf_dir="$profile_dir/workloads" + if [[ -L "$leaf_dir" ]]; then + report_preserved "$leaf_dir (symlink directory)" + elif [[ -d "$leaf_dir" ]]; then + remove_known_file "$leaf_dir/$profile.crt" + remove_known_file "$leaf_dir/$profile.key" + remove_empty_directory "$leaf_dir" + elif [[ -e "$leaf_dir" ]]; then + report_preserved "$leaf_dir (not a directory)" + fi + fi + + for filename in "${runtime_files[@]}"; do + remove_known_file "$profile_dir/$filename" + done + remove_empty_directory "$profile_dir" + done + remove_empty_directory "$runtime_root" +elif [[ -e "$runtime_root" ]]; then + report_preserved "$runtime_root (not a directory)" +fi + if [ "$removed_any" = true ]; then - echo "Removed generated certificates from $CERT_DIR" -else + echo "Removed known generated certificates from $CERT_DIR" +fi +if [ "$preserved_any" = true ]; then + echo "Unexpected entries were preserved; inspect the paths reported above." +elif [ "$removed_any" = false ]; then echo "No generated certificates found in $CERT_DIR" fi diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index cf11b756c0..f40151d47a 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -1,9 +1,72 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" CERT_DIR="${1:-$SCRIPT_DIR}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" +WORKLOAD_NAMESPACE="local" +WORKLOAD_DIR="$CERT_DIR/workloads" +RUNTIME_DIR="$CERT_DIR/local-runtime" + +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "refusing symlinked $description: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + +preflight_managed_file() { + local path="$1" + local description="$2" + local link_count + + refuse_symlink_path "$path" "$description" + [[ -e "$path" ]] || return 0 + [[ -f "$path" ]] || { + echo "refusing non-regular $description: $path" >&2 + exit 1 + } + link_count="$(stat -c '%h' -- "$path")" + if ((link_count > 1)); then + echo "refusing hard-linked $description: $path" >&2 + exit 1 + fi +} + +preflight_managed_directory() { + local path="$1" + local description="$2" + + refuse_symlink_path "$path" "$description" + if [[ -e "$path" && ! -d "$path" ]]; then + echo "refusing non-directory $description: $path" >&2 + exit 1 + fi +} + +certificate_matches_private_key() { + local certificate="$1" + local private_key="$2" + local certificate_public_key private_key_public_key + + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null)" || return 1 + [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] +} + COMPOSE_MTLS_STAGE_ROOT="" COMPOSE_MTLS_STAGE_DIR="" COMPOSE_MTLS_LEAF_STAGE_DIR="" @@ -79,7 +142,7 @@ ensure_compose_mtls_certs() { return 1 fi - local owner_id authority_dir workloads_dir service + local owner_id authority_dir workloads_dir service authority_mode_restored=0 owner_id="$(id -u)" if [[ ! -d "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" || -L "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" ]]; then echo "run-owned smoke ownership directory is unavailable." >&2 @@ -101,28 +164,59 @@ ensure_compose_mtls_certs() { echo "Compose mTLS authority path must be a real directory." >&2 return 1 fi - chmod 700 "$authority_dir" - if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then - echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 - return 1 - fi + preflight_managed_directory "$authority_dir" "Compose mTLS authority directory" + local authority_file + for authority_file in ca.crt ca.key client.crt client.key; do + preflight_managed_file "$authority_dir/$authority_file" "Compose mTLS authority material" + done if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then if [[ -n "$(find "$authority_dir" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then echo "Compose mTLS authority fixture is incomplete; refusing to replace existing material." >&2 return 1 fi + fi + if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then (umask 077; "$GENERATOR" "$authority_dir") + # The generic generator makes the bundle directory container-readable. + # Compose authority material must remain private on its first generation too. + chmod 700 "$authority_dir" + if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 + return 1 + fi + authority_mode_restored=1 fi - local authority_file for authority_file in ca.crt ca.key client.crt client.key; do - if [[ -L "$authority_dir/$authority_file" || ! -f "$authority_dir/$authority_file" ]]; then + preflight_managed_file "$authority_dir/$authority_file" "Compose mTLS authority material" + if [[ ! -f "$authority_dir/$authority_file" ]]; then echo "Compose mTLS authority fixture is missing a regular $authority_file file." >&2 return 1 fi done + if ! openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null 2>&1; then + echo "Compose mTLS shared client certificate does not verify under authority CA." >&2 + return 1 + fi + if ! certificate_matches_private_key "$authority_dir/client.crt" "$authority_dir/client.key"; then + echo "Compose mTLS shared client certificate and private key do not match." >&2 + return 1 + fi + local authority_san_output authority_uri_sans + authority_san_output="$(openssl x509 -in "$authority_dir/client.crt" -noout -ext subjectAltName)" + authority_uri_sans="$(printf '%s\n' "$authority_san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ -n "$authority_uri_sans" ]]; then + echo "Compose mTLS shared client certificate must not contain a workload URI SAN." >&2 + return 1 + fi + if ((authority_mode_restored == 0)); then + chmod 700 "$authority_dir" + if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 + return 1 + fi + fi chmod 600 "$authority_dir/ca.key" "$authority_dir/client.key" chmod 644 "$authority_dir/ca.crt" "$authority_dir/client.crt" - openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null workloads_dir="$requested_root/workloads" local -a services=( @@ -144,7 +238,11 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service ]]; then + if [[ "$service" == account-service \ + || "$service" == game-session-service \ + || "$service" == entity-management-service \ + || "$service" == social-groups-service \ + || "$service" == world-management-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -208,16 +306,36 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 return 1 fi - for service in account-service game-session-service entity-management-service world-management-service; do - local san_output + for service in \ + account-service game-session-service entity-management-service social-groups-service world-management-service; do + local san_output uri_sans san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" - if [[ "$san_output" != *"URI:spiffe://firemud/ns/dev/sa/$service"* ]]; then + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ "$uri_sans" != "URI:spiffe://firemud/ns/dev/sa/$service" \ + || "$san_output" != *"DNS:$service"* ]]; then if [[ "$service" != world-management-service ]] \ || ! migrate_legacy_world_management_leaf \ "$requested_root" "$authority_dir" "$workloads_dir/$service"; then echo "Compose mTLS workload has the wrong SPIFFE identity: $service" >&2 return 1 fi + san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ "$uri_sans" != "URI:spiffe://firemud/ns/dev/sa/$service" \ + || "$san_output" != *"DNS:$service"* ]]; then + echo "Compose mTLS workload has the wrong SPIFFE identity: $service" >&2 + return 1 + fi + fi + done + for service in \ + gateway automation-scripting-service game-design-service game-logic-service logging-admin-service tcp-proxy-service; do + local san_output uri_sans + san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ -n "$uri_sans" ]]; then + echo "Compose mTLS shared generic workload must not contain a URI SAN: $service" >&2 + return 1 fi done fi @@ -235,28 +353,200 @@ if [[ "${1:-}" == "--compose-mtls" ]]; then exit $? fi -required_files=( - "$CERT_DIR/ca.crt" - "$CERT_DIR/client.crt" - "$CERT_DIR/client.key" - "$CERT_DIR/dev-ca.pem" - "$CERT_DIR/dev-cert.pem" - "$CERT_DIR/dev-key.pem" - "$CERT_DIR/server.crt" - "$CERT_DIR/server.key" +managed_source_files=( + ca.crt ca.key ca.srl client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem + server.crt server.key server.csr dev-cert.cnf ) -missing=0 -for file in "${required_files[@]}"; do - if [[ ! -f "$file" ]]; then - missing=1 - break - fi +preflight_managed_directory "$CERT_DIR" "certificate directory" +for filename in "${managed_source_files[@]}"; do + preflight_managed_file "$CERT_DIR/$filename" "certificate material" done -if [[ "$missing" == "0" ]]; then - echo "Development certificates already exist in $CERT_DIR" - exit 0 +preflight_managed_directory "$WORKLOAD_DIR" "workload certificate directory" +for workload in account-service game-session-service social-groups-service; do + preflight_managed_file "$WORKLOAD_DIR/$workload.crt" "workload certificate output" + preflight_managed_file "$WORKLOAD_DIR/$workload.key" "workload private-key output" +done + +refuse_symlink_path "$RUNTIME_DIR" "local Compose runtime projection" +if [[ -d "$WORKLOAD_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlinked workload certificate path: $symlink_path" >&2 + exit 1 + done < <(find -P "$WORKLOAD_DIR" -mindepth 1 -maxdepth 1 -type l -print0) +fi +if [[ -d "$RUNTIME_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlink in local Compose runtime projection: $symlink_path" >&2 + exit 1 + done < <(find -P "$RUNTIME_DIR" -mindepth 1 -type l -print0) fi +# Route complete bundles through the generator's read-only validation path as +# well as routing missing bundles through its existing generation path. "$GENERATOR" "$CERT_DIR" +chmod 600 "$CERT_DIR/ca.key" + +workloads=(account-service game-session-service social-groups-service) +mkdir -p "$WORKLOAD_DIR" +chmod 700 "$WORKLOAD_DIR" + +workload_certificate_is_valid() { + local workload="$1" + local certificate="$WORKLOAD_DIR/$workload.crt" + local private_key="$WORKLOAD_DIR/$workload.key" + local expected_uri="spiffe://firemud/ns/$WORKLOAD_NAMESPACE/sa/$workload" + local subject_alt_names uri_sans + + [[ -f "$certificate" && -f "$private_key" ]] || return 1 + openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 + openssl verify -purpose sslserver -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)" || return 1 + uri_sans="$(printf '%s\n' "$subject_alt_names" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:$expected_uri" && "$subject_alt_names" == *"DNS:$workload"* ]] || return 1 + certificate_matches_private_key "$certificate" "$private_key" +} + +for workload in "${workloads[@]}"; do + certificate="$WORKLOAD_DIR/$workload.crt" + private_key="$WORKLOAD_DIR/$workload.key" + if ! workload_certificate_is_valid "$workload"; then + "$GENERATOR" --workload "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" \ + "$certificate" "$private_key" "$WORKLOAD_NAMESPACE" "$workload" + fi + workload_certificate_is_valid "$workload" || { + echo "local workload certificate failed identity, key-match, or CA validation: $workload" >&2 + exit 1 + } +done + +# Keep host-side workload keys private. Readability is granted only to the +# per-service runtime projection copied below; the generic generator output +# remains mode 0600. +chmod 700 "$WORKLOAD_DIR" +for workload in "${workloads[@]}"; do + chmod 644 "$WORKLOAD_DIR/$workload.crt" + chmod 600 "$WORKLOAD_DIR/$workload.key" +done + +# Mount only runtime material. Protected callers receive their own leaf, not +# the other protected services' private keys. No projection includes ca.key. +runtime_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) +runtime_profiles=(default "${workloads[@]}") +if [[ -e "$RUNTIME_DIR" || -L "$RUNTIME_DIR" ]]; then + [[ ! -L "$RUNTIME_DIR" && -d "$RUNTIME_DIR" ]] || { + echo "refusing symlink or non-directory local Compose runtime projection: $RUNTIME_DIR" >&2 + exit 1 + } + while IFS= read -r -d '' existing_path; do + [[ ! -L "$existing_path" ]] || { + echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 + exit 1 + } + profile_name="${existing_path##*/}" + approved=false + for profile in "${runtime_profiles[@]}"; do + if [[ "$profile_name" == "$profile" && -d "$existing_path" ]]; then + approved=true + break + fi + done + [[ "$approved" == "true" ]] || { + echo "refusing unapproved entry in local Compose runtime projection: $profile_name" >&2 + exit 1 + } + done < <(find "$RUNTIME_DIR" -mindepth 1 -maxdepth 1 -print0) +fi + +# Preflight every existing destination across all profiles before any +# projection directory chmod or file copy can mutate an aliased inode. +for profile in "${runtime_profiles[@]}"; do + profile_dir="$RUNTIME_DIR/$profile" + [[ ! -L "$profile_dir" ]] || { + echo "refusing symlink in local Compose runtime projection: $profile_dir" >&2 + exit 1 + } + if [[ -e "$profile_dir" && ! -d "$profile_dir" ]]; then + echo "refusing unapproved entry in local Compose runtime projection: $profile_dir" >&2 + exit 1 + fi + [[ -d "$profile_dir" ]] || continue + + expected_profile_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) + if [[ "$profile" != "default" ]]; then + if [[ -L "$profile_dir/workloads" ]]; then + echo "refusing symlink in local Compose runtime projection: $profile_dir/workloads" >&2 + exit 1 + fi + if [[ -e "$profile_dir/workloads" && ! -d "$profile_dir/workloads" ]]; then + echo "refusing unapproved file in local Compose runtime projection: $profile/workloads" >&2 + exit 1 + fi + expected_profile_files+=(workloads "workloads/$profile.crt" "workloads/$profile.key") + fi + + while IFS= read -r -d '' existing_path; do + [[ ! -L "$existing_path" ]] || { + echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 + exit 1 + } + relative_path="${existing_path#"$profile_dir"/}" + approved=false + for expected_path in "${expected_profile_files[@]}"; do + if [[ "$relative_path" == "$expected_path" ]]; then + if [[ "$expected_path" == "workloads" ]]; then + [[ -d "$existing_path" ]] && approved=true + else + [[ -f "$existing_path" ]] && approved=true + fi + break + fi + done + [[ "$approved" == "true" ]] || { + echo "refusing unapproved file in local Compose runtime projection: $profile/$relative_path" >&2 + exit 1 + } + if [[ -f "$existing_path" ]]; then + link_count="$(stat -c '%h' -- "$existing_path")" + if ((link_count > 1)); then + echo "refusing hard-linked file in local Compose runtime projection: $existing_path" >&2 + exit 1 + fi + fi + done < <(find "$profile_dir" -mindepth 1 -print0) +done + +# The complete existing projection passed preflight, so directory setup and +# copy/chmod operations can now proceed without changing unrelated hard links. +if [[ ! -d "$RUNTIME_DIR" ]]; then + mkdir -m 700 -- "$RUNTIME_DIR" +fi +chmod 700 -- "$RUNTIME_DIR" +for workload in "${workloads[@]}"; do + mkdir -p "$RUNTIME_DIR/$workload/workloads" +done + +for profile in "${runtime_profiles[@]}"; do + profile_dir="$RUNTIME_DIR/$profile" + mkdir -p "$profile_dir" + chmod 755 "$profile_dir" + if [[ "$profile" != "default" ]]; then + chmod 755 "$profile_dir/workloads" + fi + for file in "${runtime_files[@]}"; do + [[ -f "$CERT_DIR/$file" ]] || { + echo "missing runtime certificate material: $CERT_DIR/$file" >&2 + exit 1 + } + cp "$CERT_DIR/$file" "$profile_dir/$file" + done + if [[ "$profile" != "default" ]]; then + cp "$WORKLOAD_DIR/$profile.crt" "$profile_dir/workloads/$profile.crt" + cp "$WORKLOAD_DIR/$profile.key" "$profile_dir/workloads/$profile.key" + chmod 644 "$profile_dir/workloads/$profile.crt" "$profile_dir/workloads/$profile.key" + fi + chmod 644 "$profile_dir"/*.crt "$profile_dir"/*.key "$profile_dir"/*.pem +done + +echo "Development certificates and local Compose workload identities are ready in $CERT_DIR" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 0a31711bf9..a24728e1b7 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -1,7 +1,58 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" + +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "refusing symlinked $description: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + +preflight_managed_file() { + local path="$1" + local description="$2" + local link_count + + refuse_symlink_path "$path" "$description" + [[ -e "$path" ]] || return 0 + [[ -f "$path" ]] || { + echo "refusing non-regular $description: $path" >&2 + exit 1 + } + link_count="$(stat -c '%h' -- "$path")" + if ((link_count > 1)); then + echo "refusing hard-linked $description: $path" >&2 + exit 1 + fi +} + +preflight_managed_directory() { + local path="$1" + local description="$2" + + refuse_symlink_path "$path" "$description" + if [[ -e "$path" && ! -d "$path" ]]; then + echo "refusing non-directory $description: $path" >&2 + exit 1 + fi +} + +paths_are_same_file() { + [[ "$1" == "$2" ]] || { [[ -e "$1" && -e "$2" ]] && [[ "$1" -ef "$2" ]]; } +} if [[ "${1:-}" == "--workload" ]]; then umask 077 @@ -16,6 +67,19 @@ if [[ "${1:-}" == "--workload" ]]; then output_key="$5" runtime_namespace="$6" workload="$7" + preflight_managed_file "$ca_cert" "certificate authority source" + preflight_managed_file "$ca_key" "certificate authority source" + preflight_managed_file "$output_cert" "workload certificate output" + preflight_managed_file "$output_key" "workload private-key output" + if paths_are_same_file "$ca_cert" "$ca_key" \ + || paths_are_same_file "$output_cert" "$output_key" \ + || paths_are_same_file "$output_cert" "$ca_cert" \ + || paths_are_same_file "$output_cert" "$ca_key" \ + || paths_are_same_file "$output_key" "$ca_cert" \ + || paths_are_same_file "$output_key" "$ca_key"; then + echo "certificate authority sources and workload outputs must be distinct paths." >&2 + exit 1 + fi for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 @@ -87,7 +151,148 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi -if [ -f "$CERT_DIR/dev-cert.pem" ] && [ -f "$CERT_DIR/dev-key.pem" ] && [ -f "$CERT_DIR/dev-ca.pem" ]; then +generated_files=( + ca.crt ca.key ca.srl client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem + server.crt server.key server.csr dev-cert.cnf +) +preflight_managed_directory "$CERT_DIR" "certificate directory" +for filename in "${generated_files[@]}"; do + preflight_managed_file "$CERT_DIR/$filename" "certificate material" +done +if [[ -d "$CERT_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlinked certificate material: $symlink_path" >&2 + exit 1 + done < <(find -P "$CERT_DIR" -mindepth 1 -maxdepth 1 -type l \( \ + -name '*.crt' -o -name '*.key' -o -name '*.pem' -o -name '*.srl' -o -name '*.csr' \ + -o -name 'dev-cert.cnf' \ + \) -print0) +fi + +generic_bundle_files=( + ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key +) +local_service_dns_names=( + localhost account-service automation-scripting-service entity-management-service + game-design-service game-logic-service game-session-service logging-admin-service + social-groups-service spring-cloud-gateway tcp-proxy-service world-management-service +) + +certificate_matches_private_key() { + local certificate="$1" + local private_key="$2" + local certificate_public_key private_key_public_key + + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout 2>/dev/null \ + | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null)" || return 1 + [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] +} + +validate_existing_leaf() { + local certificate="$1" + local private_key="$2" + local description="$3" + local purpose subject_alt_names dns_name san_pattern + + if ! openssl x509 -in "$certificate" -noout >/dev/null 2>&1; then + echo "existing local $description certificate is malformed: $certificate" >&2 + return 1 + fi + if ! openssl x509 -in "$certificate" -checkend 0 -noout >/dev/null 2>&1; then + echo "existing local $description certificate is expired or expires now: $certificate" >&2 + return 1 + fi + for purpose in sslclient sslserver; do + if ! openssl verify -purpose "$purpose" -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1; then + echo "existing local $description certificate does not verify for $purpose under ca.crt: $certificate" >&2 + return 1 + fi + done + if ! certificate_matches_private_key "$certificate" "$private_key"; then + echo "existing local $description certificate and private key do not match: $certificate / $private_key" >&2 + return 1 + fi + if ! subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)"; then + echo "existing local $description certificate has no readable subject alternative names: $certificate" >&2 + return 1 + fi + if [[ "$subject_alt_names" == *"URI:"* ]]; then + echo "existing local generic $description certificate must not contain a workload URI SAN: $certificate" >&2 + return 1 + fi + for dns_name in "${local_service_dns_names[@]}"; do + san_pattern="DNS:${dns_name}([,[:space:]]|$)" + if [[ ! "$subject_alt_names" =~ $san_pattern ]]; then + echo "existing local $description certificate is missing the expected DNS SAN $dns_name: $certificate" >&2 + return 1 + fi + done + if [[ "$subject_alt_names" != *"IP Address:127.0.0.1"* ]]; then + echo "existing local $description certificate is missing the expected loopback IP SAN: $certificate" >&2 + return 1 + fi +} + +validate_existing_generic_bundle() { + local ca_cert="$CERT_DIR/ca.crt" + local ca_key="$CERT_DIR/ca.key" + + if ! openssl x509 -in "$ca_cert" -noout >/dev/null 2>&1; then + echo "existing local certificate authority certificate is malformed: $ca_cert" >&2 + return 1 + fi + if ! openssl x509 -in "$ca_cert" -checkend 0 -noout >/dev/null 2>&1; then + echo "existing local certificate authority certificate is expired or expires now: $ca_cert" >&2 + return 1 + fi + if ! openssl verify -check_ss_sig -CAfile "$ca_cert" "$ca_cert" >/dev/null 2>&1; then + echo "existing local certificate authority is not a valid trusted self-signed certificate: $ca_cert" >&2 + return 1 + fi + if ! certificate_matches_private_key "$ca_cert" "$ca_key"; then + echo "existing local certificate authority certificate and private key do not match: $ca_cert / $ca_key" >&2 + return 1 + fi + + if ! validate_existing_leaf "$CERT_DIR/server.crt" "$CERT_DIR/server.key" "server"; then + return 1 + fi + if ! validate_existing_leaf "$CERT_DIR/client.crt" "$CERT_DIR/client.key" "client"; then + return 1 + fi + + if ! cmp -s "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem"; then + echo "existing local legacy CA alias does not match ca.crt: $CERT_DIR/dev-ca.pem" >&2 + return 1 + fi + if ! cmp -s "$CERT_DIR/client.crt" "$CERT_DIR/dev-cert.pem"; then + echo "existing local legacy certificate alias does not match client.crt: $CERT_DIR/dev-cert.pem" >&2 + return 1 + fi + if ! cmp -s "$CERT_DIR/client.key" "$CERT_DIR/dev-key.pem"; then + echo "existing local legacy private-key alias does not match client.key: $CERT_DIR/dev-key.pem" >&2 + return 1 + fi +} + +bundle_present=true +for filename in "${generic_bundle_files[@]}"; do + if [[ ! -f "$CERT_DIR/$filename" ]]; then + bundle_present=false + break + fi +done + +if [[ "$bundle_present" == "true" ]]; then + if ! validate_existing_generic_bundle; then + echo "Existing local certificate bundle is invalid in $CERT_DIR; no files were changed and the CA or issued leaves were not rotated." >&2 + echo "Back up this local certificate set, then deliberately reissue it with:" >&2 + printf ' %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + printf ' %q %q\n' "$SCRIPT_DIR/generate-dev-certs.sh" "$CERT_DIR" >&2 + exit 1 + fi echo "Dev certificates already exist in $CERT_DIR" exit 0 fi @@ -152,9 +357,11 @@ rm -f "$CERT_DIR"/*.csr "$CERT_DIR"/*.srl rm -f "$CERT_DIR/dev-cert.cnf" # Containers run as a non-root application user in CI and local Docker. -# Make the generated development certificates world-readable so bind mounts -# remain readable inside the container regardless of host UID/GID. +# Keep the CA private key host-only. Runtime containers use the CA certificate +# and leaf keys from the local-runtime projection prepared by ensure-dev-certs. +# The shared client/server keys remain readable for non-root local containers. chmod 755 "$CERT_DIR" -chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/*.key "$CERT_DIR"/*.pem +chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/client.key "$CERT_DIR"/server.key "$CERT_DIR"/*.pem +chmod 600 "$CERT_DIR/ca.key" echo "Certificates generated in $(cd "$CERT_DIR" && pwd)" 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/account-workload-namespace-contract.sh b/dev-tools/tests/account-workload-namespace-contract.sh new file mode 100644 index 0000000000..c1de7ece44 --- /dev/null +++ b/dev-tools/tests/account-workload-namespace-contract.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/account-service" +TEMP_DIR="$(mktemp -d)" +trap 'rm -rf -- "$TEMP_DIR"' EXIT + +if ! command -v helm >/dev/null 2>&1; then + echo "helm is required to render the Account workload namespace contract" >&2 + exit 1 +fi + +DEFAULT_RENDER="$TEMP_DIR/default.yaml" +CUSTOM_RENDER="$TEMP_DIR/custom.yaml" +COLLISION_RENDER="$TEMP_DIR/collision.yaml" + +helm template account-default "$CHART_DIR" --namespace default >"$DEFAULT_RENDER" +helm template account-custom "$CHART_DIR" \ + --namespace pr-2848 \ + --set-string extraEnv.ORDINARY_SETTING=preserved \ + >"$CUSTOM_RENDER" + +python3 - "$DEFAULT_RENDER" "$CUSTOM_RENDER" <<'PY' +import pathlib +import sys + +import yaml + + +def account_environment(path): + documents = [ + document + for document in yaml.safe_load_all(pathlib.Path(path).read_text(encoding="utf-8")) + if isinstance(document, dict) + ] + deployment = next( + ( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "account-service" + ), + None, + ) + if deployment is None: + raise SystemExit(f"{path}: rendered Account Deployment is missing") + containers = deployment.get("spec", {}).get("template", {}).get("spec", {}).get("containers", []) + account = next( + (container for container in containers if container.get("name") == "account-service"), + None, + ) + if account is None: + raise SystemExit(f"{path}: rendered Account container is missing") + return account.get("env", []) + + +for path in sys.argv[1:]: + env = account_environment(path) + matches = [entry for entry in env if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE"] + if len(matches) != 1: + raise SystemExit( + f"{path}: expected exactly one FIREMUD_GRPC_WORKLOAD_NAMESPACE entry, found {len(matches)}" + ) + expected = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } + if matches[0] != expected: + raise SystemExit(f"{path}: workload namespace is not sourced from metadata.namespace: {matches[0]}") + +custom_env = account_environment(sys.argv[2]) +ordinary = [entry for entry in custom_env if entry.get("name") == "ORDINARY_SETTING"] +if ordinary != [{"name": "ORDINARY_SETTING", "value": "preserved"}]: + raise SystemExit(f"custom render did not preserve extraEnv: {ordinary}") +PY + +if helm template account-collision "$CHART_DIR" \ + --namespace pr-2848 \ + --set-string extraEnv.FIREMUD_GRPC_WORKLOAD_NAMESPACE=forged \ + >"$COLLISION_RENDER" 2>"$TEMP_DIR/collision.err"; then + echo "Account chart accepted a controller-owned workload namespace override" >&2 + exit 1 +fi +if ! grep -Fq 'extraEnv must not set controller-owned FIREMUD_GRPC_WORKLOAD_NAMESPACE' "$TEMP_DIR/collision.err"; then + echo "Account chart collision failed for an unexpected reason" >&2 + cat "$TEMP_DIR/collision.err" >&2 + exit 1 +fi 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/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index ec83082f6c..7f94ac38d3 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -22,20 +22,115 @@ ensure_compose_mtls_fixture() { } ensure_compose_mtls_fixture -ensure_compose_mtls_fixture - +[[ "$(stat -c '%a' "$fixture_root/authority")" == 700 ]] || { + echo "first Compose mTLS certificate setup did not retain owner-only authority permissions." >&2 + exit 1 +} services=( account-service gateway automation-scripting-service entity-management-service game-design-service game-logic-service game-session-service logging-admin-service social-groups-service tcp-proxy-service world-management-service ) workloads_dir="$fixture_root/workloads" + +snapshot_workloads() { + find "$workloads_dir" -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a %h' "$file")" + sha256sum -- "$file" + done +} + +workloads_before_idempotent_readback="$(snapshot_workloads)" +ensure_compose_mtls_fixture +[[ "$workloads_before_idempotent_readback" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS certificate verification changed an existing valid fixture." >&2 + exit 1 +} + [[ "$(stat -c '%a' "$fixture_root")" == 700 ]] [[ "$(stat -c '%a' "$fixture_root/authority")" == 700 ]] [[ "$(stat -c '%a' "$fixture_root/authority/ca.key")" == 600 ]] [[ ! -e "$workloads_dir/ca.key" ]] [[ -z "$(find "$workloads_dir" -type f -name ca.key -print -quit)" ]] +snapshot_tree() { + local tree_root="$1" + find "$tree_root" -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s %s ' "$(stat -c '%a %h' "$file")" "${file#"$tree_root"/}" + sha256sum -- "$file" + done +} + +# A CA-valid dedicated workload leaf in the shared authority slot is an +# accidental misprojection. Reject it before chmod or workload projection. +misplaced_authority_run_id="${run_id}-misplaced-authority" +misplaced_authority_project_name="firemud-smoke-$misplaced_authority_run_id" +misplaced_authority_project_key="$(printf '%s' "$misplaced_authority_project_name" | sha256sum | awk '{print $1}')" +misplaced_authority_root="$ownership_dir/$misplaced_authority_project_key.grpc-mtls" +misplaced_authority_dir="$misplaced_authority_root/authority" +mkdir -m 700 -- "$misplaced_authority_root" +mkdir -m 755 -- "$misplaced_authority_dir" +cp -- "$fixture_root/authority/ca.crt" "$misplaced_authority_dir/ca.crt" +cp -- "$fixture_root/authority/ca.key" "$misplaced_authority_dir/ca.key" +cp -- "$workloads_dir/game-session-service/client.crt" "$misplaced_authority_dir/client.crt" +cp -- "$workloads_dir/game-session-service/client.key" "$misplaced_authority_dir/client.key" +chmod 644 "$misplaced_authority_dir/ca.crt" "$misplaced_authority_dir/client.crt" +chmod 600 "$misplaced_authority_dir/ca.key" +# Noncanonical client-key mode proves refusal precedes authority-file chmod. +chmod 444 "$misplaced_authority_dir/client.key" +misplaced_authority_before="$(snapshot_tree "$misplaced_authority_root")" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$misplaced_authority_run_id" \ + COMPOSE_PROJECT_NAME="$misplaced_authority_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$misplaced_authority_root" \ + >"$TEST_ROOT/misplaced-authority-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a dedicated leaf in the shared authority slot." >&2 + exit 1 +fi +rg -Fq 'shared client certificate must not contain a workload URI SAN' "$TEST_ROOT/misplaced-authority-output" +[[ "$misplaced_authority_before" == "$(snapshot_tree "$misplaced_authority_root")" \ + && "$(stat -c '%a' "$misplaced_authority_dir")" == 755 \ + && ! -e "$misplaced_authority_root/workloads" ]] || { + echo "Compose mTLS source-identity refusal changed authority material or created workload projections." >&2 + exit 1 +} + +# Existing generic projections receive the same no-URI-SAN check, with all +# files left untouched when a dedicated certificate was placed in one. +misplaced_projection_run_id="${run_id}-misplaced-projection" +misplaced_projection_project_name="firemud-smoke-$misplaced_projection_run_id" +misplaced_projection_project_key="$(printf '%s' "$misplaced_projection_project_name" | sha256sum | awk '{print $1}')" +misplaced_projection_root="$ownership_dir/$misplaced_projection_project_key.grpc-mtls" +mkdir -m 700 -- "$misplaced_projection_root" +cp -a -- "$fixture_root/authority" "$misplaced_projection_root/authority" +cp -a -- "$workloads_dir" "$misplaced_projection_root/workloads" +chmod 644 "$misplaced_projection_root/workloads/gateway/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.key" +cp -- "$workloads_dir/game-session-service/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.crt" +cp -- "$workloads_dir/game-session-service/client.key" \ + "$misplaced_projection_root/workloads/gateway/client.key" +chmod 444 "$misplaced_projection_root/workloads/gateway/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.key" +misplaced_projection_before="$(snapshot_tree "$misplaced_projection_root")" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$misplaced_projection_run_id" \ + COMPOSE_PROJECT_NAME="$misplaced_projection_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$misplaced_projection_root" \ + >"$TEST_ROOT/misplaced-projection-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a dedicated leaf in a generic workload projection." >&2 + exit 1 +fi +rg -Fq 'shared generic workload must not contain a URI SAN: gateway' "$TEST_ROOT/misplaced-projection-output" +[[ "$misplaced_projection_before" == "$(snapshot_tree "$misplaced_projection_root")" ]] || { + echo "Compose mTLS generic-identity refusal partially changed an existing workload projection." >&2 + exit 1 +} + symlink_run_id="${run_id}-symlink" symlink_project_name="firemud-smoke-$symlink_run_id" symlink_project_key="$(printf '%s' "$symlink_project_name" | sha256sum | awk '{print $1}')" @@ -55,6 +150,58 @@ if FIREMUD_SMOKE_TEST_MODE=1 \ fi rg -Fq 'Compose mTLS workloads path must be a real directory.' "$TEST_ROOT/symlink-output" +authority_hardlink_run_id="${run_id}-authority-hardlink" +authority_hardlink_project_name="firemud-smoke-$authority_hardlink_run_id" +authority_hardlink_project_key="$(printf '%s' "$authority_hardlink_project_name" | sha256sum | awk '{print $1}')" +authority_hardlink_fixture="$ownership_dir/$authority_hardlink_project_key.grpc-mtls" +authority_hardlink_dir="$authority_hardlink_fixture/authority" +authority_hardlink_key="$authority_hardlink_dir/ca.key" +authority_hardlink_sentinel="$authority_hardlink_dir/ca-key-alias-sentinel" +mkdir -m 700 -- "$authority_hardlink_fixture" +mkdir -m 711 -- "$authority_hardlink_dir" +for file in ca.crt ca.key client.crt client.key; do + cp -- "$fixture_root/authority/$file" "$authority_hardlink_dir/$file" +done +cp -- "$authority_hardlink_key" "$authority_hardlink_sentinel" +chmod 640 "$authority_hardlink_sentinel" +rm -- "$authority_hardlink_key" +ln -- "$authority_hardlink_sentinel" "$authority_hardlink_key" + +snapshot_authority_sources() { + find "$authority_hardlink_dir" -maxdepth 1 -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a %h' "$file")" + sha256sum -- "$file" + done +} + +authority_before_hardlink_refusal="$(snapshot_authority_sources)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$authority_hardlink_run_id" \ + COMPOSE_PROJECT_NAME="$authority_hardlink_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$authority_hardlink_fixture" \ + >"$TEST_ROOT/authority-hardlink-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a hard-linked authority key." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked Compose mTLS authority material: $authority_hardlink_key" \ + "$TEST_ROOT/authority-hardlink-output" +[[ "$authority_before_hardlink_refusal" == "$(snapshot_authority_sources)" \ + && "$(stat -c '%a' "$authority_hardlink_dir")" == 711 \ + && ! -e "$authority_hardlink_fixture/workloads" ]] || { + echo "Compose mTLS authority preflight partially changed hard-linked source material." >&2 + exit 1 +} +[[ "$(<"$authority_hardlink_sentinel")" == "$(<"$fixture_root/authority/ca.key")" ]] || { + echo "Compose mTLS authority preflight changed the hard-link sentinel contents." >&2 + exit 1 +} +[[ "$(stat -c '%a' "$authority_hardlink_sentinel")" == 640 ]] || { + echo "Compose mTLS authority preflight changed the hard-link sentinel mode." >&2 + exit 1 +} + public_key_digest() { local cert_or_key="$1" kind="$2" if [[ "$kind" == certificate ]]; then @@ -183,20 +330,25 @@ for service in "${services[@]}"; do done identity_services=( - account-service game-session-service entity-management-service world-management-service + account-service game-session-service entity-management-service social-groups-service world-management-service ) declare -A identity_fingerprints=() for service in "${identity_services[@]}"; do echo "Checking exact workload identity: $service" san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" - [[ "$san_output" == *"URI:spiffe://firemud/ns/dev/sa/$service"* ]] + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:spiffe://firemud/ns/dev/sa/$service" \ + && "$san_output" == *"DNS:$service"* ]] identity_fingerprints["$service"]="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -fingerprint -sha256)" done -for ((left = 0; left < ${#identity_services[@]}; left++)); do - for ((right = left + 1; right < ${#identity_services[@]}; right++)); do - left_service="${identity_services[$left]}" - right_service="${identity_services[$right]}" - [[ "${identity_fingerprints[$left_service]}" != "${identity_fingerprints[$right_service]}" ]] +for ((i = 0; i < ${#identity_services[@]}; i++)); do + for ((j = i + 1; j < ${#identity_services[@]}; j++)); do + left="${identity_services[$i]}" + right="${identity_services[$j]}" + [[ "${identity_fingerprints[$left]}" != "${identity_fingerprints[$right]}" ]] || { + echo "Compose mTLS workloads share a private identity: $left and $right" >&2 + exit 1 + } done done echo "Checking canonical Compose entrypoints." @@ -332,7 +484,14 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; cp "$ROOT_DIR/.env.sample" "$compose_fixture/docker/compose.env" cp "$ROOT_DIR/.env.sample" "$compose_fixture/.env" - rendered_config="$TEST_ROOT/compose-config.json" + rendered_source_config="$TEST_ROOT/compose-source-config.json" + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" \ + docker compose --env-file "$compose_fixture/.env" \ + -f "$compose_fixture/docker/docker-compose.yml" \ + -f "$compose_fixture/docker/docker-compose.override.yml" \ + -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ + config --format json >"$rendered_source_config" + rendered_image_config="$TEST_ROOT/compose-image-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false \ @@ -342,57 +501,111 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; -f "$compose_fixture/docker/docker-compose.override.yml" \ -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ - config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" <<'PY' + config --format json >"$rendered_image_config" + python3 - "$rendered_source_config" "$rendered_image_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" <<'PY' import json import pathlib import sys -config_path, cert_root, capability_source = sys.argv[1:] -config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) -services = config["services"] +source_config_path, image_config_path, cert_root, capability_source = sys.argv[1:] app_names = { "account-service", "gateway", "automation-scripting-service", "entity-management-service", "game-design-service", "game-logic-service", "game-session-service", "logging-admin-service", "social-groups-service", "tcp-proxy-service", "world-management-service", } -for name in app_names: - service = services[name] - environment = service.get("environment", {}) - assert environment.get("FIREMUD_GRPC_PLAINTEXT") == "false", name - assert environment.get("GRPC_SERVER_TLS_ENABLED") == "true", name - assert environment.get("FIREMUD_GRPC_CERT_CHAIN_PATH") == "/app/certs/client.crt", name - assert environment.get("FIREMUD_GRPC_PRIVATE_KEY_PATH") == "/app/certs/client.key", name - assert environment.get("FIREMUD_GRPC_CA_CERT_PATH") == "/app/certs/ca.crt", name - mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == "/app/certs"] - assert len(mounts) == 1, name - assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (name, mounts[0]) - assert mounts[0].get("read_only") is True, name - assert service.get("build") is None, f"image-only proof must not build {name}" -entity_namespace = services["entity-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert entity_namespace == "dev", entity_namespace -wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert wms_namespace == "dev", wms_namespace -game_session = services["game-session-service"] -game_session_environment = game_session["environment"] -assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" -assert game_session_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" -assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" -capability_path = "/app/run-owned-initial-admission-capability.json" -assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path -capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] -assert len(capability_mounts) == 1, capability_mounts -assert capability_mounts[0]["source"] == capability_source, capability_mounts[0] -assert capability_mounts[0].get("read_only") is True -for name, service in services.items(): - if name != "game-session-service": - assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name -assert services["account-service"]["image"].endswith(":contract") -print("Verified Compose mTLS wiring and image-only service configuration.") +for profile, config_path, image_only in ( + ("source", source_config_path, False), + ("images", image_config_path, True), +): + services = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8"))["services"] + for name in app_names: + service = services[name] + environment = service.get("environment", {}) + assert environment.get("FIREMUD_GRPC_PLAINTEXT") == "false", (profile, name) + assert environment.get("GRPC_SERVER_TLS_ENABLED") == "true", (profile, name) + assert environment.get("FIREMUD_GRPC_CERT_CHAIN_PATH") == "/app/certs/client.crt", (profile, name) + assert environment.get("FIREMUD_GRPC_PRIVATE_KEY_PATH") == "/app/certs/client.key", (profile, name) + assert environment.get("FIREMUD_GRPC_CA_CERT_PATH") == "/app/certs/ca.crt", (profile, name) + mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == "/app/certs"] + assert len(mounts) == 1, (profile, name) + assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (profile, name, mounts[0]) + assert mounts[0].get("read_only") is True, (profile, name) + assert "/authority" not in mounts[0]["source"], (profile, name, mounts[0]) + if image_only: + assert service.get("build") is None, f"image-only proof must not build {name}" + + for name in ("account-service", "entity-management-service", "social-groups-service", "world-management-service"): + namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") + assert namespace == "dev", (profile, name, namespace) + if image_only: + assert services["account-service"]["image"].endswith(":contract") + game_session_environment = services["game-session-service"]["environment"] + assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" + assert game_session_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" + assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" + capability_path = "/app/run-owned-initial-admission-capability.json" + assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path + game_session = services["game-session-service"] + capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] + assert len(capability_mounts) == 1, capability_mounts + assert capability_mounts[0]["source"] == capability_source, capability_mounts[0] + assert capability_mounts[0].get("read_only") is True + for name, service in services.items(): + if name != "game-session-service": + assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name +print("Verified source and image Compose mTLS wiring and workload identities.") PY else echo "Docker Compose unavailable; skipped rendered-configuration assertion." fi +social_groups_key="$workloads_dir/social-groups-service/client.key" +social_groups_key_backup="$TEST_ROOT/social-groups-client-key.backup" +cp -- "$social_groups_key" "$social_groups_key_backup" +chmod 644 "$social_groups_key" +cp -- "$workloads_dir/account-service/client.key" "$social_groups_key" +chmod 444 "$social_groups_key" +mismatched_key_snapshot="$(snapshot_workloads)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$run_id" \ + COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" \ + >"$TEST_ROOT/mismatched-key-output" 2>&1; then + echo "Compose mTLS certificate verification accepted a mismatched certificate/key pair." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload certificate and private key do not match: social-groups-service' \ + "$TEST_ROOT/mismatched-key-output" +[[ "$mismatched_key_snapshot" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS verification changed an existing mismatched fixture." >&2 + exit 1 +} +chmod 644 "$social_groups_key" +cp -- "$social_groups_key_backup" "$social_groups_key" +chmod 444 "$social_groups_key" + +social_groups_leaf="$workloads_dir/social-groups-service/client.crt" +chmod 644 "$social_groups_leaf" "$social_groups_key" +cp -- "$workloads_dir/account-service/client.crt" "$social_groups_leaf" +cp -- "$workloads_dir/account-service/client.key" "$social_groups_key" +chmod 444 "$social_groups_leaf" "$social_groups_key" +wrong_leaf_snapshot="$(snapshot_workloads)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$run_id" \ + COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" \ + >"$TEST_ROOT/wrong-leaf-output" 2>&1; then + echo "Compose mTLS certificate verification accepted the Account leaf for Social Groups." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload has the wrong SPIFFE identity: social-groups-service' \ + "$TEST_ROOT/wrong-leaf-output" +[[ "$wrong_leaf_snapshot" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS certificate verification changed an existing wrong-identity fixture." >&2 + exit 1 +} + echo "Compose gRPC mTLS certificate and wiring contract passed." diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh new file mode 100644 index 0000000000..6aa4b54066 --- /dev/null +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -0,0 +1,799 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CERT_DIR="$(mktemp -d)" +trap 'rm -rf "$CERT_DIR"' EXIT +generic_bundle_files=( + ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key +) + +assert_mode() { + local expected_mode="$1" + local path="$2" + local actual_mode + actual_mode="$(stat -c '%a' "$path")" + [[ "$actual_mode" == "$expected_mode" ]] || { + echo "expected mode $expected_mode for $path, got $actual_mode" >&2 + exit 1 + } +} + +copy_generic_bundle() { + local source_dir="$1" + local target_dir="$2" + mkdir -p "$target_dir" + for file in "${generic_bundle_files[@]}"; do + cp "$source_dir/$file" "$target_dir/$file" + done +} + +assert_invalid_existing_bundle_is_preserved() { + local bundle_dir="$1" + local case_name="$2" + local manifest="$CERT_DIR/$case_name.bundle.sha256" + local output="$CERT_DIR/$case_name.output" + local unmanaged_file="$bundle_dir/unmanaged-local.key" + local file + + printf 'unmanaged certificate sentinel\n' >"$unmanaged_file" + chmod 640 "$unmanaged_file" + for file in "${generic_bundle_files[@]}"; do + sha256sum "$bundle_dir/$file" + done >"$manifest" + sha256sum "$unmanaged_file" >>"$manifest" + + if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$bundle_dir" >"$output" 2>&1; then + echo "generate-dev-certs accepted an invalid complete bundle: $case_name" >&2 + exit 1 + fi + rg -Fq 'no files were changed' "$output" || { + echo "generate-dev-certs did not report fail-closed preservation for $case_name" >&2 + cat "$output" >&2 + exit 1 + } + sha256sum -c "$manifest" >/dev/null || { + echo "generate-dev-certs changed invalid bundle material: $case_name" >&2 + exit 1 + } + + if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$bundle_dir" >"$output" 2>&1; then + echo "ensure-dev-certs accepted an invalid complete bundle: $case_name" >&2 + exit 1 + fi + rg -Fq 'no files were changed' "$output" || { + echo "ensure-dev-certs did not report fail-closed preservation for $case_name" >&2 + cat "$output" >&2 + exit 1 + } + sha256sum -c "$manifest" >/dev/null || { + echo "ensure-dev-certs changed invalid bundle material: $case_name" >&2 + exit 1 + } + [[ "$(<"$unmanaged_file")" == 'unmanaged certificate sentinel' ]] || { + echo "an invalid bundle path changed or removed an unmanaged file: $case_name" >&2 + exit 1 + } + assert_mode 640 "$unmanaged_file" +} + +# Defaults derived from a copied checkout must use its physical path even +# when each helper is invoked through a symlinked checkout ancestor. +default_path_fixture="$CERT_DIR/default-path-fixture" +default_path_checkout="$default_path_fixture/checkout" +default_path_alias="$default_path_fixture/checkout-alias" +mkdir -p "$default_path_checkout/dev-tools/certs" +for helper in ensure-dev-certs.sh generate-dev-certs.sh clean-dev-certs.sh; do + cp "$ROOT_DIR/dev-tools/certs/$helper" "$default_path_checkout/dev-tools/certs/$helper" +done +ln -s "$default_path_checkout" "$default_path_alias" +default_path_cert_dir="$default_path_checkout/dev-tools/certs" +default_path_alias_cert_dir="$default_path_alias/dev-tools/certs" +bash "$default_path_alias_cert_dir/generate-dev-certs.sh" +[[ -f "$default_path_cert_dir/ca.crt" && -f "$default_path_cert_dir/server.crt" ]] || { + echo "default certificate generation did not write into the copied physical checkout" >&2 + exit 1 +} +bash "$default_path_alias_cert_dir/ensure-dev-certs.sh" +[[ -f "$default_path_cert_dir/local-runtime/default/client.crt" ]] || { + echo "default certificate setup did not write into the copied physical checkout" >&2 + exit 1 +} +bash "$default_path_alias_cert_dir/clean-dev-certs.sh" +[[ ! -e "$default_path_cert_dir/ca.crt" \ + && ! -e "$default_path_cert_dir/local-runtime" \ + && ! -e "$default_path_cert_dir/workloads" ]] || { + echo "default certificate cleanup did not clean the copied physical checkout" >&2 + exit 1 +} + +assert_workload_certificate() { + local workload="$1" + local certificate="$CERT_DIR/local-runtime/$workload/workloads/$workload.crt" + local private_key="$CERT_DIR/local-runtime/$workload/workloads/$workload.key" + local subject_alt_names uri_sans extended_key_usage expected_uri certificate_public_key private_key_public_key + expected_uri="spiffe://firemud/ns/local/sa/$workload" + + openssl verify -purpose sslclient -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null + openssl verify -purpose sslserver -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName)" + uri_sans="$(printf '%s\n' "$subject_alt_names" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:$expected_uri" \ + && "$subject_alt_names" == *"DNS:$workload"* \ + && "$subject_alt_names" == *"DNS:$workload.local"* \ + && "$subject_alt_names" == *"DNS:$workload.local.svc"* \ + && "$subject_alt_names" == *"DNS:$workload.local.svc.cluster.local"* ]] || { + echo "workload certificate has incorrect SANs: $workload" >&2 + printf '%s\n' "$subject_alt_names" >&2 + exit 1 + } + extended_key_usage="$(openssl x509 -in "$certificate" -noout -ext extendedKeyUsage)" + [[ "$extended_key_usage" == *"TLS Web Server Authentication"* \ + && "$extended_key_usage" == *"TLS Web Client Authentication"* ]] || { + echo "workload certificate does not support both gRPC mTLS roles: $workload" >&2 + exit 1 + } + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER | openssl dgst -sha256)" + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER | openssl dgst -sha256)" + [[ "$certificate_public_key" == "$private_key_public_key" ]] || { + echo "workload certificate and private key do not match: $workload" >&2 + exit 1 + } +} + +assert_no_uri_san() { + local certificate="$1" + local subject_alt_names + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName)" + if [[ "$subject_alt_names" == *"URI:"* ]]; then + echo "generic local certificate unexpectedly contains a workload URI SAN: $certificate" >&2 + exit 1 + fi +} + +assert_invalid_workload_uri_is_reissued() { + local case_name="$1" + local subject_alt_name="$2" + local certificate="$CERT_DIR/workloads/account-service.crt" + local private_key="$CERT_DIR/workloads/account-service.key" + local fixture_dir="$CERT_DIR/workload-uri-$case_name" + local config="$fixture_dir/extensions.cnf" + local request="$fixture_dir/workload.csr" + local before_fingerprint after_fingerprint certificate_public_key private_key_public_key + mkdir -p "$fixture_dir" + openssl req -new -key "$private_key" -subj "/CN=firemud-grpc-account-service" \ + -out "$request" >/dev/null 2>&1 + printf '%s\n' \ + '[leaf]' \ + 'basicConstraints=critical,CA:FALSE' \ + 'keyUsage=critical,digitalSignature,keyEncipherment' \ + 'extendedKeyUsage=serverAuth,clientAuth' \ + "subjectAltName=$subject_alt_name" \ + >"$config" + openssl x509 -req -in "$request" -CA "$CERT_DIR/ca.crt" -CAkey "$CERT_DIR/ca.key" \ + -set_serial "0x$(openssl rand -hex 16)" -out "$certificate" -days 30 -sha256 \ + -extfile "$config" -extensions leaf >/dev/null 2>&1 + + # Keep CA trust, both mTLS usages, and key pairing valid so only the URI identity is wrong. + openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null + openssl verify -purpose sslserver -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER | openssl dgst -sha256)" + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER \ + | openssl dgst -sha256)" + [[ "$certificate_public_key" == "$private_key_public_key" ]] || { + echo "invalid URI fixture does not match the account-service key: $case_name" >&2 + exit 1 + } + + before_fingerprint="$(openssl x509 -in "$certificate" -noout -fingerprint -sha256 | cut -d= -f2)" + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" + after_fingerprint="$(openssl x509 -in "$certificate" -noout -fingerprint -sha256 | cut -d= -f2)" + [[ "$after_fingerprint" != "$before_fingerprint" ]] || { + echo "ensure-dev-certs retained an incorrect workload URI identity: $case_name" >&2 + exit 1 + } + assert_workload_certificate account-service +} + +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" + +assert_no_uri_san "$CERT_DIR/client.crt" +assert_no_uri_san "$CERT_DIR/server.crt" + +runtime_dir="$CERT_DIR/local-runtime" +[[ -z "$(find "$runtime_dir" -name ca.key -print -quit)" ]] || { + echo "CA private key was copied into the Compose runtime projection" >&2 + exit 1 +} +assert_mode 600 "$CERT_DIR/ca.key" +assert_mode 700 "$CERT_DIR/workloads" +assert_mode 700 "$runtime_dir" +for profile in default account-service game-session-service social-groups-service; do + assert_mode 755 "$runtime_dir/$profile" + assert_mode 644 "$runtime_dir/$profile/client.key" + assert_mode 644 "$runtime_dir/$profile/server.key" + assert_mode 644 "$runtime_dir/$profile/dev-key.pem" +done +for workload in account-service game-session-service social-groups-service; do + assert_mode 644 "$CERT_DIR/workloads/$workload.crt" + assert_mode 600 "$CERT_DIR/workloads/$workload.key" + assert_mode 755 "$runtime_dir/$workload/workloads" + assert_mode 644 "$runtime_dir/$workload/workloads/$workload.key" +done + +# A hard-linked managed projection destination must be rejected before any +# other profile's projection is copied or chmodded. +hardlink_case="$CERT_DIR/hardlink-projection-case" +copy_generic_bundle "$CERT_DIR" "$hardlink_case" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$hardlink_case" +hardlink_runtime="$hardlink_case/local-runtime" +hardlink_target="$hardlink_runtime/social-groups-service/workloads/social-groups-service.key" +hardlink_sentinel="$hardlink_case/runtime-projection-alias-sentinel.txt" +hardlink_output="$CERT_DIR/hardlink-projection-output" +hardlink_before="$CERT_DIR/hardlink-projection-before.sha256" +hardlink_after="$CERT_DIR/hardlink-projection-after.sha256" + +snapshot_runtime_projection() { + local root="$1" + local file + while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a %h' "$file")" + sha256sum -- "$file" + done < <(find "$root" -type f -print0 | sort -z) +} + +# A repeat ensure restores the private outer projection boundary without +# changing the directly mounted files or their container-readable modes. +runtime_projection_before="$(snapshot_runtime_projection "$runtime_dir")" +chmod 755 "$runtime_dir" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" +runtime_projection_after="$(snapshot_runtime_projection "$runtime_dir")" +[[ "$runtime_projection_before" == "$runtime_projection_after" ]] || { + echo "idempotent certificate setup changed runtime projection files or modes" >&2 + exit 1 +} +assert_mode 700 "$runtime_dir" + +snapshot_certificate_tree() { + local root="$1" + local file + while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a' "$file")" + sha256sum -- "$file" + done < <(find "$root" -type f -print0 | sort -z) +} + +printf 'external hard-link sentinel\n' >"$hardlink_sentinel" +chmod 640 "$hardlink_sentinel" +rm -- "$hardlink_target" +ln -- "$hardlink_sentinel" "$hardlink_target" +snapshot_runtime_projection "$hardlink_runtime" >"$hardlink_before" + +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$hardlink_case" >"$hardlink_output" 2>&1; then + echo "ensure-dev-certs accepted a hard-linked local runtime projection file" >&2 + exit 1 +fi +rg -Fq "refusing hard-linked file in local Compose runtime projection: $hardlink_target" \ + "$hardlink_output" || { + echo "ensure-dev-certs did not identify the hard-linked projection path" >&2 + cat "$hardlink_output" >&2 + exit 1 +} +snapshot_runtime_projection "$hardlink_runtime" >"$hardlink_after" +cmp -s "$hardlink_before" "$hardlink_after" || { + echo "ensure-dev-certs partially changed the local runtime projection before refusal" >&2 + exit 1 +} +[[ "$(<"$hardlink_sentinel")" == 'external hard-link sentinel' ]] || { + echo "ensure-dev-certs changed an external hard-link sentinel" >&2 + exit 1 +} +assert_mode 640 "$hardlink_sentinel" + +# Ensure preflights every managed source before the generic CA-key chmod or a +# missing workload-pair regeneration can alter either side of a hard link. +source_hardlink_case="$CERT_DIR/hardlink-source-case" +copy_generic_bundle "$CERT_DIR" "$source_hardlink_case" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$source_hardlink_case" +source_hardlink_key="$source_hardlink_case/workloads/game-session-service.key" +source_hardlink_certificate="$source_hardlink_case/workloads/game-session-service.crt" +source_hardlink_sentinel="$source_hardlink_case/source-key-alias-sentinel" +source_hardlink_output="$CERT_DIR/hardlink-source-output" +printf 'external source-key sentinel\n' >"$source_hardlink_sentinel" +chmod 640 "$source_hardlink_sentinel" +rm -- "$source_hardlink_key" "$source_hardlink_certificate" +ln -- "$source_hardlink_sentinel" "$source_hardlink_key" +chmod 644 "$source_hardlink_case/ca.key" +source_hardlink_before="$(snapshot_certificate_tree "$source_hardlink_case")" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$source_hardlink_case" \ + >"$source_hardlink_output" 2>&1; then + echo "ensure-dev-certs accepted a hard-linked workload source key." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked workload private-key output: $source_hardlink_key" \ + "$source_hardlink_output" +[[ "$source_hardlink_before" == "$(snapshot_certificate_tree "$source_hardlink_case")" \ + && "$(<"$source_hardlink_sentinel")" == 'external source-key sentinel' ]] || { + echo "ensure-dev-certs partially changed a hard-linked workload source or another managed file." >&2 + exit 1 +} +assert_mode 640 "$source_hardlink_sentinel" +assert_mode 644 "$source_hardlink_case/ca.key" + +# The standalone generic generator must reject a hard-linked output before an +# incomplete bundle can rotate or overwrite any of its remaining material. +generator_hardlink_case="$CERT_DIR/generator-hardlink-case" +copy_generic_bundle "$CERT_DIR" "$generator_hardlink_case" +generator_hardlink_key="$generator_hardlink_case/server.key" +generator_hardlink_sentinel="$generator_hardlink_case/server-key-alias-sentinel" +generator_hardlink_output="$CERT_DIR/generator-hardlink-output" +cp -- "$generator_hardlink_key" "$generator_hardlink_sentinel" +chmod 640 "$generator_hardlink_sentinel" +rm -- "$generator_hardlink_key" "$generator_hardlink_case/dev-key.pem" +ln -- "$generator_hardlink_sentinel" "$generator_hardlink_key" +generator_hardlink_before="$(snapshot_certificate_tree "$generator_hardlink_case")" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$generator_hardlink_case" \ + >"$generator_hardlink_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked managed certificate output." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked certificate material: $generator_hardlink_key" \ + "$generator_hardlink_output" +[[ "$generator_hardlink_before" == "$(snapshot_certificate_tree "$generator_hardlink_case")" ]] || { + echo "generate-dev-certs partially changed an incomplete hard-linked bundle." >&2 + exit 1 +} +assert_mode 640 "$generator_hardlink_sentinel" + +# The standalone workload signer preflights both read-only CA inputs and its +# certificate/key outputs before it creates either output. +workload_source_case="$CERT_DIR/generator-workload-source-case" +mkdir -p "$workload_source_case/output" +cp -- "$CERT_DIR/ca.crt" "$workload_source_case/ca.crt" +cp -- "$CERT_DIR/ca.key" "$workload_source_case/ca-key-sentinel" +chmod 640 "$workload_source_case/ca-key-sentinel" +ln -- "$workload_source_case/ca-key-sentinel" "$workload_source_case/ca.key" +workload_source_before="$(snapshot_certificate_tree "$workload_source_case")" +workload_source_output="$CERT_DIR/generator-workload-source-output" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$workload_source_case/ca.crt" "$workload_source_case/ca.key" \ + "$workload_source_case/output/client.crt" "$workload_source_case/output/client.key" \ + local account-service >"$workload_source_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked workload CA source." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked certificate authority source: $workload_source_case/ca.key" \ + "$workload_source_output" +[[ "$workload_source_before" == "$(snapshot_certificate_tree "$workload_source_case")" \ + && ! -e "$workload_source_case/output/client.crt" \ + && ! -e "$workload_source_case/output/client.key" ]] || { + echo "generate-dev-certs partially changed output after rejecting a hard-linked CA source." >&2 + exit 1 +} +assert_mode 640 "$workload_source_case/ca-key-sentinel" + +workload_output_case="$CERT_DIR/generator-workload-output-case" +mkdir -p "$workload_output_case/ca" "$workload_output_case/output" +cp -- "$CERT_DIR/ca.crt" "$workload_output_case/ca/ca.crt" +cp -- "$CERT_DIR/ca.key" "$workload_output_case/ca/ca.key" +workload_output_sentinel="$workload_output_case/output/key-alias-sentinel" +workload_output_key="$workload_output_case/output/client.key" +printf 'external workload-output sentinel\n' >"$workload_output_sentinel" +chmod 640 "$workload_output_sentinel" +ln -- "$workload_output_sentinel" "$workload_output_key" +workload_output_before="$(snapshot_certificate_tree "$workload_output_case")" +workload_output_output="$CERT_DIR/generator-workload-output-output" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$workload_output_case/ca/ca.crt" "$workload_output_case/ca/ca.key" \ + "$workload_output_case/output/client.crt" "$workload_output_key" \ + local account-service >"$workload_output_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked workload private-key output." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked workload private-key output: $workload_output_key" \ + "$workload_output_output" +[[ "$workload_output_before" == "$(snapshot_certificate_tree "$workload_output_case")" \ + && ! -e "$workload_output_case/output/client.crt" \ + && "$(<"$workload_output_sentinel")" == 'external workload-output sentinel' ]] || { + echo "generate-dev-certs partially changed a hard-linked workload output." >&2 + exit 1 +} +assert_mode 640 "$workload_output_sentinel" + +# Present managed paths must be regular files, not directories or other +# special entries that a later generator would partially replace. +invalid_kind_case="$CERT_DIR/non-regular-source-case" +copy_generic_bundle "$CERT_DIR" "$invalid_kind_case" +rm -- "$invalid_kind_case/ca.crt" +mkdir -- "$invalid_kind_case/ca.crt" +invalid_kind_before="$(snapshot_certificate_tree "$invalid_kind_case")" +invalid_kind_output="$CERT_DIR/non-regular-source-output" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$invalid_kind_case" \ + >"$invalid_kind_output" 2>&1; then + echo "ensure-dev-certs accepted a non-regular managed certificate path." >&2 + exit 1 +fi +rg -Fq "refusing non-regular certificate material: $invalid_kind_case/ca.crt" \ + "$invalid_kind_output" +[[ "$invalid_kind_before" == "$(snapshot_certificate_tree "$invalid_kind_case")" \ + && -d "$invalid_kind_case/ca.crt" ]] || { + echo "ensure-dev-certs partially changed an invalid managed source path." >&2 + exit 1 +} + +# Unmanaged regular files under workloads/ retain their own bytes and modes; +# only the three named local Compose identities are normalized by ensure. +mode_case="$CERT_DIR/unmanaged-workload-modes" +copy_generic_bundle "$CERT_DIR" "$mode_case" +mkdir -p "$mode_case/workloads" +printf 'unmanaged certificate sentinel\n' >"$mode_case/workloads/keep-me.crt" +printf 'unmanaged key sentinel\n' >"$mode_case/workloads/keep-me.key" +chmod 711 "$mode_case/workloads/keep-me.crt" +chmod 640 "$mode_case/workloads/keep-me.key" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$mode_case" +[[ "$(<"$mode_case/workloads/keep-me.crt")" == 'unmanaged certificate sentinel' \ + && "$(<"$mode_case/workloads/keep-me.key")" == 'unmanaged key sentinel' ]] || { + echo "ensure-dev-certs changed unmanaged workload certificate contents" >&2 + exit 1 +} +assert_mode 711 "$mode_case/workloads/keep-me.crt" +assert_mode 640 "$mode_case/workloads/keep-me.key" + +# Complete but unhealthy bundles fail closed through both public entrypoints. +# Their CA and issued leaves are left byte-for-byte unchanged for deliberate +# operator diagnosis or full local reissue. +malformed_case="$CERT_DIR/invalid-malformed-bundle" +copy_generic_bundle "$CERT_DIR" "$malformed_case" +printf 'malformed certificate\n' >"$malformed_case/ca.crt" +assert_invalid_existing_bundle_is_preserved "$malformed_case" malformed + +key_mismatch_case="$CERT_DIR/invalid-key-mismatch-bundle" +copy_generic_bundle "$CERT_DIR" "$key_mismatch_case" +cp "$CERT_DIR/workloads/account-service.key" "$key_mismatch_case/client.key" +cp "$key_mismatch_case/client.key" "$key_mismatch_case/dev-key.pem" +assert_invalid_existing_bundle_is_preserved "$key_mismatch_case" key-mismatch + +other_authority="$CERT_DIR/other-authority" +bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$other_authority" >/dev/null + +# An invalid shared client leaf in the run-owned Compose authority fixture +# fails closed with a bounded certificate diagnostic. +compose_mtls_run_id="invalid-client-cert-${BASHPID}" +compose_mtls_project="firemud-smoke-$compose_mtls_run_id" +compose_mtls_ownership="$CERT_DIR/compose-mtls-ownership" +compose_mtls_project_key="$(printf '%s' "$compose_mtls_project" | sha256sum | awk '{print $1}')" +compose_mtls_fixture="$compose_mtls_ownership/$compose_mtls_project_key.grpc-mtls" +mkdir -m 700 -- "$compose_mtls_ownership" + +ensure_owned_compose_mtls_fixture() { + FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$compose_mtls_ownership" \ + FIREMUD_SMOKE_RUN_ID="$compose_mtls_run_id" \ + COMPOSE_PROJECT_NAME="$compose_mtls_project" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$compose_mtls_fixture" +} + +ensure_owned_compose_mtls_fixture >/dev/null +cp -- "$other_authority/client.crt" "$compose_mtls_fixture/authority/client.crt" +chmod 644 "$compose_mtls_fixture/authority/client.crt" +compose_mtls_invalid_output="$CERT_DIR/invalid-compose-mtls-client.output" +if ensure_owned_compose_mtls_fixture >"$compose_mtls_invalid_output" 2>&1; then + echo "ensure-dev-certs accepted an untrusted Compose mTLS shared client certificate" >&2 + exit 1 +fi +rg -Fq 'Compose mTLS shared client certificate does not verify under authority CA.' \ + "$compose_mtls_invalid_output" || { + echo "ensure-dev-certs did not report the untrusted Compose mTLS shared client certificate" >&2 + cat "$compose_mtls_invalid_output" >&2 + exit 1 +} + +wrong_issuer_case="$CERT_DIR/invalid-wrong-issuer-bundle" +copy_generic_bundle "$CERT_DIR" "$wrong_issuer_case" +for file in server.crt server.key client.crt client.key dev-cert.pem dev-key.pem; do + cp "$other_authority/$file" "$wrong_issuer_case/$file" +done +assert_invalid_existing_bundle_is_preserved "$wrong_issuer_case" wrong-issuer + +misplaced_workload_case="$CERT_DIR/invalid-generic-workload-identity-bundle" +copy_generic_bundle "$CERT_DIR" "$misplaced_workload_case" +cp "$CERT_DIR/workloads/game-session-service.crt" "$misplaced_workload_case/client.crt" +cp "$CERT_DIR/workloads/game-session-service.key" "$misplaced_workload_case/client.key" +cp "$misplaced_workload_case/client.crt" "$misplaced_workload_case/dev-cert.pem" +cp "$misplaced_workload_case/client.key" "$misplaced_workload_case/dev-key.pem" +assert_invalid_existing_bundle_is_preserved "$misplaced_workload_case" generic-workload-identity + +expired_case="$CERT_DIR/invalid-expired-bundle" +copy_generic_bundle "$CERT_DIR" "$expired_case" +cat >"$expired_case/expired.cnf" <<'EOF' +[req] +distinguished_name = req_distinguished_name +req_extensions = v3_req +prompt = no + +[req_distinguished_name] +CN = firemud-grpc + +[v3_req] +basicConstraints = critical,CA:false +keyUsage = critical,digitalSignature,keyEncipherment +extendedKeyUsage = serverAuth,clientAuth +subjectAltName = @alt_names + +[alt_names] +DNS.1 = localhost +DNS.2 = account-service +DNS.3 = automation-scripting-service +DNS.4 = entity-management-service +DNS.5 = game-design-service +DNS.6 = game-logic-service +DNS.7 = game-session-service +DNS.8 = logging-admin-service +DNS.9 = social-groups-service +DNS.10 = spring-cloud-gateway +DNS.11 = tcp-proxy-service +DNS.12 = world-management-service +IP.1 = 127.0.0.1 +EOF +openssl req -new -key "$expired_case/server.key" -config "$expired_case/expired.cnf" \ + -out "$expired_case/expired.csr" +openssl x509 -req -in "$expired_case/expired.csr" -CA "$expired_case/ca.crt" \ + -CAkey "$expired_case/ca.key" -set_serial 424242 -out "$expired_case/expired.crt" \ + -days 0 -sha256 -extensions v3_req -extfile "$expired_case/expired.cnf" >/dev/null +cp "$expired_case/expired.crt" "$expired_case/server.crt" +cp "$expired_case/expired.crt" "$expired_case/client.crt" +cp "$expired_case/expired.crt" "$expired_case/dev-cert.pem" +assert_invalid_existing_bundle_is_preserved "$expired_case" expired + +legacy_alias_case="$CERT_DIR/invalid-legacy-alias-bundle" +copy_generic_bundle "$CERT_DIR" "$legacy_alias_case" +printf 'wrong legacy alias\n' >"$legacy_alias_case/dev-cert.pem" +assert_invalid_existing_bundle_is_preserved "$legacy_alias_case" legacy-alias + +expected_files=( + default/ca.crt + default/client.crt + default/client.key + default/dev-ca.pem + default/dev-cert.pem + default/dev-key.pem + default/server.crt + default/server.key + account-service/ca.crt + account-service/client.crt + account-service/client.key + account-service/dev-ca.pem + account-service/dev-cert.pem + account-service/dev-key.pem + account-service/server.crt + account-service/server.key + account-service/workloads/account-service.crt + account-service/workloads/account-service.key + game-session-service/ca.crt + game-session-service/client.crt + game-session-service/client.key + game-session-service/dev-ca.pem + game-session-service/dev-cert.pem + game-session-service/dev-key.pem + game-session-service/server.crt + game-session-service/server.key + game-session-service/workloads/game-session-service.crt + game-session-service/workloads/game-session-service.key + social-groups-service/ca.crt + social-groups-service/client.crt + social-groups-service/client.key + social-groups-service/dev-ca.pem + social-groups-service/dev-cert.pem + social-groups-service/dev-key.pem + social-groups-service/server.crt + social-groups-service/server.key + social-groups-service/workloads/social-groups-service.crt + social-groups-service/workloads/social-groups-service.key +) +mapfile -t expected_files < <(printf '%s\n' "${expected_files[@]}" | sort) +mapfile -t actual_files < <(cd "$runtime_dir" && find . -type f -printf '%P\n' | sort) +[[ "${actual_files[*]}" == "${expected_files[*]}" ]] || { + echo "local runtime projection does not match the approved file allowlist" >&2 + printf 'expected: %s\n' "${expected_files[*]}" >&2 + printf 'actual: %s\n' "${actual_files[*]}" >&2 + exit 1 +} + +declare -A seen_certificates=() +for workload in account-service game-session-service social-groups-service; do + assert_workload_certificate "$workload" + fingerprint="$(openssl x509 -in "$runtime_dir/$workload/workloads/$workload.crt" -noout -fingerprint -sha256 | cut -d= -f2)" + [[ -z "${seen_certificates[$fingerprint]:-}" ]] || { + echo "local workloads share a certificate: $workload" >&2 + exit 1 + } + seen_certificates[$fingerprint]=1 +done + +expected_account_uri="spiffe://firemud/ns/local/sa/account-service" +account_dns_sans='DNS:account-service,DNS:account-service.local,DNS:account-service.local.svc,DNS:account-service.local.svc.cluster.local' +assert_invalid_workload_uri_is_reissued \ + duplicate-uri "URI:$expected_account_uri,URI:spiffe://firemud/ns/local/sa/other,$account_dns_sans" +assert_invalid_workload_uri_is_reissued \ + prefix-uri "URI:xURI:$expected_account_uri,$account_dns_sans" +assert_invalid_workload_uri_is_reissued \ + suffix-uri "URI:${expected_account_uri}-shadow,$account_dns_sans" + +# A malformed or stale local leaf is replaced only after it fails closed +# identity/issuer/key validation; the generic workload generator remains 0600. +printf 'invalid local leaf\n' >"$CERT_DIR/workloads/account-service.crt" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" +assert_workload_certificate account-service +[[ ! -e "$runtime_dir/game-session-service/workloads/account-service.key" \ + && ! -e "$runtime_dir/social-groups-service/workloads/account-service.key" \ + && ! -e "$runtime_dir/account-service/workloads/game-session-service.key" \ + && ! -e "$runtime_dir/account-service/workloads/social-groups-service.key" ]] || { + echo "local runtime projection exposes another workload's private key" >&2 + exit 1 +} + +# Certificate authority sources and workload outputs must not follow symlinks; +# verify rejected paths leave their target content untouched. +symlink_ensure_dir="$CERT_DIR/symlink-ensure" +mkdir -p "$symlink_ensure_dir/workloads" +for file in ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key; do + cp "$CERT_DIR/$file" "$symlink_ensure_dir/$file" +done +printf 'protected CA source\n' >"$symlink_ensure_dir/ca-key-target" +rm "$symlink_ensure_dir/ca.key" +ln -s "$symlink_ensure_dir/ca-key-target" "$symlink_ensure_dir/ca.key" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$symlink_ensure_dir"; then + echo "ensure-dev-certs accepted a symlinked CA source" >&2 + exit 1 +fi +[[ "$(<"$symlink_ensure_dir/ca-key-target")" == "protected CA source" ]] || { + echo "ensure-dev-certs modified a symlinked CA source target" >&2 + exit 1 +} +rm "$symlink_ensure_dir/ca.key" +cp "$CERT_DIR/ca.key" "$symlink_ensure_dir/ca.key" + +printf 'protected workload output\n' >"$symlink_ensure_dir/workload-key-target" +ln -s "$symlink_ensure_dir/workload-key-target" \ + "$symlink_ensure_dir/workloads/account-service.key" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$symlink_ensure_dir"; then + echo "ensure-dev-certs accepted a symlinked workload output" >&2 + exit 1 +fi +[[ "$(<"$symlink_ensure_dir/workload-key-target")" == "protected workload output" ]] || { + echo "ensure-dev-certs modified a symlinked workload output target" >&2 + exit 1 +} + +symlink_generator_dir="$CERT_DIR/symlink-generator" +mkdir -p "$symlink_generator_dir" +printf 'protected generator key\n' >"$symlink_generator_dir/key-target" +ln -s "$symlink_generator_dir/key-target" "$symlink_generator_dir/output.key" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" \ + "$symlink_generator_dir/output.crt" "$symlink_generator_dir/output.key" \ + local account-service; then + echo "generate-dev-certs accepted a symlinked workload output" >&2 + exit 1 +fi +[[ "$(<"$symlink_generator_dir/key-target")" == "protected generator key" \ + && ! -e "$symlink_generator_dir/output.crt" ]] || { + echo "generate-dev-certs modified a symlinked output target" >&2 + exit 1 +} + +for compose_file in docker-compose.override.yml docker-compose.local-images.override.yml; do + compose_path="$ROOT_DIR/docker/$compose_file" + rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$compose_path" + rg -Fq 'GRPC_SERVER_TLS_ENABLED: "true"' "$compose_path" + rg -Fq '../dev-tools/certs/local-runtime/default:/app/certs:ro' "$compose_path" + rg -Fq 'GATEWAY_WS_URL: ws://gateway:8080/ws/game' "$compose_path" + if rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "true"' "$compose_path" \ + || rg -Fq 'GRPC_SERVER_TLS_ENABLED: "false"' "$compose_path" \ + || rg -Fq '../dev-tools/certs:/app/certs' "$compose_path"; then + echo "$compose_file contains an insecure gRPC override or broad certificate mount" >&2 + exit 1 + fi + [[ "$(rg -c 'volumes: \*local-runtime-volumes' "$compose_path")" == "8" ]] || { + echo "$compose_file does not project runtime-only certs for every Java service" >&2 + exit 1 + } + for workload in account-service game-session-service social-groups-service; do + rg -Fq "../dev-tools/certs/local-runtime/$workload:/app/certs:ro" "$compose_path" + rg -Fq "FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/$workload.crt" "$compose_path" + rg -Fq "FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/$workload.key" "$compose_path" + rg -Fq 'FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt' "$compose_path" + done + rg -Fq 'FIREMUD_GRPC_WORKLOAD_NAMESPACE: local' "$compose_path" +done + +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$CERT_DIR" 2>&1)" +[[ ! -e "$CERT_DIR/workloads" && ! -e "$CERT_DIR/local-runtime" && ! -e "$CERT_DIR/ca.key" ]] || { + echo "certificate cleanup left generated workload or runtime material behind" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +# Unknown files and symlinks are preserved and reported; only known generated +# leaf/projection names are deleted, and their directories remain non-empty. +mkdir -p "$CERT_DIR/workloads" "$CERT_DIR/local-runtime/default" +printf 'generated\n' >"$CERT_DIR/workloads/account-service.key" +printf 'keep\n' >"$CERT_DIR/workloads/keep.txt" +printf 'generated\n' >"$CERT_DIR/local-runtime/default/client.key" +printf 'keep\n' >"$CERT_DIR/local-runtime/default/keep.txt" +printf 'target\n' >"$CERT_DIR/retained-target" +ln -s "$CERT_DIR/retained-target" "$CERT_DIR/local-runtime/default/server.key" +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$CERT_DIR" 2>&1)" +[[ ! -e "$CERT_DIR/workloads/account-service.key" \ + && ! -e "$CERT_DIR/local-runtime/default/client.key" \ + && -f "$CERT_DIR/workloads/keep.txt" \ + && -f "$CERT_DIR/local-runtime/default/keep.txt" \ + && -L "$CERT_DIR/local-runtime/default/server.key" \ + && "$(<"$CERT_DIR/retained-target")" == "target" ]] || { + echo "certificate cleanup did not preserve unexpected files and symlinks safely" >&2 + exit 1 +} +[[ "$cleanup_output" == *"$CERT_DIR/workloads/keep.txt"* \ + && "$cleanup_output" == *"$CERT_DIR/local-runtime/default/server.key"* ]] || { + echo "certificate cleanup did not report preserved entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +symlink_case="$CERT_DIR/symlink-case" +mkdir -p "$symlink_case/target" +printf 'protected\n' >"$symlink_case/target/social-groups-service.key" +ln -s "$symlink_case/target" "$symlink_case/workloads" +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$symlink_case" 2>&1)" +[[ -L "$symlink_case/workloads" \ + && "$(<"$symlink_case/target/social-groups-service.key")" == "protected" \ + && "$cleanup_output" == *"$symlink_case/workloads (symlink directory)"* ]] || { + echo "certificate cleanup followed or failed to report a symlinked leaf directory" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +ancestor_symlink_case="$CERT_DIR/ancestor-symlink-case" +ancestor_real_parent="$ancestor_symlink_case/real-parent" +ancestor_real_cert_dir="$ancestor_real_parent/cert-dir" +ancestor_alias="$ancestor_symlink_case/alias" +ancestor_alias_cert_dir="$ancestor_alias/cert-dir" +mkdir -p "$ancestor_real_cert_dir" +printf 'protected generated-name sentinel\n' >"$ancestor_real_cert_dir/ca.key" +chmod 640 "$ancestor_real_cert_dir/ca.key" +printf 'protected workload sentinel\n' >"$ancestor_real_cert_dir/workloads.key" +chmod 644 "$ancestor_real_cert_dir/workloads.key" +ln -s "$ancestor_real_parent" "$ancestor_alias" +if cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$ancestor_alias_cert_dir" 2>&1)"; then + echo "certificate cleanup accepted a certificate directory beneath a symlinked ancestor" >&2 + exit 1 +fi +[[ "$cleanup_output" == *"Refusing symlinked certificate directory; preserving it: $ancestor_alias_cert_dir"* \ + && "$(<"$ancestor_real_cert_dir/ca.key")" == 'protected generated-name sentinel' \ + && "$(<"$ancestor_real_cert_dir/workloads.key")" == 'protected workload sentinel' ]] || { + echo "certificate cleanup followed an ancestor symlink or changed protected entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} +assert_mode 640 "$ancestor_real_cert_dir/ca.key" +assert_mode 644 "$ancestor_real_cert_dir/workloads.key" + +direct_symlink_alias="$ancestor_symlink_case/direct-alias" +ln -s "$ancestor_real_cert_dir" "$direct_symlink_alias" +if cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$direct_symlink_alias/" 2>&1)"; then + echo "certificate cleanup accepted a symlink directory with a trailing slash" >&2 + exit 1 +fi +[[ "$cleanup_output" == *"Refusing symlinked certificate directory; preserving it: $direct_symlink_alias/"* \ + && "$(<"$ancestor_real_cert_dir/ca.key")" == 'protected generated-name sentinel' \ + && "$(<"$ancestor_real_cert_dir/workloads.key")" == 'protected workload sentinel' ]] || { + echo "certificate cleanup followed a trailing-slash symlink or changed protected entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} +assert_mode 640 "$ancestor_real_cert_dir/ca.key" +assert_mode 644 "$ancestor_real_cert_dir/workloads.key" + +echo "Local Compose workload identity contract passed." 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/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/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index cfa3dd89ff..e9256d7dea 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -7051,7 +7051,7 @@ def test_role_assurance_rejects_legacy_vocabulary_shape(self): def test_legacy_target_only_route_declaration_is_rejected(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) - route = route_for(document, "account-service", "POST /auth/bootstrap/join") + route = route_for(document, "account-service", "BillingArtifactsTenant") route.pop("route_status") route.setdefault("implementation_status", {})["target_only"] = True errors = validate_document(self.validator, document) diff --git a/docker/README.md b/docker/README.md index 127600e66e..02334f3694 100644 --- a/docker/README.md +++ b/docker/README.md @@ -34,7 +34,9 @@ docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.ym docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml down ``` -For ordinary local development, prefer `./gradlew devUp` and `./gradlew devDown`. The Gradle task builds the base image, application images, and `pg-dump-cron` image, generates development certificates, synchronizes the local Compose environment, and waits for the requested services to become ready. The raw source-built commands above are useful when iterating directly on the Compose build path; the certificate helper prepares the mounted local material, while the local override still selects plaintext internal gRPC for this development stack. +For ordinary local development, prefer `./gradlew devUp` and `./gradlew devDown`. The Gradle task builds the base image, application images, and `pg-dump-cron` image, ensures development certificates and workload identities, synchronizes the local Compose environment, and waits for the requested services to become ready. The raw source-built commands above are useful when iterating directly on the Compose build path. + +Both local Compose lanes use internal gRPC mTLS. `ensure-dev-certs.sh` creates local-only Account, Game Session, and Social Groups workload leaves signed by the local development CA, and prepares the ignored `dev-tools/certs/local-runtime/` bind-mount projection. That projection contains runtime certificates and keys but not the CA private key; it is not a hosted certificate source. The local overrides point the protected callers at their own leaf, set the `local` workload namespace for Account peer checks, and keep Gateway/TCP Proxy HTTP and WebSocket routing unchanged. Do not copy these local settings or certificates into preview, dev-demo, or production deployments. Canonical smoke/bootstrap proof: @@ -78,6 +80,6 @@ Gradle-managed local prebuilt-image stack: ## Local Runtime Notes - Compose service discovery uses Docker DNS plus the defaults in service `application.yml` files and the local Compose env overrides; it does not depend on a separate Spring `dev` profile lane. -- The local override files intentionally relax internal gRPC/TLS settings for the Docker development stack. +- The local override files keep internal gRPC mTLS enabled for the Docker development stack and replace the base certificate-directory mount with the CA-key-free local runtime projection. - The Compose stack also runs `pg-dump-cron`, which writes rotated PostgreSQL dumps under `docker/backups/`. - The scripted smoke clients require Python 3 and the `websocket-client` package; see [Smoke Tests for Login + PLAY + LOOK](../design/developer-workflows/login-session-smoke-tests.md#requirements) for the client prerequisites and transport-specific controls. diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index ab79427c42..1f32180350 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -1,7 +1,7 @@ # Canonical fresh/image/restart smoke profile. This deliberately overrides the -# ordinary local plaintext profile. Account, Game Session, Entity Management, -# and World Management receive distinct dev-namespace SPIFFE leaves; the other -# seven local apps share the local client leaf. Each app gets only its scoped +# ordinary local Compose profile. Account, Game Session, Entity Management, +# Social Groups, and World Management receive distinct dev-namespace SPIFFE leaves; the other six +# local apps share the generic client leaf. Each app gets only its scoped # read-only leaf mount and the public CA certificate under /app/certs. The CA # private key stays host-only and is never mounted into an app. x-grpc-mtls-environment: &grpc-mtls-environment @@ -16,6 +16,7 @@ services: account-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/account-service:/app/certs:ro @@ -76,6 +77,7 @@ services: social-groups-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/social-groups-service:/app/certs:ro diff --git a/docker/docker-compose.local-images.override.yml b/docker/docker-compose.local-images.override.yml index 7a1ddddac1..5af039f319 100644 --- a/docker/docker-compose.local-images.override.yml +++ b/docker/docker-compose.local-images.override.yml @@ -1,8 +1,11 @@ x-local-java-env: &local-java-env BPL_JAVA_NMT_ENABLED: "false" BPL_JVM_THREAD_COUNT: "20" - FIREMUD_GRPC_PLAINTEXT: "true" - GRPC_SERVER_TLS_ENABLED: "false" + FIREMUD_GRPC_PLAINTEXT: "false" + GRPC_SERVER_TLS_ENABLED: "true" + +x-local-runtime-volumes: &local-runtime-volumes + - ../dev-tools/certs/local-runtime/default:/app/certs:ro services: account-service: @@ -12,6 +15,12 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/account-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/account-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: + - ../dev-tools/certs/local-runtime/account-service:/app/certs:ro gateway: build: null @@ -22,6 +31,7 @@ services: <<: *local-java-env FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS: "true" FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0: 172.16.0.0/12 + volumes: *local-runtime-volumes automation-scripting-service: build: null @@ -30,6 +40,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes entity-management-service: build: null @@ -38,6 +49,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-design-service: build: null @@ -46,6 +58,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-logic-service: build: null @@ -54,6 +67,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-session-service: build: null @@ -63,6 +77,11 @@ services: environment: <<: *local-java-env GAME_LOGIC_DEFAULT_ROOM_ID: "1" + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/game-session-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/game-session-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/game-session-service:/app/certs:ro logging-admin-service: build: null @@ -71,6 +90,8 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: *local-runtime-volumes social-groups-service: build: null @@ -79,6 +100,11 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/social-groups-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/social-groups-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/social-groups-service:/app/certs:ro tcp-proxy-service: build: null @@ -88,6 +114,7 @@ services: environment: <<: *local-java-env GATEWAY_WS_URL: ws://gateway:8080/ws/game + volumes: *local-runtime-volumes world-management-service: build: null @@ -96,6 +123,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes pg-dump-cron: build: null diff --git a/docker/docker-compose.override.yml b/docker/docker-compose.override.yml index 20fb7f21f5..795df2baa7 100644 --- a/docker/docker-compose.override.yml +++ b/docker/docker-compose.override.yml @@ -1,47 +1,73 @@ -# Local override for plaintext/dev-only Compose behavior. Do not reuse these -# settings as a template for preview or other production-like environments. +# Local override for the development Compose stack. Do not reuse these settings +# as a template for preview or other production-like environments. x-local-java-env: &local-java-env - FIREMUD_GRPC_PLAINTEXT: "true" - GRPC_SERVER_TLS_ENABLED: "false" + FIREMUD_GRPC_PLAINTEXT: "false" + GRPC_SERVER_TLS_ENABLED: "true" + +x-local-runtime-volumes: &local-runtime-volumes + - ../dev-tools/certs/local-runtime/default:/app/certs:ro services: account-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/account-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/account-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: + - ../dev-tools/certs/local-runtime/account-service:/app/certs:ro gateway: environment: <<: *local-java-env FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS: "true" FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0: 172.16.0.0/12 + volumes: *local-runtime-volumes automation-scripting-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes entity-management-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-design-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-logic-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-session-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/game-session-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/game-session-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/game-session-service:/app/certs:ro logging-admin-service: environment: <<: *local-java-env + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: *local-runtime-volumes social-groups-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/social-groups-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/social-groups-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/social-groups-service:/app/certs:ro tcp-proxy-service: environment: @@ -52,10 +78,12 @@ services: TCP_PROXY_DEFAULT_POINTER_VERSION: ${TCP_PROXY_DEFAULT_POINTER_VERSION:-1} TCP_PROXY_DEFAULT_GAME_INSTANCE_ID: ${TCP_PROXY_DEFAULT_GAME_INSTANCE_ID:-1} TCP_PROXY_DEFAULT_TENANT_ID: ${TCP_PROXY_DEFAULT_TENANT_ID:-1} + volumes: *local-runtime-volumes world-management-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes redisinsight: image: redis/redisinsight:2.70 diff --git a/k8s/helm/account-service/templates/deployment.yaml b/k8s/helm/account-service/templates/deployment.yaml index bde01874a2..fcb1c9389c 100644 --- a/k8s/helm/account-service/templates/deployment.yaml +++ b/k8s/helm/account-service/templates/deployment.yaml @@ -1,5 +1,8 @@ apiVersion: apps/v1 kind: Deployment +{{- if hasKey (.Values.extraEnv | default dict) "FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} +{{- fail "extraEnv must not set controller-owned FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} +{{- end }} metadata: name: account-service spec: @@ -23,6 +26,10 @@ spec: ports: - containerPort: 8080 env: + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace {{- range $key, $value := .Values.extraEnv }} - name: {{ $key }} value: "{{ $value }}" diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 210539837f..764ebf8c6b 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -64,6 +64,10 @@ message CreateLogEventResponse { string payload_digest = 9; AccountAuditReceiptStatus status = 10; AccountAuditReceiptOutcome outcome = 11; + // Version 1 attests the receipt/projection link. Positive delivery evidence also requires a + // COMMITTED receipt and matching receiver identities for the exact scoped outbox row, not payload replay. + // Zero or unsupported versions cannot verify delivery or historical producer provenance. + int32 audit_projection_version = 12; } message ReadLogEventReceiptRequest { @@ -91,6 +95,10 @@ message ReadLogEventReceiptResponse { AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; shared.v1.ErrorDetail error = 11; + // Same version-1 receipt/projection evidence rule as CreateLogEventResponse: a COMMITTED receipt + // with receiver identities matching the exact scoped outbox row; it is never payload replay proof. + // Zero or unsupported versions cannot verify delivery or historical producer provenance. + int32 audit_projection_version = 12; } enum AccountAuditScope { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 4eee08dfc8..2565777ef2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -107,6 +107,10 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { } throw new IllegalStateException("Account audit receiver returned error code " + errorCode); } + if (response.getAuditProjectionVersion() != 1) { + throw new IllegalStateException( + "Account audit receiver did not prove a supported audit projection version"); + } if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) || !response.getPayloadDigest().equals(envelope.payloadDigest()) || response.getSchemaVersion() != envelope.schemaVersion() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index adc504c777..5db7a07ad9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -78,16 +78,18 @@ public ResponseEntity> exportTenantData( long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); - TenantDataExportDto data = accountService.exportTenantData(parsedTenantId, parsedAccountId); - return ResponseEntity.ok(ApiResponse.success(data)); + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Tenant-admin export is unavailable until the tenant-wide export contract is implemented"); } @DeleteMapping("/{accountId}") public ResponseEntity> deleteAccount(@PathVariable String accountId) { long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); - accountService.deleteAccount(parsedAccountId); - return ResponseEntity.ok(ApiResponse.success(null)); + throw new net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException( + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented"); } private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 1a7c649e49..4b41e70837 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -9,6 +9,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; @@ -69,12 +70,45 @@ public List pending(int limit, Instant dueBeforeOrAt) { .fetch(this::toEnvelope); } + /** Locks one exact Account JOIN transition envelope for transaction-local reconciliation. */ + public Optional findJoinEnvelopeForUpdate(UUID auditEventId, long tenantId) { + if (auditEventId == null || tenantId <= 0) { + throw new IllegalArgumentException("JOIN audit identity and tenant are required"); + } + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.SCOPE.eq("tenant")) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_ID.eq(tenantId)) + .and(ACCOUNT_AUDIT_OUTBOX.PRODUCER_SERVICE.eq("account-service")) + .and(ACCOUNT_AUDIT_OUTBOX.EVENT_TYPE.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"))) + .forUpdate() + .fetchOptional( + row -> + new JoinAuditEvidence( + toEnvelope(row), + row.getDeliveryStatus(), + row.getReceiverAuditProjectionVersion(), + row.getReceiverReceiptId(), + row.getReceiverLogEventId())); + } + public void markDelivered( UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + if (auditEventId == null + || receiptId == null + || receiptId.isBlank() + || logEventId == null + || logEventId.isBlank()) { + throw new IllegalArgumentException("Verified audit delivery requires nonblank identity"); + } var update = dsl.update(ACCOUNT_AUDIT_OUTBOX) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_AUDIT_PROJECTION_VERSION, 1) .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) .set(ACCOUNT_AUDIT_OUTBOX.NEXT_ATTEMPT_AT, (LocalDateTime) null); @@ -139,4 +173,15 @@ private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { row.getPayloadDigest(), row.getPayload()); } + + public record JoinAuditEvidence( + AccountAuditEnvelope envelope, + String deliveryStatus, + Integer auditProjectionVersion, + String receiptId, + String projectionId) { + public JoinAuditEvidence { + Objects.requireNonNull(envelope, "envelope"); + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index de441fb2de..4a2470fc62 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -7,6 +7,7 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import org.jooq.DSLContext; @@ -79,6 +80,38 @@ public Optional find(String connectScopeId) { .fetchOptional(record -> toScope(record, connectScopeId)); } + /** + * Reads retained target evidence by its one-way token hash. This record cannot be used as a + * connect-scope bearer and deliberately does not reconstruct or expose the plaintext token. + */ + public Optional findEvidenceByTokenHash(String scopeTokenHash) { + if (scopeTokenHash == null || scopeTokenHash.isBlank()) { + throw new IllegalArgumentException("JOIN scope token hash is required"); + } + return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) + .where(ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq(scopeTokenHash)) + .fetchOptional(AccountConnectScopeRepository::toEvidence); + } + + private static ConnectScopeEvidence toEvidence(Record record) { + return new ConnectScopeEvidence( + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST)); + } + /** * Deletes a bounded batch of expired scopes only when no JOIN receipt references them. Malformed * expiry values are retained. The database FK from JOIN receipts is the concurrent insert fence @@ -122,4 +155,21 @@ private VerifiedJoinScope toScope(Record record, String connectScopeId) { } return scope; } + + public record ConnectScopeEvidence( + String scopeTokenHash, + long accountId, + String targetClass, + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + String snapshotDigest) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index a43a4b536b..77a5ef6aac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -2,8 +2,12 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_JOIN_OPERATIONS; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; @@ -16,6 +20,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountJoinOperationRepository { + private static final int MAX_RECONCILIATION_PAGE_SIZE = 100; + private final DSLContext dsl; public AccountJoinOperationRepository(DSLContext dsl) { @@ -47,6 +53,112 @@ public Optional findForUpdate(String requestId) { .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } + /** Returns a stable, bounded page of all due PENDING operations. */ + public List findDuePendingReconciliation(Instant now, int limit) { + if (now == null) { + throw new IllegalArgumentException("JOIN reconciliation time is required"); + } + if (limit < 1 || limit > MAX_RECONCILIATION_PAGE_SIZE) { + throw new IllegalArgumentException("JOIN reconciliation page size must be between 1 and 100"); + } + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where( + ACCOUNT_JOIN_OPERATIONS + .STATUS + .eq("PENDING") + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( + toLocalDateTime(now)))) + .orderBy( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.asc(), + ACCOUNT_JOIN_OPERATIONS.CREATED_AT.asc(), + ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.asc()) + .limit(limit) + .fetch(AccountJoinOperationRepository::toJoinOperation); + } + + /** Counts due PENDING operations without loading rows or taking per-account locks. */ + public long countDuePendingReconciliation(Instant now) { + if (now == null) { + throw new IllegalArgumentException("JOIN reconciliation time is required"); + } + Long count = + dsl.select(org.jooq.impl.DSL.count().cast(Long.class)) + .from(ACCOUNT_JOIN_OPERATIONS) + .where( + ACCOUNT_JOIN_OPERATIONS + .STATUS + .eq("PENDING") + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( + toLocalDateTime(now)))) + .fetchOne(0, Long.class); + if (count == null) { + throw new IllegalStateException("JOIN reconciliation due-operation count was unavailable"); + } + return count; + } + + /** + * Records one reconciliation attempt only if the pending row still has the observed attempt count + * and due time. The count saturates at the configured diagnostic threshold. A false result means + * another worker changed or rescheduled the row. + */ + public boolean recordReconciliationAttempt( + String requestId, + int expectedAttemptCount, + int maxAttempts, + Instant expectedNextAttemptAt, + Instant attemptedAt, + String reason, + Instant nextAttemptAt) { + if (requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("JOIN request ID is required"); + } + if (expectedAttemptCount < 0 || maxAttempts < 1 || expectedNextAttemptAt == null) { + throw new IllegalArgumentException("JOIN reconciliation attempt count is outside its limit"); + } + if (attemptedAt == null || nextAttemptAt == null || nextAttemptAt.isBefore(attemptedAt)) { + throw new IllegalArgumentException("JOIN reconciliation attempt times are invalid"); + } + if (reason == null || reason.isBlank() || reason.trim().length() > 128) { + throw new IllegalArgumentException( + "JOIN reconciliation reason must contain 1 to 128 characters"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT, + org.jooq + .impl + .DSL + .when( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts), + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.plus(1)) + .otherwise(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT)) + .set( + ACCOUNT_JOIN_OPERATIONS.LAST_RECONCILIATION_ATTEMPT_AT, + toLocalDateTime(attemptedAt)) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_RECONCILIATION_ATTEMPT_REASON, reason.trim()) + .set( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT, + toLocalDateTime(nextAttemptAt)) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, toLocalDateTime(attemptedAt)) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) + .and( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.eq( + expectedAttemptCount)) + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.eq( + toLocalDateTime(expectedNextAttemptAt)))) + .execute(); + return updated == 1; + } + public boolean hasRetainedOperation(long accountId) { return dsl.fetchExists( ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); @@ -209,9 +321,17 @@ public void recordCallerBoundAuthorityInvalidation(String requestId) { } public record JoinOperation( + String requestId, long accountId, long tenantId, UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, String callerBinding, String scopeTokenHash, String connectScopeDigest, @@ -228,14 +348,26 @@ public record JoinOperation( int intentDigestVersion, String intentDigest, String lastAttemptFailureCode, - String lastAttemptAuthorityAvailability) {} + String lastAttemptAuthorityAvailability, + int reconciliationAttemptCount, + Instant lastReconciliationAttemptAt, + String lastReconciliationAttemptReason, + Instant nextReconciliationAttemptAt) {} private static JoinOperation toJoinOperation( net.firedevops.firemud.accountservice.jooq.tables.records.AccountJoinOperationsRecord row) { return new JoinOperation( + row.getRequestId(), row.getAccountId(), row.getTenantId(), row.getRealmId(), + row.getWorldSlug(), + row.getRealmSlug(), + row.getPlayableStateNamespaceId(), + row.getPlayableStateScope(), + row.getGameInstanceId(), + row.getCatalogRevision(), + row.getPointerVersion(), row.getVerifiedCallerBinding(), row.getScopeTokenHash(), row.getConnectScopeDigest(), @@ -252,6 +384,12 @@ private static JoinOperation toJoinOperation( row.getIntentDigestVersion(), row.getIntentDigest(), row.getLastAttemptFailureCode(), - row.getLastAttemptAuthorityAvailability()); + row.getLastAttemptAuthorityAvailability(), + row.getReconciliationAttemptCount(), + row.getLastReconciliationAttemptAt() == null + ? null + : toInstant(row.getLastReconciliationAttemptAt()), + row.getLastReconciliationAttemptReason(), + toInstant(row.getNextReconciliationAttemptAt())); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 1a4b5e3e10..758d89b331 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -34,6 +34,38 @@ public Optional findByAccountIdAndTenantId( .fetchOne(this::toEntity)); } + /** Reads and locks the exact membership row for a JOIN reconciliation proof. */ + public Optional findJoinProofForUpdate(long accountId, long tenantId) { + return dsl.select( + ACCOUNT_TENANT_MEMBERSHIP.ID, + ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, + ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, + ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, + ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE) + .from(ACCOUNT_TENANT_MEMBERSHIP) + .where( + ACCOUNT_TENANT_MEMBERSHIP + .ACCOUNT_ID + .eq(accountId) + .and(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID.eq(tenantId))) + .forUpdate() + .fetchOptional( + record -> + new JoinMembershipProof( + record.get(ACCOUNT_TENANT_MEMBERSHIP.ID), + record.get(ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID), + record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID), + Boolean.TRUE.equals( + record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED)), + record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE), + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION), + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION), + record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE))); + } + public boolean existsByAccountIdAndTenantId(Long accountId, Long tenantId) { return dsl.fetchExists( ACCOUNT_TENANT_MEMBERSHIP, @@ -169,4 +201,14 @@ private AccountTenantMembership toEntity(Record record) { membership.setAuthorityProvenance(record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE)); return membership; } + + public record JoinMembershipProof( + long membershipId, + long accountId, + long tenantId, + boolean gameplayAdmissionAllowed, + String lifecycleState, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java index acb2c576fb..9657039da8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java @@ -61,6 +61,22 @@ public void delete(EmailVerificationToken entity) { } } + /** Atomically consumes a still-valid token so only one transaction can claim it. */ + public boolean consumeIfUnexpired(EmailVerificationToken token, LocalDateTime capturedNow) { + if (token == null || token.getId() == null) { + return false; + } + return dsl.deleteFrom(EMAIL_VERIFICATION_TOKEN) + .where( + EMAIL_VERIFICATION_TOKEN + .ID + .eq(token.getId()) + .and(EMAIL_VERIFICATION_TOKEN.TOKEN.eq(token.getToken())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.ge(capturedNow))) + .execute() + == 1; + } + public void deleteByAccountId(Long accountId) { dsl.deleteFrom(EMAIL_VERIFICATION_TOKEN) .where(EMAIL_VERIFICATION_TOKEN.ACCOUNT_ID.eq(accountId)) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java index 5c509ff3eb..38ede92a17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java @@ -61,6 +61,22 @@ public void delete(PasswordResetToken entity) { } } + /** Atomically consumes a still-valid token so only one transaction can claim it. */ + public boolean consumeIfUnexpired(PasswordResetToken token, LocalDateTime capturedNow) { + if (token == null || token.getId() == null) { + return false; + } + return dsl.deleteFrom(PASSWORD_RESET_TOKEN) + .where( + PASSWORD_RESET_TOKEN + .ID + .eq(token.getId()) + .and(PASSWORD_RESET_TOKEN.TOKEN.eq(token.getToken())) + .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.ge(capturedNow))) + .execute() + == 1; + } + public void deleteByAccountId(Long accountId) { dsl.deleteFrom(PASSWORD_RESET_TOKEN) .where(PASSWORD_RESET_TOKEN.ACCOUNT_ID.eq(accountId)) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java new file mode 100644 index 0000000000..0db99576f5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Periodically invokes Account's bounded, readback-only JOIN reconciler. */ +@Component +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Invalid scheduling configuration must fail startup.") +public class AccountJoinReconciliationJob { + private final AccountJoinReconciliationService reconciliationService; + + public AccountJoinReconciliationJob( + AccountJoinReconciliationService reconciliationService, + @Value("${firemud.account.join-reconciliation.interval-ms:30000}") long intervalMillis) { + if (intervalMillis < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.interval-ms must be positive"); + } + this.reconciliationService = reconciliationService; + } + + @Scheduled( + fixedDelayString = "${firemud.account.join-reconciliation.interval-ms:30000}", + timeUnit = TimeUnit.MILLISECONDS) + public void reconcilePendingJoinOperations() { + reconciliationService.reconcileDueOperations(Instant.now()); + } +} 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 new file mode 100644 index 0000000000..6160fd25ae --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java @@ -0,0 +1,540 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.MeterRegistry; +import java.nio.charset.StandardCharsets; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +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.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Readback-only recovery for Account JOIN operations left PENDING after an uncertain commit. */ +@Service +@SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Injected Spring collaborators are internal; invalid reconciliation settings must fail startup.") +public class AccountJoinReconciliationService { + private static final Logger logger = + LoggerFactory.getLogger(AccountJoinReconciliationService.class); + private static final int MAX_BATCH_SIZE = 100; + private static final long MAX_BACKOFF_MILLIS = 300_000L; + private static final Pattern SHA256_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set JOIN_AUDIT_FIELDS = + Set.of("accountId", "tenantId", "worldSlug", "realmSlug", "membershipVersion", "requestId"); + private static final JsonMapper AUDIT_JSON = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountConnectScopeRepository connectScopeRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final TransactionTemplate joinTransactionTemplate; + private final int batchSize; + private final int maxAttempts; + private final long backoffMillis; + private final Counter committed; + private final Counter unresolved; + private final Counter failures; + private final Counter maxAttemptsReached; + private final AtomicLong dueBacklog = new AtomicLong(); + private final AtomicLong dueButNotSelected = new AtomicLong(); + private final AtomicLong dueBacklogSampleUnknown = new AtomicLong(1); + + public AccountJoinReconciliationService( + AccountJoinOperationRepository joinOperationRepository, + AccountConnectScopeRepository connectScopeRepository, + AccountTenantMembershipRepository membershipRepository, + AccountAuditOutboxRepository auditOutboxRepository, + MeterRegistry meterRegistry, + PlatformTransactionManager transactionManager, + @Value("${firemud.account.join-reconciliation.batch-size:50}") int batchSize, + @Value("${firemud.account.join-reconciliation.max-attempts:12}") int maxAttempts, + @Value("${firemud.account.join-reconciliation.backoff-ms:30000}") long backoffMillis) { + if (batchSize < 1 || batchSize > MAX_BATCH_SIZE) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.batch-size must be between 1 and 100"); + } + if (maxAttempts < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.max-attempts must be positive"); + } + if (backoffMillis < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.backoff-ms must be positive"); + } + this.joinOperationRepository = joinOperationRepository; + this.connectScopeRepository = connectScopeRepository; + this.membershipRepository = membershipRepository; + this.auditOutboxRepository = auditOutboxRepository; + this.batchSize = batchSize; + this.maxAttempts = maxAttempts; + this.backoffMillis = backoffMillis; + this.joinTransactionTemplate = new TransactionTemplate(transactionManager); + this.joinTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.committed = counter(meterRegistry, "committed"); + this.unresolved = counter(meterRegistry, "unresolved"); + this.failures = counter(meterRegistry, "failure"); + this.maxAttemptsReached = counter(meterRegistry, "max_attempts_reached"); + Gauge.builder("account.join.reconciliation.due.backlog", dueBacklog, AtomicLong::doubleValue) + .description("Last successfully sampled count of due PENDING Account JOIN operations") + .register(meterRegistry); + Gauge.builder( + "account.join.reconciliation.due.not.selected", + dueButNotSelected, + AtomicLong::doubleValue) + .description("Due JOIN operations beyond the configured bounded page capacity") + .register(meterRegistry); + Gauge.builder( + "account.join.reconciliation.due.backlog.sample.unknown", + dueBacklogSampleUnknown, + AtomicLong::doubleValue) + .description( + "One when the latest due JOIN backlog count failed and retained values are stale") + .register(meterRegistry); + } + + /** Processes one bounded due page using the caller's captured time for deterministic rechecks. */ + public void reconcileDueOperations(Instant now) { + Objects.requireNonNull(now, "JOIN reconciliation time is required"); + sampleDueBacklog(now); + final List dueOperations; + try { + dueOperations = joinOperationRepository.findDuePendingReconciliation(now, batchSize); + } catch (RuntimeException ex) { + failures.increment(); + logger.warn( + "JOIN reconciliation could not list due operations ({})", ex.getClass().getSimpleName()); + return; + } + + for (JoinOperation candidate : dueOperations) { + reconcileOne(candidate, now); + } + } + + private void sampleDueBacklog(Instant now) { + try { + long count = joinOperationRepository.countDuePendingReconciliation(now); + long excess = count > batchSize ? count - batchSize : 0L; + dueBacklog.set(count); + dueButNotSelected.set(excess); + dueBacklogSampleUnknown.set(0); + if (count > batchSize) { + logger.warn( + "JOIN reconciliation due backlog {} exceeds bounded page size {} by {}", + count, + batchSize, + excess); + } + } catch (RuntimeException ex) { + failures.increment(); + dueBacklogSampleUnknown.set(1); + logger.warn( + "JOIN reconciliation due backlog count is unavailable; retaining the last successful sample ({})", + ex.getClass().getSimpleName()); + } + } + + /** Convenience entry point for direct operational invocation. */ + public void reconcileDueOperations() { + reconcileDueOperations(Instant.now()); + } + + private void reconcileOne(JoinOperation candidate, Instant now) { + try { + ReconciliationResult result = + joinTransactionTemplate.execute(transactionStatus -> reconcileLocked(candidate, now)); + if (result == null || result == ReconciliationResult.SKIPPED) { + return; + } + if (result == ReconciliationResult.COMMITTED) { + committed.increment(); + } else if (result == ReconciliationResult.ATTEMPT_RECORDED) { + unresolved.increment(); + } else if (result == ReconciliationResult.MAX_ATTEMPTS_REACHED) { + unresolved.increment(); + maxAttemptsReached.increment(); + } + } catch (RuntimeException ex) { + failures.increment(); + logger.warn( + "JOIN reconciliation readback failed for request {} ({})", + candidate.requestId(), + ex.getClass().getSimpleName()); + ReconciliationResult fallbackResult = recordUnavailableAttempt(candidate, now); + if (fallbackResult == ReconciliationResult.ATTEMPT_RECORDED) { + unresolved.increment(); + } else if (fallbackResult == ReconciliationResult.MAX_ATTEMPTS_REACHED) { + unresolved.increment(); + maxAttemptsReached.increment(); + } + } + } + + private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant now) { + // Keep the same lock order as the caller: account row, then durable operation row. + joinOperationRepository.lockAccount(candidate.accountId()); + JoinOperation operation = + joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); + if (operation == null + || operation.accountId() != candidate.accountId() + || !"PENDING".equals(operation.status()) + || operation.nextReconciliationAttemptAt() == null + || operation.nextReconciliationAttemptAt().isAfter(now)) { + return ReconciliationResult.SKIPPED; + } + + String unresolvedReason = validateOperationAndPolicy(operation); + if (unresolvedReason == null) { + unresolvedReason = validateRetainedScope(operation); + } + + JoinMembershipProof membership = null; + JoinAuditEvidence auditEvidence = null; + if (unresolvedReason == null) { + membership = + membershipRepository + .findJoinProofForUpdate(operation.accountId(), operation.tenantId()) + .orElse(null); + if (membership == null) { + unresolvedReason = "MEMBERSHIP_EVIDENCE_ABSENT"; + } else if (!membershipMatches(operation, membership)) { + unresolvedReason = "MEMBERSHIP_EVIDENCE_MISMATCH"; + } + } + + 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"; + } + } + + if (unresolvedReason != null) { + return recordUnresolvedAttempt(operation, now, unresolvedReason); + } + + joinOperationRepository.finish( + operation.requestId(), + "COMMITTED", + "JOINED", + membership.membershipId(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration()); + return ReconciliationResult.COMMITTED; + } + + private String validateOperationAndPolicy(JoinOperation operation) { + if (operation.requestId() == null + || operation.requestId().isBlank() + || operation.accountId() <= 0 + || operation.tenantId() <= 0 + || operation.realmId() == null + || !hasText(operation.worldSlug()) + || !hasText(operation.realmSlug()) + || !hasText(operation.playableStateNamespaceId()) + || !hasText(operation.playableStateScope()) + || operation.gameInstanceId() <= 0 + || operation.catalogRevision() <= 0 + || operation.pointerVersion() <= 0 + || operation.callerBinding() == null + || operation.callerBinding().isBlank() + || operation.intentDigestVersion() != 1 + || !isSha256(operation.intentDigest()) + || operation.requestDigestVersion() == null + || operation.requestDigestVersion() != 1 + || !isSha256(operation.requestDigest()) + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0 + || operation.outcome() != null + || operation.membershipId() != null + || operation.membershipVersion() != null + || operation.membershipAuthorityGeneration() != null) { + return "JOIN_OPERATION_POLICY_UNPROVEN"; + } + return null; + } + + private String validateRetainedScope(JoinOperation operation) { + if (!isSha256(operation.scopeTokenHash()) || !isSha256(operation.connectScopeDigest())) { + return "JOIN_SCOPE_DIGEST_UNCLEAR"; + } + var evidence = + connectScopeRepository.findEvidenceByTokenHash(operation.scopeTokenHash()).orElse(null); + if (evidence == null) { + return "JOIN_SCOPE_EVIDENCE_ABSENT"; + } + if (!scopeMatches(operation, evidence)) { + return "JOIN_SCOPE_EVIDENCE_MISMATCH"; + } + if (evidence.evaluatedAt() == null || evidence.connectScopeExpiresAt() == null) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + try { + Instant evaluatedAt = Instant.parse(evidence.evaluatedAt()); + Instant expiresAt = Instant.parse(evidence.connectScopeExpiresAt()); + // Expiry blocks new caller use; it cannot erase positive persisted commit evidence. + if (!expiresAt.isAfter(evaluatedAt)) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + } catch (DateTimeException ex) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + return null; + } + + private static boolean scopeMatches( + JoinOperation operation, AccountConnectScopeRepository.ConnectScopeEvidence evidence) { + return evidence.accountId() == operation.accountId() + && "PUBLIC_PRODUCTION".equals(evidence.targetClass()) + && evidence.tenantId() == operation.tenantId() + && Objects.equals(evidence.realmId(), operation.realmId()) + && Objects.equals(evidence.worldSlug(), operation.worldSlug()) + && Objects.equals(evidence.realmSlug(), operation.realmSlug()) + && Objects.equals(evidence.playableStateNamespaceId(), operation.playableStateNamespaceId()) + && Objects.equals(evidence.playableStateScope(), operation.playableStateScope()) + && evidence.gameInstanceId() == operation.gameInstanceId() + && evidence.catalogRevision() == operation.catalogRevision() + && evidence.pointerVersion() == operation.pointerVersion() + && Objects.equals(evidence.scopeTokenHash(), operation.scopeTokenHash()) + && Objects.equals(evidence.snapshotDigest(), operation.connectScopeDigest()) + && isSha256(evidence.snapshotDigest()); + } + + private static boolean membershipMatches( + JoinOperation operation, JoinMembershipProof membership) { + return membership.membershipId() > 0 + && membership.accountId() == operation.accountId() + && membership.tenantId() == operation.tenantId() + && membership.gameplayAdmissionAllowed() + && "ACTIVE".equals(membership.lifecycleState()) + && "EXPLICIT_JOIN".equals(membership.authorityProvenance()) + && membership.membershipVersion() > 0 + && membership.membershipAuthorityGeneration() > 0; + } + + private static boolean auditEnvelopeMatches( + JoinOperation operation, JoinMembershipProof membership, AccountAuditEnvelope envelope) { + if (!joinAuditEventId(operation.requestId()).equals(envelope.auditEventId()) + || !"tenant".equals(envelope.scope()) + || !Objects.equals(envelope.tenantId(), operation.tenantId()) + || !"account-service".equals(envelope.producerService()) + || !"ACCOUNT_JOINED_PUBLIC_PRODUCTION".equals(envelope.eventType()) + || envelope.occurredAt() == null + || envelope.schemaVersion() != 1 + || envelope.payloadDigestVersion() != 1 + || !isSha256(envelope.payloadDigest()) + || envelope.payload() == null + || !envelope.payloadDigest().equals(AccountAuditDigest.ofPayload(envelope.payload()))) { + return false; + } + + JoinAuditPayload payload = parseJoinAuditPayload(envelope.payload()); + return payload != null + && payload.accountId() == operation.accountId() + && payload.tenantId() == operation.tenantId() + && Objects.equals(payload.worldSlug(), operation.worldSlug()) + && Objects.equals(payload.realmSlug(), operation.realmSlug()) + && payload.membershipVersion() == membership.membershipVersion() + && Objects.equals(payload.requestId(), operation.requestId()); + } + + private static boolean verifiedJoinAuditDelivery(JoinAuditEvidence evidence) { + return "COMMITTED".equals(evidence.deliveryStatus()) + && Integer.valueOf(1).equals(evidence.auditProjectionVersion()) + && hasText(evidence.receiptId()) + && hasText(evidence.projectionId()); + } + + private static JoinAuditPayload parseJoinAuditPayload(String json) { + try { + JsonNode root = AUDIT_JSON.readTree(json); + if (root == null || !root.isObject()) { + return null; + } + Set names = new HashSet<>(); + root.properties().forEach(entry -> names.add(entry.getKey())); + if (!JOIN_AUDIT_FIELDS.equals(names)) { + return null; + } + JsonNode accountId = root.get("accountId"); + JsonNode tenantId = root.get("tenantId"); + JsonNode worldSlug = root.get("worldSlug"); + JsonNode realmSlug = root.get("realmSlug"); + JsonNode membershipVersion = root.get("membershipVersion"); + JsonNode requestId = root.get("requestId"); + if (!isLong(accountId) + || !isLong(tenantId) + || !worldSlug.isTextual() + || !realmSlug.isTextual() + || !isLong(membershipVersion) + || !requestId.isTextual()) { + return null; + } + return new JoinAuditPayload( + accountId.longValue(), + tenantId.longValue(), + worldSlug.textValue(), + realmSlug.textValue(), + membershipVersion.longValue(), + requestId.textValue()); + } catch (RuntimeException ex) { + return null; + } + } + + private static boolean isLong(JsonNode node) { + return node != null && node.isIntegralNumber() && node.canConvertToLong(); + } + + private ReconciliationResult recordUnresolvedAttempt( + JoinOperation operation, Instant now, String reason) { + boolean recorded = + joinOperationRepository.recordReconciliationAttempt( + operation.requestId(), + operation.reconciliationAttemptCount(), + maxAttempts, + operation.nextReconciliationAttemptAt(), + now, + reason, + nextAttemptAt(now, operation.reconciliationAttemptCount())); + if (!recorded) { + return ReconciliationResult.SKIPPED; + } + if (operation.reconciliationAttemptCount() < maxAttempts + && operation.reconciliationAttemptCount() + 1 >= maxAttempts) { + logger.warn( + "JOIN reconciliation reached its diagnostic attempt threshold for request {}; exact readback will continue with backoff while it remains PENDING (reason {})", + operation.requestId(), + reason); + return ReconciliationResult.MAX_ATTEMPTS_REACHED; + } + logger.debug( + "JOIN reconciliation remains pending for request {} (reason {})", + operation.requestId(), + reason); + return ReconciliationResult.ATTEMPT_RECORDED; + } + + private ReconciliationResult recordUnavailableAttempt(JoinOperation candidate, Instant now) { + try { + ReconciliationResult result = + joinTransactionTemplate.execute( + transactionStatus -> { + joinOperationRepository.lockAccount(candidate.accountId()); + JoinOperation operation = + joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); + if (operation == null + || operation.accountId() != candidate.accountId() + || !"PENDING".equals(operation.status()) + || operation.nextReconciliationAttemptAt() == null + || operation.nextReconciliationAttemptAt().isAfter(now)) { + return ReconciliationResult.SKIPPED; + } + return recordUnresolvedAttempt(operation, now, "JOIN_READBACK_UNAVAILABLE"); + }); + return result == null ? ReconciliationResult.SKIPPED : result; + } catch (RuntimeException ex) { + logger.warn( + "JOIN reconciliation could not persist a retry diagnostic for request {} ({})", + candidate.requestId(), + ex.getClass().getSimpleName()); + return ReconciliationResult.SKIPPED; + } + } + + private Instant nextAttemptAt(Instant attemptedAt, int persistedAttemptCount) { + try { + return attemptedAt.plusMillis(retryDelayMillis(persistedAttemptCount)); + } catch (DateTimeException | ArithmeticException ex) { + throw new IllegalStateException("JOIN reconciliation backoff is outside timestamp range", ex); + } + } + + private long retryDelayMillis(int persistedAttemptCount) { + long cap = Math.max(backoffMillis, MAX_BACKOFF_MILLIS); + long delay = backoffMillis; + int remainingDoublings = Math.max(0, persistedAttemptCount); + while (remainingDoublings > 0 && delay < cap) { + if (delay > cap / 2) { + return cap; + } + delay *= 2; + remainingDoublings--; + } + return delay; + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static boolean isSha256(String value) { + return value != null && SHA256_PATTERN.matcher(value).matches(); + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + private static Counter counter(MeterRegistry meterRegistry, String result) { + return Counter.builder("account.join.reconciliation.operations") + .description("Account JOIN reconciliation operation outcomes") + .tag("result", result) + .register(meterRegistry); + } + + private enum ReconciliationResult { + SKIPPED, + COMMITTED, + ATTEMPT_RECORDED, + MAX_ATTEMPTS_REACHED + } + + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 29b6201f11..47ee2ac770 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -36,16 +36,13 @@ import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; -import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; -import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; -import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.grpc.GrpcAppErrors; @@ -53,6 +50,7 @@ import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.security.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -208,6 +206,33 @@ private void requireGameSessionPeer() { } } + private void requireSocialGroupsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/social-groups-service")) { + throw new AdminAuthorizationException("Verified Social Groups workload identity is required"); + } + } + + private void requireCallerAccountSubject(long accountId) { + if (SessionContext.isInternalService()) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + + Long callerAccountId; + try { + callerAccountId = SessionContext.currentAccountIdOrNull(); + } catch (IllegalArgumentException ex) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + if (callerAccountId == null || callerAccountId.longValue() != accountId) { + throw new AdminAuthorizationException("Profile access is restricted to the caller account"); + } + } + private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { return new DirectTextCallerContext( @@ -307,6 +332,7 @@ public void createAccount( public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); net.firedevops.firemud.accountservice.dto.AuthenticationResult result = accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = @@ -316,6 +342,13 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + AuthenticateResponse response = + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { AuthenticateResponse response = AuthenticateResponse.newBuilder() @@ -346,8 +379,14 @@ public void requestEmailLoginOtp( RequestEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); accountService.requestEmailLoginOtp(requireEmail(request.getEmail())); responseObserver.onNext(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + RequestEmailLoginOtpResponse.newBuilder() + .setError(appError("RequestEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( RequestEmailLoginOtpResponse.newBuilder() @@ -362,12 +401,18 @@ public void requestEmailLoginOtp( public void verifyEmailLoginOtp( VerifyEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); var result = accountService.verifyEmailLoginOtp(request.getEmail(), request.getCode()); responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) .setAccountId(String.valueOf(result.accountId())) .build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError(appError("VerifyEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( AuthenticateResponse.newBuilder() @@ -392,40 +437,26 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantMembershipForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getRequestId()); - GetTenantMembershipForRuntimeResponse response = - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setMembershipExists(dto.membershipExists()) - .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) - .setMembershipVersion(dto.membershipVersion()) - .setMembershipLifecycleState(dto.membershipLifecycleState()) - .setMembershipAuthorityGeneration(dto.membershipAuthorityGeneration()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetTenantMembershipForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetTenantMembershipForRuntimeResponse.newBuilder() .setError( - appError("GetTenantMembershipForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetTenantMembershipForRuntimeResponse response = - GetTenantMembershipForRuntimeResponse.newBuilder() - .setError(appError("GetTenantMembershipForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetTenantMembershipForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantMembershipForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized player and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -434,41 +465,26 @@ public void getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getRealmAccessGrantForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getWorldSlug(), - request.getRealmSlug(), - request.getRequestId()); - GetRealmAccessGrantForRuntimeResponse response = - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setWorldSlug(dto.worldSlug()) - .setRealmSlug(dto.realmSlug()) - .setGranted(dto.granted()) - .setGrantVersion(dto.grantVersion()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetRealmAccessGrantForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( - appError("GetRealmAccessGrantForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetRealmAccessGrantForRuntimeResponse response = - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setError(appError("GetRealmAccessGrantForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetRealmAccessGrantForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError( + "GetRealmAccessGrantForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized player and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -477,43 +493,26 @@ public void getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantEntitlementsForRuntime( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getRequestId()); - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId(String.valueOf(dto.tenantId())) - .setGameplayAvailable(dto.gameplayAvailable()) - .setAllowPublicJoin(dto.allowPublicJoin()) - .setEntitlementVersion(dto.entitlementVersion()) - .setTenantBillingSequence(dto.tenantBillingSequence()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetTenantEntitlementsForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( - appError("GetTenantEntitlementsForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AuthenticationException ex) { - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(appError("GetTenantEntitlementsForRuntime", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(appError("GetTenantEntitlementsForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetTenantEntitlementsForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantEntitlementsForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized caller and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -521,16 +520,23 @@ public void getTenantEntitlementsForRuntime( public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getProfile( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); + requireCallerAccountSubject(accountId); + var dto = accountService.getProfile(tenantId, accountId); GetProfileResponse response = GetProfileResponse.newBuilder() .setProfileJson(JsonMapper.builder().build().writeValueAsString(dto)) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetProfileResponse response = GetProfileResponse.newBuilder() @@ -555,6 +561,7 @@ public void listPresenceVisibilityPolicies( StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); if (request.getAccountIdsCount() > MAX_ACCOUNT_IDS_PER_REQUEST) { throw new InvalidRequestException( @@ -578,6 +585,13 @@ public void listPresenceVisibilityPolicies( .build())); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError( + appError("ListPresenceVisibilityPolicies", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() @@ -605,14 +619,18 @@ public void listPresenceVisibilityPolicies( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); + requireCallerAccountSubject(accountId); JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); accountService.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), + tenantId, + accountId, displayName, bio, ProfilePresenceVisibilityPolicy.valueOf( @@ -622,6 +640,14 @@ public void updateProfile( UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() @@ -645,69 +671,30 @@ public void updateProfile( @Timed(value = "accountGrpc.exportAccount") public void exportAccount( ExportAccountRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportAccountData( - requirePositiveRequestId(request.getAccountId(), "accountId")); - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfilesJson(JsonMapper.builder().build().writeValueAsString(data.profiles())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportAccountResponse.newBuilder() + .setError( + appError( + "ExportAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @Timed(value = "accountGrpc.exportTenantData") public void exportTenantData( ExportTenantDataRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportTenantData( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setTenantId(String.valueOf(data.tenantId())) - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfileJson( - data.profile() != null - ? JsonMapper.builder().build().writeValueAsString(data.profile()) - : "") - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportTenantDataResponse.newBuilder() + .setError( + appError( + "ExportTenantData", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -716,9 +703,16 @@ public void deleteAccount( DeleteAccountRequest request, StreamObserver responseObserver) { try { AdminRoleGuard.requireAdminRole(); - accountService.deleteAccount(requirePositiveRequestId(request.getAccountId(), "accountId")); - DeleteAccountResponse response = DeleteAccountResponse.newBuilder().setSuccess(true).build(); - responseObserver.onNext(response); + requirePositiveRequestId(request.getAccountId(), "accountId"); + responseObserver.onNext( + DeleteAccountResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "DeleteAccount", + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented")) + .build()); responseObserver.onCompleted(); } catch (InvalidRequestException ex) { DeleteAccountResponse response = @@ -736,14 +730,6 @@ public void deleteAccount( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); - } catch (AccountLifecycleException ex) { - DeleteAccountResponse response = - DeleteAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("DeleteAccount", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); } catch (Exception ex) { DeleteAccountResponse response = DeleteAccountResponse.newBuilder() @@ -761,23 +747,16 @@ public void requestPasswordReset( net.firedevops.firemud.account.v1.RequestPasswordResetRequest request, StreamObserver responseObserver) { - try { - accountService.requestPasswordReset(new PasswordResetRequest(request.getEmail())); - var response = - net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestPasswordReset", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "RequestPasswordReset", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -786,24 +765,16 @@ public void completePasswordReset( net.firedevops.firemud.account.v1.CompletePasswordResetRequest request, StreamObserver responseObserver) { - try { - accountService.completePasswordReset( - new CompletePasswordResetRequest(request.getToken(), request.getNewPassword())); - var response = - net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() - .setSuccess(false) - .setError(appError("CompletePasswordReset", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "CompletePasswordReset", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -812,36 +783,16 @@ public void linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest request, StreamObserver responseObserver) { - try { - accountService.linkExternalAccount( - new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), - request.getProvider(), - request.getExternalId())); - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "LinkExternalAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -850,32 +801,16 @@ public void requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest request, StreamObserver responseObserver) { - try { - accountService.requestEmailVerification( - requirePositiveRequestId(request.getAccountId(), "accountId")); - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "RequestEmailVerification", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -883,24 +818,16 @@ public void requestEmailVerification( public void verifyEmail( net.firedevops.firemud.account.v1.VerifyEmailRequest request, StreamObserver responseObserver) { - try { - accountService.verifyEmail( - new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest(request.getToken())); - var response = - net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() - .setSuccess(false) - .setError(appError("VerifyEmail", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "VerifyEmail", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } private net.firedevops.firemud.shared.v1.ErrorDetail appError( 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 d843608e32..2a688ab098 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 @@ -669,7 +669,9 @@ private JoinPublicProductionResult executePendingJoinAttempt( VerifiedJoinScope scope, JoinOperation operation) { if (isConnectScopeExpired(scope)) { - return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + accountJoinOperationRepository.recordAttemptFailure( + requestId, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + return pendingJoinFailure(scope, "AUTH_UNAVAILABLE"); } JoinEvaluation evaluation = evaluateJoin(scope, false); @@ -740,6 +742,11 @@ private JoinPublicProductionResult executePendingJoinAttempt( accountTenantMembershipRepository .findByAccountIdAndTenantId(accountId, scope.tenantId()) .orElse(null); + if (isConnectScopeExpired(scope)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + return pendingJoinFailure(scope, "AUTH_UNAVAILABLE"); + } boolean transitioned = false; if (membership == null) { membership = new AccountTenantMembership(); @@ -2152,61 +2159,19 @@ public AccountDataExportDto exportAccountData(Long accountId) { @Transactional(readOnly = true) @Timed(value = "account.tenant_export") public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { - Account account = requireAccount(accountId); - Profile profile = - profileRepository.findByAccountIdAndTenantId(accountId, tenantId).orElse(null); - if (!accountTenantMembershipRepository.existsByAccountIdAndTenantId(accountId, tenantId) - && profile == null) { - throw new IllegalArgumentException("Tenant data not found"); - } - return new TenantDataExportDto( - tenantId, - accountMapper.toDto(account), - profile != null ? profileMapper.toDto(profile) : null); + throw new ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Tenant-admin export is unavailable until the tenant-wide export contract is implemented"); } @Override @Transactional @Timed(value = "account.delete") public void deleteAccount(Long accountId) { - Account account = requireAccount(accountId); - if (accountJoinOperationRepository.hasRetainedOperation(accountId)) { - throw new AccountLifecycleException( - "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", - "Account JOIN receipts require retention and deletion reconciliation"); - } - List subscriptions = - subscriptionRepository.findByAccountId(accountId); - Optional blockingSubscription = - subscriptions.stream().filter(this::isNonterminalSubscription).findFirst(); - if (blockingSubscription.isPresent()) { - throw new AccountLifecycleException( - "ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", - "Account has nonterminal tenant subscriptions; cancel or end subscriptions first"); - } - emailVerificationTokenRepository.deleteByAccountId(accountId); - passwordResetTokenRepository.deleteByAccountId(accountId); - accountRealmAccessGrantRepository.deleteByAccountId(accountId); - externalAccountRepository.deleteByAccountId(accountId); - paymentTransactionRepository.deleteByAccountId(accountId); - subscriptionRepository.deleteByAccountId(accountId); - profileRepository.deleteByAccountId(accountId); - accountTenantMembershipRepository.deleteByAccountId(accountId); - accountRepository.delete(account); - } - - private boolean isNonterminalSubscription( - net.firedevops.firemud.accountservice.entity.Subscription subscription) { - String status = - subscription.getStatus() == null - ? "" - : subscription.getStatus().trim().toLowerCase(java.util.Locale.ROOT); - boolean terminalStatus = - switch (status) { - case "canceled", "cancelled", "ended", "expired" -> true; - default -> false; - }; - return !terminalStatus || subscription.getEndedAt() == null; + requireAccount(accountId); + throw new AccountLifecycleException( + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented"); } @Override @@ -2244,13 +2209,16 @@ public void completePasswordReset(CompletePasswordResetRequest request) { passwordResetTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + LocalDateTime now = LocalDateTime.now(); + if (token.getExpiresAt().isBefore(now)) { throw new IllegalArgumentException("Token expired"); } + if (!passwordResetTokenRepository.consumeIfUnexpired(token, now)) { + throw new IllegalArgumentException("Invalid token"); + } net.firedevops.firemud.accountservice.entity.Account account = token.getAccount(); account.setPasswordHash(hashPassword(request.newPassword())); accountRepository.save(account); - passwordResetTokenRepository.delete(token); } @Override @@ -2302,13 +2270,16 @@ public void verifyEmail(VerifyEmailRequest request) { emailVerificationTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + LocalDateTime now = LocalDateTime.now(); + if (token.getExpiresAt().isBefore(now)) { throw new IllegalArgumentException("Token expired"); } + if (!emailVerificationTokenRepository.consumeIfUnexpired(token, now)) { + throw new IllegalArgumentException("Invalid token"); + } Account account = token.getAccount(); account.setEmailVerified(true); accountRepository.save(account); - emailVerificationTokenRepository.delete(token); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java index 1adc30f9a8..54c76c2bfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java @@ -13,7 +13,7 @@ import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -49,98 +49,33 @@ public VirtualCurrencyGrpcService( @Timed(value = "currencyGrpc.getBalance") public void getBalance( GetBalanceRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.getBalance( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode()); - GetBalanceResponse response = GetBalanceResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "GetBalance", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "GetBalance", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + GetBalanceResponse.newBuilder().setError(unavailable("GetBalance")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.addCurrency") public void addCurrency( AddCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.addCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - AddCurrencyResponse response = AddCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "AddCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "AddCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + AddCurrencyResponse.newBuilder().setError(unavailable("AddCurrency")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.spendCurrency") public void spendCurrency( SpendCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.spendCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "SpendCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "SpendCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + SpendCurrencyResponse.newBuilder().setError(unavailable("SpendCurrency")).build()); + responseObserver.onCompleted(); + } + + private ErrorDetail unavailable(String operation) { + String message = operation + " is unavailable"; + return meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); } } diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index a0058cdd88..4357cb661a 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -72,8 +72,6 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping - - account.v1.AccountService/GetTenantMembershipForRuntime - - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership grpc: @@ -85,6 +83,11 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + join-reconciliation: + batch-size: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE:50} + max-attempts: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS:12} + interval-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS:30000} + backoff-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS:30000} connect-scopes: cleanup: batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 526520c5d0..2ddcadc3bf 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -45,6 +45,11 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + join-reconciliation: + batch-size: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE:50} + max-attempts: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS:12} + interval-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS:30000} + backoff-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS:30000} connect-scopes: cleanup: batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} @@ -98,8 +103,6 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping - - account.v1.AccountService/GetTenantMembershipForRuntime - - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership diff --git a/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql b/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql new file mode 100644 index 0000000000..df24ae30b7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql @@ -0,0 +1,6 @@ +ALTER TABLE account_audit_outbox + ADD COLUMN receiver_audit_projection_version INTEGER; + +ALTER TABLE account_audit_outbox + ADD CONSTRAINT account_audit_outbox_projection_version_check + CHECK (receiver_audit_projection_version IS NULL OR receiver_audit_projection_version = 1); diff --git a/services/account-service/src/main/resources/db/migration/V38__account_join_reconciliation.sql b/services/account-service/src/main/resources/db/migration/V38__account_join_reconciliation.sql new file mode 100644 index 0000000000..bbb47b5ed6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V38__account_join_reconciliation.sql @@ -0,0 +1,26 @@ +-- PENDING JOIN evidence is retained until an exact deterministic outcome is proved. +-- Bounded reconciliation metadata schedules retries without expiring or deleting operations. +ALTER TABLE account_join_operations + ADD COLUMN reconciliation_attempt_count INTEGER NOT NULL DEFAULT 0, + ADD COLUMN last_reconciliation_attempt_at TIMESTAMP, + ADD COLUMN last_reconciliation_attempt_reason VARCHAR(128), + ADD COLUMN next_reconciliation_attempt_at TIMESTAMP NOT NULL + DEFAULT pg_catalog.timezone('UTC', CURRENT_TIMESTAMP), + ADD CONSTRAINT account_join_reconciliation_attempt_count_check + CHECK (reconciliation_attempt_count >= 0), + ADD CONSTRAINT account_join_reconciliation_attempt_detail_check + CHECK ((reconciliation_attempt_count = 0 + AND last_reconciliation_attempt_at IS NULL + AND last_reconciliation_attempt_reason IS NULL) + OR (reconciliation_attempt_count > 0 + AND last_reconciliation_attempt_at IS NOT NULL + AND last_reconciliation_attempt_reason IS NOT NULL + AND btrim(last_reconciliation_attempt_reason) <> '')); + +CREATE INDEX idx_account_join_operations_pending_reconciliation + ON account_join_operations( + next_reconciliation_attempt_at, + created_at, + request_id + ) + WHERE status = 'PENDING'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 2207175c8b..decacb239c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -1,20 +1,33 @@ package net.firedevops.firemud.accountservice; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.time.LocalDateTime; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.jooq.DSLContext; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -25,6 +38,8 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -60,6 +75,8 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -117,6 +134,201 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws .isEqualTo(1L); } + @Test + void concurrentPasswordResetAttemptsConsumeTokenExactlyOnce() throws Exception { + String suffix = UUID.randomUUID().toString(); + String email = "reset-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "reset-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + + CompletePasswordResetRequest request = + new CompletePasswordResetRequest(rawToken, "new-password"); + assertExactlyOneConcurrentSuccess( + () -> { + accountService.completePasswordReset(request); + return null; + }, + () -> { + accountService.completePasswordReset(request); + return null; + }); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isNotEqualTo("initial-hash"); + } + + @Test + void passwordResetConsumptionRollsBackWithAccountMutation() { + String suffix = UUID.randomUUID().toString(); + String email = "reset-rollback-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "rr-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + CompletePasswordResetRequest request = + new CompletePasswordResetRequest(rawToken, "new-password"); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + accountService.completePasswordReset(request); + throw new IllegalStateException("force rollback after token consumption"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("force rollback after token consumption"); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isEqualTo("initial-hash"); + + accountService.completePasswordReset(request); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isNotEqualTo("initial-hash"); + } + + @Test + void accountDeletionUnavailablePreservesTerminalSubscriptionAndPaymentEvidence() { + String suffix = UUID.randomUUID().toString(); + String email = "delete-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "del-" + suffix.substring(0, 12), + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + LocalDateTime subscriptionEndedAt = LocalDateTime.now().minusDays(1); + dsl.execute( + "INSERT INTO subscription (account_id, plan_id, status, started_at, ended_at, tenant_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + accountId, + "retained-plan", + "canceled", + subscriptionEndedAt.minusDays(30), + subscriptionEndedAt, + 1L); + String providerId = "pi-" + suffix.substring(0, 24); + dsl.execute( + "INSERT INTO payment_transaction " + + "(account_id, amount_cents, currency, status, provider_id, tenant_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + accountId, + 2500L, + "USD", + "succeeded", + providerId, + 1L); + + AccountLifecycleException exception = + Assertions.assertThrows( + AccountLifecycleException.class, () -> accountService.deleteAccount(accountId)); + + assertThat(exception.getCode()).isEqualTo("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE"); + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM accounts WHERE id = ?", accountId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM subscription " + + "WHERE account_id = ? AND status = 'canceled' AND ended_at IS NOT NULL", + accountId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM payment_transaction " + + "WHERE account_id = ? AND provider_id = ? AND status = 'succeeded'", + accountId, + providerId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void concurrentEmailVerificationAttemptsConsumeTokenExactlyOnce() throws Exception { + String suffix = UUID.randomUUID().toString(); + String email = "verify-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "verify-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO email_verification_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + + VerifyEmailRequest request = new VerifyEmailRequest(rawToken); + assertExactlyOneConcurrentSuccess( + () -> { + accountService.verifyEmail(request); + return null; + }, + () -> { + accountService.verifyEmail(request); + return null; + }); + + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM email_verification_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT email_verified FROM accounts WHERE id = ?", accountId) + .fetchOne(0, Boolean.class)) + .isTrue(); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = @@ -177,4 +389,37 @@ void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Except assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); assertThat(response.body()).contains("\"message\":\"tenantId must be positive\""); } + + private static void assertExactlyOneConcurrentSuccess(Callable first, Callable second) + throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future firstResult = executor.submit(() -> runWhenReleased(first, ready, start)); + Future secondResult = executor.submit(() -> runWhenReleased(second, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(firstResult.get(30, TimeUnit.SECONDS)) + .isNotEqualTo(secondResult.get(30, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private static boolean runWhenReleased( + Callable operation, CountDownLatch ready, CountDownLatch start) throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent recovery attempt"); + } + try { + operation.call(); + return true; + } catch (IllegalArgumentException alreadyConsumed) { + return false; + } + } } 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 new file mode 100644 index 0000000000..5955eff9dc --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH + }) +class AccountJoinPostgresIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + private static final String WORLD_SLUG = "join-proof-world"; + private static final String REALM_SLUG = "production"; + private static final String NAMESPACE_ID = "4f9e5c68-6251-4b22-8c3a-a0ed4a2d6bc1"; + private static final long GAME_INSTANCE_ID = 44L; + private static final long CATALOG_REVISION = 23L; + private static final long POINTER_VERSION = 17L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + + @Test + void terminalCommitWithLostAcknowledgementReadsBackExactStoredJoinResult() { + JoinFixture fixture = fixture("active"); + AtomicBoolean loseNextTerminalAcknowledgement = new AtomicBoolean(true); + doAnswer( + invocation -> { + invocation.callRealMethod(); + if ("COMMITTED".equals(invocation.getArgument(1)) + && loseNextTerminalAcknowledgement.compareAndSet(true, false)) { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + throw new IllegalStateException( + "simulated lost terminal commit acknowledgement"); + } + }); + } + return null; + }) + .when(joinOperationRepository) + .finish(anyString(), anyString(), anyString(), any(), any(), any()); + + JoinPublicProductionResult result = join(fixture); + + assertThat(result) + .isEqualTo( + new JoinPublicProductionResult( + true, + "JOINED", + fixture.accountId(), + fixture.tenantId(), + result.membershipId(), + 1L, + 1L, + true)); + assertThat(result.membershipId()).isPositive(); + assertThat( + dsl.fetchOne( + "SELECT status, outcome, request_digest, request_digest_version, entitlement_version, allow_public_join, membership_id, outcome_membership_version, outcome_membership_authority_generation " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId())) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("outcome", String.class)).isEqualTo("JOINED"); + assertThat(row.get("request_digest", String.class)).startsWith("sha256:"); + assertThat(row.get("request_digest_version", Integer.class)).isEqualTo(1); + assertThat(row.get("entitlement_version", Long.class)).isEqualTo(1L); + assertThat(row.get("allow_public_join", Boolean.class)).isTrue(); + assertThat(row.get("membership_id", Long.class)).isEqualTo(result.membershipId()); + assertThat(row.get("outcome_membership_version", Long.class)).isEqualTo(1L); + assertThat(row.get("outcome_membership_authority_generation", Long.class)) + .isEqualTo(1L); + }); + assertTransitionAndAuditOutboxOnce(fixture, result.membershipId()); + } + + @Test + void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { + JoinFixture fixture = fixture("active"); + AtomicBoolean failNextTerminalAttempt = new AtomicBoolean(true); + doAnswer( + invocation -> { + invocation.callRealMethod(); + if ("COMMITTED".equals(invocation.getArgument(1)) + && failNextTerminalAttempt.compareAndSet(true, false)) { + throw new IllegalStateException( + "simulated failure before terminal transaction commit"); + } + return null; + }) + .when(joinOperationRepository) + .finish(anyString(), anyString(), anyString(), any(), any(), any()); + + AuthenticationException uncertain = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(uncertain.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat( + dsl.fetchOne( + "SELECT status, outcome, request_digest, membership_id, last_attempt_failure_code " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId())) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("outcome", String.class)).isNull(); + assertThat(row.get("request_digest", String.class)).isNull(); + assertThat(row.get("membership_id", Long.class)).isNull(); + assertThat(row.get("last_attempt_failure_code", String.class)) + .isEqualTo("AUTH_UNAVAILABLE"); + }); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + JoinPublicProductionResult recovered = join(fixture); + + assertThat(recovered.success()).isTrue(); + assertThat(recovered.outcomeCode()).isEqualTo("JOINED"); + assertThat(recovered.replayed()).isFalse(); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertTransitionAndAuditOutboxOnce(fixture, recovered.membershipId()); + } + + @Test + void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { + JoinFixture fixture = fixture("grace"); + + JoinPublicProductionResult failed = join(fixture); + JoinPublicProductionResult replayed = join(fixture); + + assertThat(failed.success()).isFalse(); + assertThat(failed.outcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(failed.replayed()).isFalse(); + assertThat(replayed) + .isEqualTo( + new JoinPublicProductionResult( + failed.success(), + failed.outcomeCode(), + failed.accountId(), + failed.tenantId(), + failed.membershipId(), + failed.membershipVersion(), + failed.membershipAuthorityGeneration(), + true)); + String originalDigest = + dsl.resultQuery( + "SELECT request_digest FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class); + assertThat(originalDigest).startsWith("sha256:"); + assertThat( + dsl.resultQuery( + "SELECT status || ':' || outcome FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + dsl.execute( + "UPDATE subscription SET status = 'active', entitlement_version = 2 WHERE tenant_id = ?", + fixture.tenantId()); + AuthenticationException conflict = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(conflict.getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat( + dsl.resultQuery( + "SELECT request_digest FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo(originalDigest); + assertThat( + dsl.resultQuery( + "SELECT status || ':' || outcome FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + 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( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "join-proof-" + suffix, + "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); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + tenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "join-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + tenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + } + + private long countMemberships(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + } + + private long countJoinOutbox(JoinFixture fixture) { + UUID eventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + eventId, + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + membershipId, + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND payload LIKE ?", + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId()) + .getBytes(StandardCharsets.UTF_8)), + "%" + fixture.requestId() + "%") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + private record JoinFixture( + long accountId, + long tenantId, + String requestId, + DirectTextCallerContext caller, + String connectScopeId) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java new file mode 100644 index 0000000000..167cc948af --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -0,0 +1,679 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.VerifiedJoinScope; +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.service.AccountJoinReconciliationService; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.account.join-reconciliation.interval-ms=3600000", + "firemud.account.join-reconciliation.batch-size=20", + "firemud.account.join-reconciliation.max-attempts=2", + "firemud.account.join-reconciliation.backoff-ms=1000" + }) +class AccountJoinReconciliationPostgresIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("a825f7ef-0ea3-4e8c-bf7c-a20242b4c931"); + private static final String WORLD_SLUG = "join-reconciliation-world"; + private static final String REALM_SLUG = "production"; + private static final String NAMESPACE_ID = "c3b77762-3cc2-4f76-9fc8-5f4938fe7924"; + private static final long GAME_INSTANCE_ID = 73L; + private static final long CATALOG_REVISION = 29L; + private static final long POINTER_VERSION = 11L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountJoinReconciliationService reconciliationService; + @Autowired private AccountJoinOperationRepository joinOperationRepository; + @Autowired private AccountConnectScopeRepository connectScopeRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void reconciliationIntentDefaultUsesUtcForDueReadbackInNonUtcDatabaseSession() { + JoinFixture fixture = fixture("active"); + VerifiedJoinScope scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); + String callerBinding = "direct-text-session:" + fixture.caller().sessionId(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + assertThat( + dsl.resultQuery("SELECT current_setting('TimeZone')").fetchOne(0, String.class)) + .isEqualTo("Pacific/Auckland"); + + LocalDateTime expectedUtcDueTime = + dsl.resultQuery("SELECT pg_catalog.timezone('UTC', CURRENT_TIMESTAMP)") + .fetchOne(0, LocalDateTime.class); + String intentDigest = AccountJoinDigest.intent(fixture.requestId(), scope, callerBinding); + assertThat( + joinOperationRepository.insertIntent( + fixture.requestId(), scope, callerBinding, intentDigest)) + .isTrue(); + + var inserted = joinOperationRepository.find(fixture.requestId()).orElseThrow(); + assertThat(inserted.nextReconciliationAttemptAt()) + .isEqualTo(expectedUtcDueTime.toInstant(ZoneOffset.UTC)); + assertThat( + joinOperationRepository + .findDuePendingReconciliation( + expectedUtcDueTime.toInstant(ZoneOffset.UTC), 20) + .stream() + .map(AccountJoinOperationRepository.JoinOperation::requestId)) + .contains(fixture.requestId()); + + // SET LOCAL and the synthetic intent are both discarded, so no pooled session inherits + // the test timezone and no fixture row remains. + status.setRollbackOnly(); + }); + } + + @Test + void dueAggregateCountsOnlyPendingRowsDueAtTheCapturedTime() { + Instant capturedNow = Instant.now().plusSeconds(10); + long baselineCount = joinOperationRepository.countDuePendingReconciliation(capturedNow); + + JoinFixture due = committedEvidencePendingFixture(); + JoinFixture future = committedEvidencePendingFixture(); + JoinFixture terminal = fixture("active"); + JoinPublicProductionResult terminalResult = join(terminal); + assertThat(terminalResult.success()).isTrue(); + assertThat(terminalResult.outcomeCode()).isEqualTo("JOINED"); + + LocalDateTime futureDueAt = + LocalDateTime.ofInstant(capturedNow.plusSeconds(3_600), ZoneOffset.UTC); + assertThat( + dsl.execute( + "UPDATE account_join_operations SET next_reconciliation_attempt_at = ? WHERE request_id = ? AND status = 'PENDING'", + futureDueAt, + future.requestId())) + .isEqualTo(1); + + assertThat(joinOperationRepository.countDuePendingReconciliation(capturedNow)) + .isEqualTo(baselineCount + 1); + List duePage = + joinOperationRepository.findDuePendingReconciliation(capturedNow, 100); + assertThat(duePage).extracting(JoinOperation::requestId).contains(due.requestId()); + assertThat(duePage) + .extracting(JoinOperation::requestId) + .doesNotContain(future.requestId(), terminal.requestId()); + } + + @Test + void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplicates() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult original = join(fixture); + assertThat(original.success()).isTrue(); + assertThat(original.outcomeCode()).isEqualTo("JOINED"); + long membershipId = original.membershipId(); + + // This is a synthetic ambiguous row assembled from a genuine committed JOIN. The current + // atomic terminal transaction cannot naturally commit membership/audit while leaving the + // operation PENDING; this fixture tests the exact readback branch without inventing evidence. + makeOperationPendingWithRetainedEvidence(fixture, 2); + Instant scopeExpiry = expireScopeBeforeReconciliationButAfterEvaluation(fixture); + + Instant now = scopeExpiry.plusSeconds(1); + reconciliationService.reconcileDueOperations(now); + + assertOperation(fixture, "COMMITTED", "JOINED", 2, null); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 1 AND outcome_membership_authority_generation = 1", + fixture.requestId(), + membershipId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertMembershipAndAuditOnce(fixture, membershipId); + + JoinPublicProductionResult retry = join(fixture); + assertThat(retry.success()).isTrue(); + assertThat(retry.outcomeCode()).isEqualTo("JOINED"); + assertThat(retry.replayed()).isTrue(); + assertThat(retry.membershipId()).isEqualTo(membershipId); + assertMembershipAndAuditOnce(fixture, membershipId); + } + + @Test + void retainedLegacyReceiptIdsWithoutProjectionVersionStayPending() { + JoinFixture fixture = committedEvidencePendingFixture(); + UUID auditEventId = joinAuditEventId(fixture.requestId()); + int updated = + dsl.execute( + "UPDATE account_audit_outbox SET receiver_audit_projection_version = NULL WHERE audit_event_id = ? AND delivery_status = 'COMMITTED'", + auditEventId); + assertThat(updated).isEqualTo(1); + assertThat( + dsl.resultQuery( + "SELECT receiver_receipt_id FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, String.class)) + .isNotBlank(); + assertThat( + dsl.resultQuery( + "SELECT receiver_log_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, String.class)) + .isNotBlank(); + assertThat( + dsl.resultQuery( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, Integer.class)) + .isNull(); + + assertUnresolvedAtThreshold(fixture, "JOIN_AUDIT_RECEIPT_UNVERIFIED"); + assertOperation(fixture, "PENDING", null, 2, "JOIN_AUDIT_RECEIPT_UNVERIFIED"); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + } + + @Test + void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics() { + JoinFixture absentScope = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(absentScope.connectScopeId())); + assertUnresolvedAtThreshold(absentScope, "JOIN_SCOPE_EVIDENCE_ABSENT"); + assertThat(countMemberships(absentScope)).isEqualTo(1L); + assertThat(countJoinOutbox(absentScope)).isEqualTo(1L); + + JoinFixture expiredWithoutMembership = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + expiredWithoutMembership.accountId(), + expiredWithoutMembership.tenantId()); + Instant scopeExpiry = + expireScopeBeforeReconciliationButAfterEvaluation(expiredWithoutMembership); + assertUnresolvedAtThreshold( + expiredWithoutMembership, "MEMBERSHIP_EVIDENCE_ABSENT", scopeExpiry.plusSeconds(1)); + assertThat(countMemberships(expiredWithoutMembership)).isZero(); + assertThat(countJoinOutbox(expiredWithoutMembership)).isEqualTo(1L); + } + + @Test + void absentMembershipOrAuditEnvelopeCannotTerminalizePendingOperation() { + JoinFixture absentMembership = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + absentMembership.accountId(), + absentMembership.tenantId()); + assertUnresolved(absentMembership, "MEMBERSHIP_EVIDENCE_ABSENT"); + assertThat(countJoinOutbox(absentMembership)).isEqualTo(1L); + + JoinFixture absentAudit = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_audit_outbox WHERE audit_event_id = ?", + joinAuditEventId(absentAudit.requestId())); + assertUnresolved(absentAudit, "JOIN_AUDIT_ENVELOPE_ABSENT"); + assertThat(countMemberships(absentAudit)).isEqualTo(1L); + assertThat(countJoinOutbox(absentAudit)).isZero(); + } + + @Test + void concurrentCallerRetryAndReconcilerKeepSingleMembershipTransitionAndAudit() throws Exception { + JoinFixture fixture = committedEvidencePendingFixture(); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Instant now = Instant.now().plusSeconds(1); + Future reconciliation = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + Future callerRetry = + executor.submit( + () -> { + await(start); + return join(fixture); + }); + start.countDown(); + + reconciliation.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult retry = callerRetry.get(30, TimeUnit.SECONDS); + + assertThat(retry.success()).isTrue(); + assertThat(retry.outcomeCode()).isIn("JOINED", "ALREADY_ACTIVE"); + assertOperation(fixture, "COMMITTED", retry.outcomeCode(), 0, null); + assertMembershipAndAuditOnce(fixture, originalMembershipId(fixture)); + } finally { + executor.shutdownNow(); + } + } + + @Test + void naturallyAbandonedPendingIntentRemainsDueAfterConfiguredDiagnosticThreshold() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + + JoinPublicProductionResult attempt = join(fixture); + + assertThat(attempt.success()).isFalse(); + assertThat(attempt.outcomeCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertOperation(fixture, "PENDING", null, 0, null); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + Instant firstAttemptAt = Instant.now().plusSeconds(1); + reconciliationService.reconcileDueOperations(firstAttemptAt); + assertOperation(fixture, "PENDING", null, 1, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt); + assertOperation(fixture, "PENDING", null, 1, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt.plusMillis(1500)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt.plusSeconds(5)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + reconciliationService.reconcileDueOperations(firstAttemptAt.plusSeconds(7)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + @Test + void aboveThresholdAttemptCountIsPreservedWithoutOverflowAndKeepsScheduling() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + join(fixture); + setReconciliationAttempts(fixture, Integer.MAX_VALUE); + + Instant now = Instant.now().plusSeconds(2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, Integer.MAX_VALUE, "JOIN_OPERATION_POLICY_UNPROVEN"); + reconciliationService.reconcileDueOperations(now.plusSeconds(2)); + assertOperation(fixture, "PENDING", null, Integer.MAX_VALUE, "JOIN_OPERATION_POLICY_UNPROVEN"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + @Test + void staleDueTimestampFencesLostUpdateAfterCounterSaturatesAtThreshold() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + setReconciliationAttempts(fixture, 2); + JoinOperation observed = joinOperationRepository.find(fixture.requestId()).orElseThrow(); + Instant firstAttemptAt = Instant.now().plusSeconds(2); + Instant firstNextAttemptAt = firstAttemptAt.plusMillis(1_000); + + boolean firstUpdated = + joinOperationRepository.recordReconciliationAttempt( + fixture.requestId(), + observed.reconciliationAttemptCount(), + 2, + observed.nextReconciliationAttemptAt(), + firstAttemptAt, + "FIRST_THRESHOLD_ATTEMPT", + firstNextAttemptAt); + assertThat(firstUpdated).isTrue(); + + boolean staleUpdated = + joinOperationRepository.recordReconciliationAttempt( + fixture.requestId(), + observed.reconciliationAttemptCount(), + 2, + observed.nextReconciliationAttemptAt(), + firstNextAttemptAt, + "STALE_RECONCILIATION_CANDIDATE", + firstNextAttemptAt.plusMillis(1_000)); + + assertThat(staleUpdated).isFalse(); + assertOperation(fixture, "PENDING", null, 2, "FIRST_THRESHOLD_ATTEMPT"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + @Test + void twoWorkersRecoverThresholdPendingEvidenceWithoutDuplicatingMembershipOrAudit() + throws Exception { + JoinFixture fixture = committedEvidencePendingFixture(); + setReconciliationAttempts(fixture, 2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Instant now = Instant.now().plusSeconds(1); + Future first = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + Future second = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + start.countDown(); + first.get(30, TimeUnit.SECONDS); + second.get(30, TimeUnit.SECONDS); + + assertOperation(fixture, "COMMITTED", "JOINED", 2, null); + assertMembershipAndAuditOnce(fixture, originalMembershipId(fixture)); + } finally { + executor.shutdownNow(); + } + } + + private JoinFixture committedEvidencePendingFixture() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult committed = join(fixture); + assertThat(committed.success()).isTrue(); + assertThat(committed.outcomeCode()).isEqualTo("JOINED"); + makeOperationPendingWithRetainedEvidence(fixture); + return fixture; + } + + private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture) { + makeOperationPendingWithRetainedEvidence(fixture, 0); + } + + private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int attempts) { + int updated = + dsl.execute( + "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CASE WHEN ? = 0 THEN NULL ELSE pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '2 seconds' END, last_reconciliation_attempt_reason = CASE WHEN ? = 0 THEN NULL ELSE 'PRIOR_RECONCILIATION_ATTEMPT' END, next_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", + attempts, + attempts, + attempts, + fixture.requestId()); + assertThat(updated).isEqualTo(1); + int auditUpdated = + dsl.execute( + "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + joinAuditEventId(fixture.requestId()), + fixture.tenantId()); + assertThat(auditUpdated).isEqualTo(1); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + } + + private void setReconciliationAttempts(JoinFixture fixture, int attempts) { + int updated = + dsl.execute( + "UPDATE account_join_operations SET reconciliation_attempt_count = ?, last_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '2 seconds', last_reconciliation_attempt_reason = 'PRIOR_RECONCILIATION_ATTEMPT', next_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'PENDING'", + attempts, + fixture.requestId()); + assertThat(updated).isEqualTo(1); + } + + private Instant expireScopeBeforeReconciliationButAfterEvaluation(JoinFixture fixture) { + String expiresAt = + dsl.resultQuery( + "SELECT connect_scope_expires_at FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(fixture.connectScopeId())) + .fetchOne(0, String.class); + assertThat(expiresAt).isNotBlank(); + return Instant.parse(expiresAt); + } + + private void assertUnresolved(JoinFixture fixture, String reason) { + Instant now = Instant.now().plusSeconds(2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 1, reason); + + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 1, reason); + } + + private void assertUnresolvedAtThreshold(JoinFixture fixture, String reason) { + assertUnresolvedAtThreshold(fixture, reason, Instant.now().plusSeconds(2)); + } + + private void assertUnresolvedAtThreshold(JoinFixture fixture, String reason, Instant now) { + setReconciliationAttempts(fixture, 2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 2, reason); + + reconciliationService.reconcileDueOperations(now.plusMillis(1_500)); + assertOperation(fixture, "PENDING", null, 2, reason); + } + + private void assertOperation( + JoinFixture fixture, String status, String outcome, int attempts, String reason) { + var row = + dsl.resultQuery( + "SELECT status, outcome, reconciliation_attempt_count, last_reconciliation_attempt_reason, (next_reconciliation_attempt_at > last_reconciliation_attempt_at) AS backoff_scheduled FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("status", String.class)).isEqualTo(status); + assertThat(row.get("outcome", String.class)).isEqualTo(outcome); + assertThat(row.get("reconciliation_attempt_count", Integer.class)).isEqualTo(attempts); + assertThat(row.get("last_reconciliation_attempt_reason", String.class)).isEqualTo(reason); + if (attempts > 0) { + assertThat(row.get("backoff_scheduled", Boolean.class)).isTrue(); + } + } + + private long originalMembershipId(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private void assertMembershipAndAuditOnce(JoinFixture fixture, long membershipId) { + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND gameplay_admission_allowed = TRUE AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + membershipId, + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' AND payload_digest_version = 1 AND payload_digest LIKE 'sha256:%' AND payload LIKE ?", + joinAuditEventId(fixture.requestId()), + fixture.tenantId(), + "%" + fixture.requestId() + "%") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + private long countMemberships(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countJoinOutbox(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + joinAuditEventId(fixture.requestId()), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + } + + private JoinFixture fixture(String subscriptionStatus) { + String suffix = UUID.randomUUID().toString(); + String requestId = "join-rec-" + suffix; + long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "join-rec-" + suffix, + "join-rec-" + 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-reconcile", + subscriptionStatus); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + tenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "join-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + tenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static void await(CountDownLatch start) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent JOIN test did not receive its start signal"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("concurrent JOIN test was interrupted", ex); + } + } + + private record JoinFixture( + long accountId, + long tenantId, + String requestId, + DirectTextCallerContext caller, + String connectScopeId) {} +} 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 f8cf352cf7..eae5444b36 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 @@ -207,6 +207,12 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { Long.class, auditEventId)) .isEqualTo(1L); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + auditEventId)) + .isNull(); } @Test @@ -293,6 +299,12 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { String.class, minimizedEventId)) .isEqualTo("MINIMIZED"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + minimizedEventId)) + .isEqualTo(1); assertThat( jdbc.queryForObject( "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", @@ -305,6 +317,25 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { String.class, committedEventId)) .isEqualTo("COMMITTED"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + committedEventId)) + .isEqualTo(1); + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE account_audit_outbox SET receiver_audit_projection_version = 2 WHERE audit_event_id = ?", + committedEventId)) + .isInstanceOf(org.springframework.dao.DataAccessException.class) + .hasStackTraceContaining("account_audit_outbox_projection_version_check"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + committedEventId)) + .isEqualTo(1); assertThat(outbox.pending(10, Instant.now())) .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); @@ -507,6 +538,31 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio } } + @Test + void markDeliveredRejectsBlankReceiverIdentityWithoutChangingPendingRow() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID eventId = UUID.randomUUID(); + outbox.append(eventId, "platform", null, "ACCOUNT_REGISTERED", "{\"accountId\":44}"); + + assertThatThrownBy(() -> outbox.markDelivered(eventId, " ", "projection-id", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Verified audit delivery requires nonblank identity"); + + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + eventId)) + .isEqualTo("PENDING"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + eventId)) + .isNull(); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java index cc3ebf0e79..d276f2dec9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.accountservice.client; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -29,12 +31,16 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.slf4j.LoggerFactory; @@ -44,6 +50,26 @@ class LoggingAdminClientTest { private static final long TRANSACTION_ID = 30L; private static final String PAYMENT_PAYLOAD = "{\"accountId\":10,\"transactionId\":30}"; + @Test + void acceptsOnlyExactCommittedReceiptWithCurrentProjectionVersion() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())).thenReturn(response(1)); + LoggingAdminClient.AuditDeliveryResult result = newClient(stub).deliver(validEnvelope()); + assertThat(result.receiptId()).isEqualTo("receipt-1"); + assertThat(result.logEventId()).isEqualTo("projection-1"); + assertThat(result.minimized()).isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, -1}) + void rejectsMissingOrUnsupportedProjectionVersion(int version) throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())).thenReturn(response(version)); + assertThatThrownBy(() -> newClient(stub).deliver(validEnvelope())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account audit receiver did not prove a supported audit projection version"); + } + @Test void logPaymentIgnoresTransportFailureAndPreservesAuditEnvelope() throws Exception { var stub = mockStub(); @@ -91,7 +117,7 @@ void logPaymentIgnoresUnexpectedRuntimeFailureAndPreservesAuditEnvelope() throws void logPaymentIgnoresMismatchedReceiptAndPreservesAuditEnvelope() throws Exception { var stub = mockStub(); when(stub.createLogEvent(any())) - .thenReturn(CreateLogEventResponse.newBuilder().setAuditEventId("other-event").build()); + .thenReturn(response(1).toBuilder().setAuditEventId("other-event").build()); LoggingAdminClient client = newClient(stub); assertDoesNotThrow(() -> client.logPayment(TENANT_ID, ACCOUNT_ID, TRANSACTION_ID)); @@ -103,7 +129,7 @@ void logPaymentIgnoresMismatchedReceiptAndPreservesAuditEnvelope() throws Except void deliverStillThrowsWhenTheReceiverReturnsMismatchedReceiptEvidence() throws Exception { var stub = mockStub(); when(stub.createLogEvent(any())) - .thenReturn(CreateLogEventResponse.newBuilder().setAuditEventId("other-event").build()); + .thenReturn(response(1).toBuilder().setAuditEventId("other-event").build()); LoggingAdminClient client = newClient(stub); assertThrows(IllegalStateException.class, () -> client.deliver(validEnvelope())); @@ -193,6 +219,23 @@ private static AccountAuditEnvelope validEnvelope() { payload); } + private static CreateLogEventResponse response(int projectionVersion) { + AccountAuditEnvelope envelope = validEnvelope(); + return CreateLogEventResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId(Long.toString(TENANT_ID)) + .setAuditEventId(envelope.auditEventId().toString()) + .setReceiptId("receipt-1") + .setLogEventId("projection-1") + .setSchemaVersion(envelope.schemaVersion()) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED) + .setAuditProjectionVersion(projectionVersion) + .build(); + } + private static AccountAuditEnvelope envelopeWithScope(String scope, Long tenantId) { AccountAuditEnvelope envelope = validEnvelope(); return new AccountAuditEnvelope( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 20010b7bb1..34864846b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -19,7 +19,6 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.TenantDataExportDto; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.service.AccountService; @@ -112,13 +111,15 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { } @Test - void deleteAccountAllowsScopedTenantAdmin() throws Exception { + void deleteAccountDeniesPlatformAdminBeforeServiceMutation() throws Exception { String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE")); + + verifyNoInteractions(accountService); } @Test @@ -147,10 +148,7 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { } @Test - void exportTenantDataAllowsScopedTenantRole() throws Exception { - AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); - when(accountService.exportTenantData(7L, 42L)) - .thenReturn(new TenantDataExportDto(7L, account, null)); + void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception { String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("moderator")))); @@ -159,8 +157,9 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { get("/accounts/42/tenant-export") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isNotImplemented()); + + verifyNoInteractions(accountService); } @Test @@ -195,7 +194,7 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { } @Test - void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { + void deleteAccountDeniesCurrentAccountBeforeServiceMutation() throws Exception { String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); mockMvc @@ -203,8 +202,10 @@ void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep delete("/accounts/42") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE")); + + verifyNoInteractions(accountService); } @Test 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 new file mode 100644 index 0000000000..d469ec4998 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; + +class AccountMigrationVersionTest { + @Test + void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() + throws IOException, URISyntaxException { + List migrations; + var migrationDirectory = + Path.of( + Objects.requireNonNull( + AccountMigrationVersionTest.class.getClassLoader().getResource("db/migration")) + .toURI()); + try (var files = Files.list(migrationDirectory)) { + migrations = + files + .map(path -> Objects.requireNonNull(path.getFileName()).toString()) + .filter(name -> name.startsWith("V") && name.endsWith(".sql")) + .sorted() + .toList(); + } + + assertThat(migrations) + .contains( + "V28__account_audit_delivery_backoff.sql", + "V37__verified_audit_projection_evidence.sql", + "V38__account_join_reconciliation.sql") + .doesNotContain("V28__account_join_reconciliation.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")); + } + + private static MigrationVersion version(String name) { + int separator = name.indexOf("__"); + assertThat(separator).as("versioned migration naming: %s", name).isGreaterThan(1); + return MigrationVersion.fromVersion(name.substring(1, separator)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java index cdad776a8c..ceb6732cb4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java @@ -9,7 +9,6 @@ import io.grpc.Status; import java.util.List; import java.util.Map; -import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.JwtUtil; @@ -48,23 +47,15 @@ void allowsValidToken() { } @Test - void allowsConfiguredUnauthenticatedRuntimeMethodWithoutToken() { - AuthTokenInterceptor runtimeAwareInterceptor = - new AuthTokenInterceptor( - jwtUtil, - Set.of( - AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName())); - TestServerCall call = - new TestServerCall( - AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName()); - Metadata headers = new Metadata(); - - ServerCall.Listener listener = - runtimeAwareInterceptor.interceptCall( - call, headers, (c, h) -> new ServerCall.Listener<>() {}); - - assertNotNull(listener); - assertEquals(null, call.status); + void rejectsRuntimeMethodsWithoutToken() { + for (String method : + List.of( + AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName(), + AccountServiceGrpc.getGetTenantEntitlementsForRuntimeMethod().getFullMethodName())) { + TestServerCall call = new TestServerCall(method); + interceptor.interceptCall(call, new Metadata(), (c, h) -> new ServerCall.Listener<>() {}); + assertEquals(Status.UNAUTHENTICATED.getCode(), call.status.getCode()); + } } private static class TestServerCall extends ServerCall { 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 new file mode 100644 index 0000000000..9df682a400 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -0,0 +1,832 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +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.VerifiedJoinScope; +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.AccountConnectScopeRepository.ConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJoinReconciliationServiceTest { + private static final Instant NOW = Instant.parse("2026-09-24T00:00:00Z"); + private static final Instant EVALUATED_AT = NOW.minusSeconds(60); + private static final Instant EXPIRED_AT = NOW.minusSeconds(30); + private static final long ACCOUNT_ID = 101L; + private static final long TENANT_ID = 7L; + private static final long MEMBERSHIP_ID = 501L; + private static final long MEMBERSHIP_VERSION = 4L; + private static final long MEMBERSHIP_AUTHORITY_GENERATION = 3L; + private static final String REQUEST_ID = "join-request-1"; + private static final String CONNECT_SCOPE_ID = "retained-connect-scope-token"; + private static final String CALLER_BINDING = "game-session:instance-a"; + private static final String WORLD_SLUG = "demo-world"; + private static final String REALM_SLUG = "production"; + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + + @Test + void dueBacklogMetricsExposeBoundedPageExcessWithoutLoadingRows() { + Fixture fixture = fixture(3); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)).thenReturn(14L); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)).thenReturn(List.of()); + + fixture.service.reconcileDueOperations(NOW); + + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(14); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(4); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isZero(); + verify(fixture.joinOperations).findDuePendingReconciliation(NOW, 10); + verify(fixture.joinOperations, never()).lockAccount(ACCOUNT_ID); + } + + @Test + void dueBacklogMetricsClearWhenTheSampledQueueFallsBelowThePage() { + Fixture fixture = fixture(3); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)).thenReturn(12L, 2L, 0L); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)).thenReturn(List.of()); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(12); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(2); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(2); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isZero(); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isZero(); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isZero(); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isZero(); + } + + @Test + void dueBacklogCountFailureKeepsLastSampleAndStillRunsReadbackSafely() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)) + .thenReturn(13L) + .thenThrow(new IllegalStateException("transient count failure")); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) + .thenReturn(List.of(), List.of(pending)); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + fixture.service.reconcileDueOperations(NOW); + + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(13); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(3); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isEqualTo(1); + verify(fixture.joinOperations, org.mockito.Mockito.times(2)) + .findDuePendingReconciliation(NOW, 10); + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.memberships, fixture.auditOutbox); + assertThat(reconciliationCounter(fixture, "failure")).isEqualTo(1); + } + + @Test + void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { + Fixture fixture = fixture(5); + JoinOperation pending = pendingOperation(5, 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.of(activeJoinMembership())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); + + fixture.service.reconcileDueOperations(NOW); + + InOrder lockOrder = inOrder(fixture.joinOperations); + lockOrder.verify(fixture.joinOperations).lockAccount(ACCOUNT_ID); + lockOrder.verify(fixture.joinOperations).findForUpdate(REQUEST_ID); + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.joinOperations, never()) + .recordReconciliationAttempt( + anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); + assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); + } + + @ParameterizedTest + @MethodSource("unverifiedAuditDeliveryEvidence") + void incompleteOrLegacyAuditDeliveryEvidenceStaysPending( + String status, Integer version, String receiptId, String projectionId) { + 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.of(activeJoinMembership())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + new JoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()), + status, + version, + receiptId, + projectionId))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_RECEIPT_UNVERIFIED", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_RECEIPT_UNVERIFIED", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + } + + private static List unverifiedAuditDeliveryEvidence() { + return List.of( + Arguments.of("PENDING", null, null, null), + Arguments.of("COMMITTED", null, "legacy-receipt", "legacy-log-event-id"), + Arguments.of("COMMITTED", 2, "receipt-v2", "projection-v2"), + Arguments.of("COMMITTED", 1, " ", "projection-v1"), + Arguments.of("MINIMIZED", 1, "receipt-v1", "projection-v1")); + } + + @Test + void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThreshold() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(3, 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, + 3, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(40_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 3, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(40_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.auditOutbox); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); + } + + @Test + void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { + Fixture fixture = fixture(1); + 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.of(activeJoinMembership())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 1, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + JoinOperation atThreshold = pendingOperation(1, NOW.plusMillis(5_000)); + when(fixture.joinOperations.findDuePendingReconciliation(NOW.plusMillis(6_000), 10)) + .thenReturn(List.of(atThreshold)); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(atThreshold)); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 1, + 1, + NOW.plusMillis(5_000), + NOW.plusMillis(6_000), + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(16_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW.plusMillis(6_000)); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 1, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isEqualTo(1); + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 1, + 1, + NOW.plusMillis(5_000), + NOW.plusMillis(6_000), + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(16_000)); + } + + @Test + void readbackExceptionAtTheThresholdStillSchedulesAnotherAttempt() { + Fixture fixture = fixture(2); + JoinOperation pending = pendingOperation(2, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)) + .thenThrow(new IllegalStateException("transient read failure")) + .thenReturn(Optional.of(pending)); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 2, + 2, + NOW.minusSeconds(1), + NOW, + "JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(20_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 2, + 2, + NOW.minusSeconds(1), + NOW, + "JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(20_000)); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); + } + + @Test + void retryDelayDoublesFromInitialDelayAndSaturatesWithoutArithmeticOverflow() { + assertRetryDelay(0, 12, 5_000, 5_000); + assertRetryDelay(1, 12, 5_000, 10_000); + assertRetryDelay(5, 12, 5_000, 160_000); + assertRetryDelay(6, 12, 5_000, 300_000); + assertRetryDelay(2, 2, 5_000, 20_000); + assertRetryDelay(Integer.MAX_VALUE, Integer.MAX_VALUE, 5_000, 300_000); + assertRetryDelay(1, 2, Long.MAX_VALUE, Long.MAX_VALUE); + } + + private static void assertRetryDelay( + int attemptCount, int maxAttempts, long initialDelayMillis, long expectedDelayMillis) { + Fixture fixture = fixture(maxAttempts, initialDelayMillis); + JoinOperation pending = pendingOperation(attemptCount, 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()); + Instant expectedNextAttempt = NOW.plusMillis(expectedDelayMillis); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + attemptCount, + maxAttempts, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + expectedNextAttempt)) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + attemptCount, + maxAttempts, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + expectedNextAttempt); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void wrongPayloadDigestStaysPending() { + 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.of(activeJoinMembership())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong"))))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { + 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.of(activeJoinMembership())); + String mismatchedPayload = joinAuditEnvelope("other-world", TENANT_ID, "unused").payload(); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope( + "other-world", + TENANT_ID, + AccountAuditDigest.ofPayload(mismatchedPayload))))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void wrongRetainedTargetStaysPending() { + 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("PRIVATE", TENANT_ID, WORLD_SLUG))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_MISMATCH", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_MISMATCH", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.memberships, fixture.auditOutbox); + } + + @Test + void repeatedRunDoesNotFinishSameJoinTwice() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) + .thenReturn(List.of(pending), List.of()); + 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())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); + + fixture.service.reconcileDueOperations(NOW); + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + verify(fixture.auditOutbox, never()) + .append(any(), anyString(), any(), anyString(), anyString()); + } + + @Test + void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { + Fixture fixture = fixture(3); + JoinOperation pendingSnapshot = pendingOperation(0, NOW.minusSeconds(1)); + JoinOperation terminalOperation = terminalOperation(); + stubDue(fixture, pendingSnapshot); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)) + .thenReturn(Optional.of(terminalOperation)); + + fixture.service.reconcileDueOperations(NOW); + + InOrder lockOrder = inOrder(fixture.joinOperations); + lockOrder.verify(fixture.joinOperations).lockAccount(ACCOUNT_ID); + lockOrder.verify(fixture.joinOperations).findForUpdate(REQUEST_ID); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verify(fixture.joinOperations, never()) + .recordReconciliationAttempt( + anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); + verifyNoInteractions(fixture.connectScopes, fixture.memberships, fixture.auditOutbox); + } + + private static Fixture fixture(int maxAttempts) { + return fixture(maxAttempts, 5_000); + } + + private static Fixture fixture(int maxAttempts, long backoffMillis) { + AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); + AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); + AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + AccountJoinReconciliationService service = + new AccountJoinReconciliationService( + joinOperations, + connectScopes, + memberships, + auditOutbox, + meterRegistry, + transactionManager, + 10, + maxAttempts, + backoffMillis); + return new Fixture( + service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); + } + + private static void stubDue(Fixture fixture, JoinOperation operation) { + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) + .thenReturn(List.of(operation)); + } + + private static JoinOperation pendingOperation(int attemptCount, Instant nextAttemptAt) { + VerifiedJoinScope scope = verifiedScope(); + return new JoinOperation( + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + CALLER_BINDING, + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + scope.snapshotDigest(), + "AVAILABLE", + true, + 42L, + 1, + AccountJoinDigest.request(scope, CALLER_BINDING, true, 42L), + "PENDING", + null, + null, + null, + null, + 1, + AccountJoinDigest.intent(REQUEST_ID, scope, CALLER_BINDING), + null, + "AVAILABLE", + attemptCount, + attemptCount == 0 ? null : NOW.minusSeconds(1), + attemptCount == 0 ? null : "PREVIOUS_RECONCILIATION_ATTEMPT", + nextAttemptAt); + } + + private static JoinOperation terminalOperation() { + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + return new JoinOperation( + pending.requestId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE", + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt()); + } + + private static VerifiedJoinScope verifiedScope() { + VerifiedJoinScope unsigned = + new VerifiedJoinScope( + CONNECT_SCOPE_ID, + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + EVALUATED_AT.toString(), + EXPIRED_AT.toString(), + "unused"); + return new VerifiedJoinScope( + unsigned.connectScopeId(), + unsigned.accountId(), + unsigned.tenantId(), + unsigned.realmId(), + unsigned.worldSlug(), + unsigned.realmSlug(), + unsigned.playableStateNamespaceId(), + unsigned.playableStateScope(), + unsigned.gameInstanceId(), + unsigned.catalogRevision(), + unsigned.pointerVersion(), + unsigned.evaluatedAt(), + unsigned.connectScopeExpiresAt(), + AccountJoinDigest.scope(unsigned)); + } + + private static ConnectScopeEvidence scopeEvidence( + String targetClass, long tenantId, String worldSlug) { + VerifiedJoinScope scope = verifiedScope(); + return new ConnectScopeEvidence( + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + ACCOUNT_ID, + targetClass, + tenantId, + REALM_ID, + worldSlug, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static JoinMembershipProof activeJoinMembership() { + return new JoinMembershipProof( + MEMBERSHIP_ID, + ACCOUNT_ID, + TENANT_ID, + true, + "ACTIVE", + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + "EXPLICIT_JOIN"); + } + + private static AccountAuditEnvelope joinAuditEnvelope( + String payloadWorldSlug, long payloadTenantId, String digest) { + String payload = + "{\"accountId\":" + + ACCOUNT_ID + + ",\"tenantId\":" + + payloadTenantId + + ",\"worldSlug\":\"" + + payloadWorldSlug + + "\",\"realmSlug\":\"" + + REALM_SLUG + + "\",\"membershipVersion\":" + + MEMBERSHIP_VERSION + + ",\"requestId\":\"" + + REQUEST_ID + + "\"}"; + return new AccountAuditEnvelope( + joinAuditEventId(), + "tenant", + TENANT_ID, + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + NOW.minusSeconds(10), + 1, + 1, + digest, + payload); + } + + private static JoinAuditEvidence verifiedJoinAuditEvidence(AccountAuditEnvelope envelope) { + return new JoinAuditEvidence(envelope, "COMMITTED", 1, "verified-receipt", "verified-log"); + } + + private static UUID joinAuditEventId() { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + REQUEST_ID).getBytes(StandardCharsets.UTF_8)); + } + + private static String correctPayloadDigest() { + return AccountAuditDigest.ofPayload( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, "unused").payload()); + } + + private static String sha256(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } + + private static double reconciliationCounter(Fixture fixture, String result) { + return fixture + .meterRegistry + .get("account.join.reconciliation.operations") + .tag("result", result) + .counter() + .count(); + } + + private static double reconciliationGauge(Fixture fixture, String suffix) { + return fixture.meterRegistry.get("account.join.reconciliation." + suffix).gauge().value(); + } + + private record Fixture( + AccountJoinReconciliationService service, + AccountJoinOperationRepository joinOperations, + AccountConnectScopeRepository connectScopes, + AccountTenantMembershipRepository memberships, + AccountAuditOutboxRepository auditOutbox, + SimpleMeterRegistry meterRegistry) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 0db02b400a..04a234ba9f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -73,6 +73,11 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service", WORKLOAD_NAMESPACE, "game-session-service"); + private static final GrpcPeerIdentity SOCIAL_GROUPS_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/social-groups-service", + WORKLOAD_NAMESPACE, + "social-groups-service"); private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() @@ -483,50 +488,87 @@ void authenticateFailureReturnsErrorDetail() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.authenticate( - AuthenticateRequest.newBuilder().setEmail("demo@example.com").setPassword("bad").build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("bad") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, ref.get().getError().getCode()); Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "bad"); } + @Test + void authenticateReturnsAuthenticatedSessionForExactGameSessionPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); + + assertEquals("9", observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertTrue(observer.completed()); + Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "password"); + } + @Test void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), - new StreamObserver() { - @Override - public void onNext(RequestEmailLoginOtpResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), + new StreamObserver() { + @Override + public void onNext(RequestEmailLoginOtpResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertTrue(ref.get().getAccepted()); @@ -537,11 +579,15 @@ public void onCompleted() {} void requestEmailLoginOtpRejectsBlankEmailBeforeCallingAccountService() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder().setEmail(" ").build(), observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail(" ").build(), observer)); assertNotNull(observer.response()); assertFalse(observer.response().getAccepted()); @@ -558,26 +604,30 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("9", ref.get().getAccountId()); @@ -592,15 +642,19 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer)); assertNotNull(observer.response()); assertEquals( @@ -609,6 +663,63 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { assertFalse(observer.receivedTransportError()); } + @Test + void credentialMethodsRejectAbsentAndWrongGameSessionPeersBeforeServiceCall() { + List rejectedPeers = + java.util.Arrays.asList( + null, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + WORKLOAD_NAMESPACE, + "world-management-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver authenticateObserver = new RecordingObserver<>(); + RecordingObserver requestObserver = new RecordingObserver<>(); + RecordingObserver verifyObserver = new RecordingObserver<>(); + + withPeer( + peer, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + authenticateObserver)); + withPeer( + peer, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), + requestObserver)); + withPeer( + peer, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + verifyObserver)); + + assertEquals("PERMISSION_DENIED", authenticateObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", requestObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verifyObserver.response().getError().getCode()); + assertTrue(authenticateObserver.completed()); + assertTrue(requestObserver.completed()); + assertTrue(verifyObserver.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -712,23 +823,28 @@ void getProfileReturnsProfile() throws Exception { .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertEquals( "demo", @@ -750,23 +866,28 @@ public void onCompleted() {} void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -774,6 +895,81 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @Test + void getProfileRejectsMissingOrWrongPeerBeforeLookup() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + + withPeer( + peer, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void getProfileRejectsInternalOrCrossAccountSubjectBeforeLookup() { + for (boolean internalService : List.of(false, true)) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext( + internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void getProfileRejectsMissingCallerAccountSubjectBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void listPresenceVisibilityPoliciesMapsPersistedPolicies() { PingService pingService = Mockito.mock(PingService.class); @@ -783,17 +979,21 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { Map.of( 2L, ProfilePresenceVisibilityPolicy.PRIVATE, 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .addAccountIds("3") + .addAccountIds("2") + .build(), + observer)); assertNotNull(observer.response()); assertEquals(2, observer.response().getPoliciesCount()); @@ -811,19 +1011,58 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } + @Test + void listPresenceVisibilityPoliciesRejectsMissingOrWrongPeerBeforeLookup() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = + new RecordingObserver<>(); + + withPeer( + peer, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + @Test void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("0") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("0") + .build(), + observer)); assertNotNull(observer.response()); assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); @@ -837,18 +1076,22 @@ void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalArgumentException("Tenant not found")); RecordingObserver notFoundObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - notFoundObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + notFoundObserver)); assertEquals("NOT_FOUND", notFoundObserver.response().getError().getCode()); assertTrue(notFoundObserver.completed()); @@ -859,12 +1102,15 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - internalObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + internalObserver)); assertEquals("INTERNAL", internalObserver.response().getError().getCode()); assertTrue(internalObserver.completed()); @@ -872,295 +1118,440 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors } @Test - void getTenantMembershipForRuntimeReturnsResponse() { + void getTenantMembershipForRuntimeRejectsMissingPeerBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - @Override - public void onCompleted() {} - }); + withPeer( + null, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(ref.get()); - assertEquals("2", ref.get().getAccountId()); - assertTrue(ref.get().getMembershipExists()); - assertTrue(ref.get().getGameplayAdmissionAllowed()); - assertEquals(44L, ref.get().getMembershipVersion()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); } @Test - void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed() { + void getTenantMembershipForRuntimeFailsClosedWithExactPeerBecauseCallerContextIsMissing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(observer.response()); - assertFalse(observer.response().getMembershipExists()); - assertTrue(observer.response().getGameplayAdmissionAllowed()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); } @Test - void getTenantMembershipForRuntimeRejectsZeroTenantIdBeforeLookup() { + void getTenantMembershipForRuntimeRejectsWrongPeerBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("0") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - @Override - public void onCompleted() {} - }); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("0") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { + void getTenantMembershipForRuntimeFailsClosedForCrossAccountOrTenantIds() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.getRealmAccessGrantForRuntime( - GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("0") - .setTenantId("1") - .setWorldSlug("demo") - .setRealmSlug("production") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetRealmAccessGrantForRuntimeResponse value) { - ref.set(value); - } + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + List crossTargetRequests = + List.of( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("3") + .setTenantId("1") + .setRequestId("cross-account") + .build(), + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("9") + .setRequestId("cross-tenant") + .build()); + + for (GetTenantMembershipForRuntimeRequest request : crossTargetRequests) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getTenantMembershipForRuntime(request, observer)); + + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } - @Override - public void onError(Throwable t) {} + @Test + void getRealmAccessGrantForRuntimeRejectsMissingOrWrongPeerBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); - @Override - public void onCompleted() {} - }); + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + peer, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + @Test + void getRealmAccessGrantForRuntimeFailsClosedForCrossAccountOrTenantIds() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + List crossTargetRequests = + List.of( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("3") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("cross-account") + .build(), + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("9") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("cross-tenant") + .build()); + + for (GetRealmAccessGrantForRuntimeRequest request : crossTargetRequests) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getRealmAccessGrantForRuntime(request, observer)); + + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void getTenantEntitlementsForRuntimeReturnsResponse() { + void getTenantEntitlementsForRuntimeFailsClosedWithExactPeerBeforeRead() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( - 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void getTenantEntitlementsForRuntimeRejectsMissingOrWrongPeerBeforeRead() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); - assertNotNull(ref.get()); - assertEquals("1", ref.get().getTenantId()); - assertTrue(ref.get().getGameplayAvailable()); - assertTrue(ref.get().getAllowPublicJoin()); - assertEquals(19L, ref.get().getEntitlementVersion()); + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { + void getTenantEntitlementsForRuntimeFailsClosedForCrossTenantTarget() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-ambiguous")) - .thenThrow( - new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is missing or ambiguous; retry later")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-ambiguous") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("9") + .setRequestId("cross-tenant") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void updateProfileAllowsExactSocialPeerWithMatchingSubject() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - assertNotNull(ref.get()); - assertTrue(ref.get().hasError()); - assertEquals("ENTITLEMENT_UNAVAILABLE", ref.get().getError().getCode()); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertTrue(observer.response().getSuccess()); + assertTrue(observer.completed()); + org.mockito.ArgumentCaptor + captor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); + Mockito.verify(accountService).updateProfile(captor.capture()); + assertEquals(1L, captor.getValue().tenantId()); + assertEquals(2L, captor.getValue().accountId()); + assertEquals("demo", captor.getValue().displayName()); } @Test - void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { + void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + Mockito.doThrow(new IllegalArgumentException("bad")) + .when(accountService) + .updateProfile(Mockito.any()); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("0") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verify(accountService).updateProfile(Mockito.any()); + } - @Override - public void onCompleted() {} - }); + @Test + void updateProfileRejectsMissingOrWrongPeerBeforeUpdate() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + + withPeer( + peer, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void updateProfileErrorReturnsDetail() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.updateProfile(Mockito.any())) - .thenThrow(new IllegalArgumentException("bad")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + void updateProfileRejectsCrossAccountOrInternalSubjectBeforeUpdate() { + for (boolean internalService : List.of(false, true)) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext( + internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); - AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); + } + } - @Override - public void onError(Throwable t) {} + @Test + void updateProfileRejectsMissingCallerAccountSubjectBeforeUpdate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - @Override - public void onCompleted() {} - }); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); } @Test void updateProfileRejectsZeroTenantIdBeforeUpdate() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("0") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1169,11 +1560,9 @@ public void onCompleted() {} } @Test - void exportAccountErrorReturnsDetail() { + void exportAccountFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new IllegalArgumentException("missing")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -1193,11 +1582,12 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("NOT_FOUND", ref.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test - void exportAccountRejectsZeroAccountIdBeforeLookup() { + void exportAccountFailsClosedBeforeValidatingRequestWithoutCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1219,20 +1609,19 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void exportTenantDataRejectsZeroTenantIdBeforeLookup() { + void exportTenantDataFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), + ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId("2").build(), new StreamObserver() { @Override public void onNext(ExportTenantDataResponse value) { @@ -1247,13 +1636,12 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void deleteAccountSuccess() { + void deleteAccountFailsClosedBeforeServiceMutation() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -1276,7 +1664,25 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + assertFalse(ref.get().getSuccess()); + assertEquals("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void deleteAccountRejectsMissingSessionBeforeUnavailableWorkflow() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + SessionContext.clear(); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.deleteAccount(DeleteAccountRequest.newBuilder().setAccountId("2").build(), observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test @@ -1310,7 +1716,7 @@ public void onCompleted() {} } @Test - void linkExternalAccountSuccess() { + void linkExternalAccountFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1338,11 +1744,13 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test - void linkExternalAccountRejectsZeroTenantIdBeforeLink() { + void linkExternalAccountFailsClosedBeforeValidatingRequestWithoutCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1371,13 +1779,12 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { + void requestEmailVerificationFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1386,7 +1793,7 @@ void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { new AtomicReference<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() - .setAccountId("0") + .setAccountId("2") .build(), new StreamObserver() { @Override @@ -1404,8 +1811,79 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void verifyEmailFailsClosedBeforeTokenConsumption() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + + AtomicReference ref = + new AtomicReference<>(); + service.verifyEmail( + net.firedevops.firemud.account.v1.VerifyEmailRequest.newBuilder() + .setToken("verification-token") + .build(), + new StreamObserver() { + @Override + public void onNext(net.firedevops.firemud.account.v1.VerifyEmailResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void requestPasswordResetFailsClosedWithoutAuthorizedInternalCaller() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.requestPasswordReset( + net.firedevops.firemud.account.v1.RequestPasswordResetRequest.newBuilder() + .setEmail("player@example.com") + .build(), + observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void completePasswordResetFailsClosedBeforeTokenConsumption() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.completePasswordReset( + net.firedevops.firemud.account.v1.CompletePasswordResetRequest.newBuilder() + .setToken("reset-token") + .setNewPassword("new-password") + .build(), + observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); Mockito.verifyNoInteractions(accountService); } 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 2b3aa8aa5d..46bbe07e1d 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 @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -785,6 +786,105 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( + boolean retainedPendingIntent) { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + tokenProperties.setConnectScopeExpirationMs(3_600_000L); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest( + connectScopeId, + retainedPendingIntent ? "join-expiring-retained-1" : "join-expiring-new-1"); + + if (retainedPendingIntent) { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult initialAttempt = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(initialAttempt.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", initialAttempt.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + } + + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + VerifiedJoinScope scope = retainedScope.get(); + java.time.Instant scopeExpiry = java.time.Instant.parse(scope.connectScopeExpiresAt()); + java.time.Instant evaluatedAt = java.time.Instant.parse(scope.evaluatedAt()); + assertTrue(scopeExpiry.isAfter(evaluatedAt)); + AtomicReference now = new AtomicReference<>(evaluatedAt); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer( + invocation -> { + now.set(scopeExpiry); + return java.util.List.of(active); + }); + org.mockito.Mockito.clearInvocations( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository, + subscriptionRepository); + + JoinPublicProductionResult result; + try (org.mockito.MockedStatic instantMock = + org.mockito.Mockito.mockStatic( + java.time.Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + instantMock.when(java.time.Instant::now).thenAnswer(invocation -> now.get()); + result = service.joinPublicProduction(bootstrap.bootstrapToken(), request); + } + + assertFalse(result.success()); + assertFalse(result.replayed()); + assertEquals("AUTH_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("NOT_EVALUATED", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordAttemptFailure(request.requestId(), "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCallerBoundAuthorityInvalidation(request.requestId()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + org.mockito.Mockito.verify(accountTenantMembershipRepository) + .findByAccountIdAndTenantId(11L, 7L); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + @Test void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); @@ -1019,7 +1119,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { } @Test - void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1081,9 +1181,17 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans .toString(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + request.requestId(), expiredScope.accountId(), expiredScope.tenantId(), expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), expiredScope.snapshotDigest(), @@ -1101,36 +1209,44 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( request.requestId(), expiredScope, callerBinding), "ENTITLEMENT_UNAVAILABLE", - "UNAVAILABLE")); + "UNAVAILABLE", + 0, + null, + null, + java.time.Instant.now())); JoinPublicProductionResult expiredRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var expiredTerminalOperation = retainedOperation.get(); - JoinPublicProductionResult terminalReadback = + JoinPublicProductionResult repeatedExpiredRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(expiredRetry.success()); - assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); - assertFalse(terminalReadback.success()); - assertFalse(terminalReadback.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); - assertEquals(expiredTerminalOperation, retainedOperation.get()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + assertFalse(expiredRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", expiredRetry.outcomeCode()); + assertFalse(repeatedExpiredRetry.success()); + assertFalse(repeatedExpiredRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", repeatedExpiredRetry.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + .recordAttemptFailure(request.requestId(), "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .finish( - org.mockito.ArgumentMatchers.eq(request.requestId()), - org.mockito.ArgumentMatchers.eq("FAILED"), - org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull()); + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); verifyNoInteractions( subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); } - @Test - void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { + @ParameterizedTest + @CsvSource({"COMMITTED, JOINED, true", "FAILED, PUBLIC_PRODUCTION_ADMISSION_DENIED, false"}) + void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredResult( + String status, String outcome, boolean allowPublicJoin) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1147,42 +1263,10 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { AtomicReference retainedOperation = new AtomicReference<>(); retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-committed-connect-scope"; + String connectScopeId = expiredConnectScopeId(); JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); - VerifiedJoinScope unsignedExpiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - unsignedExpiredScope.connectScopeId(), - unsignedExpiredScope.accountId(), - unsignedExpiredScope.tenantId(), - unsignedExpiredScope.realmId(), - unsignedExpiredScope.worldSlug(), - unsignedExpiredScope.realmSlug(), - unsignedExpiredScope.playableStateNamespaceId(), - unsignedExpiredScope.playableStateScope(), - unsignedExpiredScope.gameInstanceId(), - unsignedExpiredScope.catalogRevision(), - unsignedExpiredScope.pointerVersion(), - unsignedExpiredScope.evaluatedAt(), - unsignedExpiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - unsignedExpiredScope)); + new JoinPublicProductionRequest(connectScopeId, "join-expired-terminal-1"); + VerifiedJoinScope expiredScope = expiredVerifiedJoinScope(connectScopeId); retainedScope.set(expiredScope); String callerBinding = new JwtUtil(JWT_SECRET, 300000L) @@ -1190,31 +1274,16 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { .getPayload() .get("jti") .toString(); - var committedOperation = - new AccountJoinOperationRepository.JoinOperation( - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), + var terminalOperation = + terminalJoinOperation( + request.requestId(), + expiredScope, callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "AVAILABLE", - true, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - expiredScope, callerBinding, true, 1L), - "COMMITTED", - "JOINED", - 701L, - 1L, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - null, - "AVAILABLE"); - retainedOperation.set(committedOperation); + status, + outcome, + allowPublicJoin, + false); + retainedOperation.set(terminalOperation); JoinPublicProductionResult retry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); @@ -1222,12 +1291,32 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { assertFalse(retry.success()); assertFalse(retry.replayed()); assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(701L, retainedOperation.get().membershipId()); + assertEquals(terminalOperation, retainedOperation.get()); + assertEquals(status, retainedOperation.get().status()); + assertEquals(outcome, retainedOperation.get().outcome()); + assertEquals(terminalOperation.membershipId(), retainedOperation.get().membershipId()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + + var mismatchedIntent = + terminalJoinOperation( + request.requestId(), + expiredScope, + callerBinding, + status, + outcome, + allowPublicJoin, + true); + retainedOperation.set(mismatchedIntent); + AuthenticationException intentConflict = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + + assertEquals("IDEMPOTENCY_CONFLICT", intentConflict.getCode()); + assertEquals(mismatchedIntent, retainedOperation.get()); + verifyNoInteractions(subscriptionRepository); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .finish( org.mockito.ArgumentMatchers.anyString(), @@ -1236,7 +1325,152 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { org.mockito.ArgumentMatchers.nullable(Long.class), org.mockito.ArgumentMatchers.nullable(Long.class), org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + } + + @Test + void newJoinRejectsExpiredConnectScopeBeforePersistingIntent() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException expiredScope = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest( + expiredConnectScopeId(), "join-expired-new-1"))); + + assertEquals("CONNECT_SCOPE_INVALID", expiredScope.getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions( + accountConnectScopeRepository, + accountTenantMembershipRepository, + subscriptionRepository, + accountAuditOutboxRepository); + } + + private VerifiedJoinScope expiredVerifiedJoinScope(String connectScopeId) { + VerifiedJoinScope unsignedScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + return new VerifiedJoinScope( + unsignedScope.connectScopeId(), + unsignedScope.accountId(), + unsignedScope.tenantId(), + unsignedScope.realmId(), + unsignedScope.worldSlug(), + unsignedScope.realmSlug(), + unsignedScope.playableStateNamespaceId(), + unsignedScope.playableStateScope(), + unsignedScope.gameInstanceId(), + unsignedScope.catalogRevision(), + unsignedScope.pointerVersion(), + unsignedScope.evaluatedAt(), + unsignedScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(unsignedScope)); + } + + private String expiredConnectScopeId() { + return new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + -1000L, + 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", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", 44L), + Map.entry("catalogRevision", 23L), + Map.entry("pointerVersion", 17L), + Map.entry("evaluatedAt", "1999-12-31T23:59:00Z"), + Map.entry("connectScopeExpiresAt", "2000-01-01T00:00:00Z"), + Map.entry("jti", "expired-connect-scope"))); + } + + private AccountJoinOperationRepository.JoinOperation terminalJoinOperation( + String requestId, + VerifiedJoinScope scope, + String callerBinding, + String status, + String outcome, + boolean allowPublicJoin, + boolean corruptIntentDigest) { + String intentDigest = + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + requestId, scope, callerBinding); + if (corruptIntentDigest) { + intentDigest = "corrupt-" + intentDigest; + } + boolean committed = "COMMITTED".equals(status); + return new AccountJoinOperationRepository.JoinOperation( + requestId, + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + "AVAILABLE", + allowPublicJoin, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + scope, callerBinding, allowPublicJoin, 1L), + status, + outcome, + committed ? 701L : null, + committed ? 1L : null, + committed ? 1L : null, + 1, + intentDigest, + null, + "AVAILABLE", + 0, + null, + null, + java.time.Instant.now()); } @ParameterizedTest @@ -1271,9 +1505,17 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig Long originalMembershipId = "COMMITTED".equals(originalStatus) ? 812L : null; AccountJoinOperationRepository.JoinOperation originalOperation = new AccountJoinOperationRepository.JoinOperation( + requestId, 12L, scope.tenantId(), scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), "different-caller", net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), scope.snapshotDigest(), @@ -1293,7 +1535,11 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( requestId, scope, "different-caller"), null, - "AVAILABLE"); + "PENDING".equals(originalStatus) ? "NOT_EVALUATED" : "AVAILABLE", + 0, + null, + null, + java.time.Instant.now()); retainedOperation.set(originalOperation); AuthenticationException conflict = @@ -1453,9 +1699,17 @@ private void retainJoinEvidence( String intentDigest = invocation.getArgument(3); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + requestId, scope.accountId(), scope.tenantId(), scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( scope.connectScopeId()), @@ -1473,7 +1727,11 @@ private void retainJoinEvidence( 1, intentDigest, null, - "NOT_EVALUATED")); + "NOT_EVALUATED", + 0, + null, + null, + java.time.Instant.now())); return true; }) .when(accountJoinOperationRepository) @@ -1487,9 +1745,17 @@ private void retainJoinEvidence( var pending = retainedOperation.get(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -1506,7 +1772,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), null, - "AVAILABLE")); + "AVAILABLE", + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -1521,9 +1791,17 @@ private void retainJoinEvidence( String availability = invocation.getArgument(1); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -1542,7 +1820,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), invocation.getArgument(2), - availability)); + availability, + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -1555,9 +1837,17 @@ private void retainJoinEvidence( var pending = retainedOperation.get(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -1574,7 +1864,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), null, - pending.lastAttemptAuthorityAvailability())); + pending.lastAttemptAuthorityAvailability(), + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -5393,24 +5687,27 @@ void exportAccountDataIncludesProfilesAcrossTenants() { } @Test - void exportTenantDataRequiresTenantMembershipOrProfile() { - Account account = new Account(); - account.setId(2L); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(profileRepository.findByAccountIdAndTenantId(2L, 7L)).thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 7L)).thenReturn(false); + void exportTenantDataFailsClosedBeforeReadingAccountOrTenantData() { + org.springframework.web.server.ResponseStatusException exception = + assertThrows( + org.springframework.web.server.ResponseStatusException.class, + () -> service.exportTenantData(7L, 2L)); - assertThrows(IllegalArgumentException.class, () -> service.exportTenantData(7L, 2L)); + assertEquals(org.springframework.http.HttpStatus.NOT_IMPLEMENTED, exception.getStatusCode()); + verifyNoInteractions(accountRepository, profileRepository, accountTenantMembershipRepository); } - @Test - void deleteAccountRefusesNonterminalSubscription() { + @ParameterizedTest + @CsvSource({"active, false", "canceled, true"}) + void deleteAccountFailsClosedWithoutMutationForAnySubscriptionState( + String status, boolean terminal) { Account account = new Account(); account.setId(2L); Subscription subscription = new Subscription(); - subscription.setStatus("active"); + subscription.setStatus(status); + if (terminal) { + subscription.setEndedAt(java.time.LocalDateTime.now()); + } subscription.setAccount(account); subscription.setTenantId(7L); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); @@ -5418,32 +5715,129 @@ void deleteAccountRefusesNonterminalSubscription() { AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); - assertEquals("ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", ex.getCode()); + assertEquals("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", ex.getCode()); + verify(accountRepository).findById(2L); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions( + accountJoinOperationRepository, + emailVerificationTokenRepository, + passwordResetTokenRepository, + accountRealmAccessGrantRepository, + externalAccountRepository, + paymentTransactionRepository, + subscriptionRepository, + profileRepository, + accountTenantMembershipRepository); } @Test - void deleteAccountRemovesAccountOwnedRowsAfterTerminalSubscriptions() { + void deleteAccountStillRequiresAnExistingAccountBeforeReturningUnavailable() { + when(accountRepository.findById(404L)).thenReturn(Optional.empty()); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> service.deleteAccount(404L)); + + assertEquals("Account not found", exception.getMessage()); + verify(accountRepository).findById(404L); + verifyNoInteractions( + accountJoinOperationRepository, + emailVerificationTokenRepository, + passwordResetTokenRepository, + accountRealmAccessGrantRepository, + externalAccountRepository, + paymentTransactionRepository, + subscriptionRepository, + profileRepository, + accountTenantMembershipRepository); + } + + @Test + void completePasswordResetConsumesTokenBeforeUpdatingPassword() { Account account = new Account(); - account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("canceled"); - subscription.setEndedAt(java.time.LocalDateTime.now()); - subscription.setAccount(account); - subscription.setTenantId(7L); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + account.setId(1L); + account.setPasswordHash("old-hash"); + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(true); + + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password")); + + assertFalse("old-hash".equals(account.getPasswordHash())); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(passwordResetTokenRepository, accountRepository); + order + .verify(passwordResetTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void completePasswordResetRejectsAlreadyConsumedTokenBeforePasswordMutation() { + Account account = new Account(); + account.setPasswordHash("old-hash"); + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(false); - service.deleteAccount(2L); + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password"))); - org.mockito.Mockito.verify(emailVerificationTokenRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(passwordResetTokenRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(externalAccountRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(paymentTransactionRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(subscriptionRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(profileRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountTenantMembershipRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountRepository).delete(account); + assertEquals("old-hash", account.getPasswordHash()); + org.mockito.Mockito.verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void completePasswordResetRejectsExpiredTokenBeforeConsumption() { + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password"))); + + assertEquals("Token expired", exception.getMessage()); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + org.mockito.Mockito.verifyNoInteractions(accountRepository); } @Test @@ -5670,14 +6064,78 @@ void requestEmailVerificationByEmailContainsDeliveryFailureAfterSavingToken() { void verifyEmailSetsFlag() { Account account = new Account(); EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); token.setAccount(account); + token.setToken("tok"); token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(true); service.verifyEmail(new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok")); assertTrue(account.isEmailVerified()); - org.mockito.Mockito.verify(emailVerificationTokenRepository).delete(token); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order + .verify(emailVerificationTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void verifyEmailRejectsAlreadyConsumedTokenBeforeMarkingAccountVerified() { + Account account = new Account(); + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(false); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertFalse(account.isEmailVerified()); + org.mockito.Mockito.verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void verifyEmailRejectsExpiredTokenBeforeConsumption() { + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertEquals("Token expired", exception.getMessage()); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + org.mockito.Mockito.verifyNoInteractions(accountRepository); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java index 1947118023..06b34067a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java @@ -6,6 +6,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.CreateDonationRequest; import net.firedevops.firemud.account.v1.CreateDonationResponse; @@ -18,6 +20,72 @@ import org.junit.jupiter.api.Test; class PaymentGrpcServiceTest { + @Test + void genericPaymentsRemainClosedForRepeatedRequests() { + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + PaymentGrpcService service = new PaymentGrpcService(meterRegistry); + CreatePaymentIntentRequest intent = + CreatePaymentIntentRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setAmountCents(500) + .build(); + CreateDonationRequest donation = + CreateDonationRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setAmountCents(100) + .build(); + RefundPaymentRequest refund = + RefundPaymentRequest.newBuilder().setTenantId("1").setPaymentId("9").build(); + List intents = new ArrayList<>(); + List donations = new ArrayList<>(); + List refunds = new ArrayList<>(); + + for (int attempt = 0; attempt < 2; attempt++) { + service.createPaymentIntent(intent, collecting(intents)); + service.createDonation(donation, collecting(donations)); + service.refundPayment(refund, collecting(refunds)); + } + + assertEquals(2, intents.size()); + assertEquals(2, donations.size()); + assertEquals(2, refunds.size()); + for (CreatePaymentIntentResponse response : intents) { + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("", response.getIntentId()); + assertEquals("", response.getClientSecret()); + } + for (CreateDonationResponse response : donations) { + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("", response.getIntentId()); + assertEquals("", response.getClientSecret()); + } + for (RefundPaymentResponse response : refunds) { + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertFalse(response.getSuccess()); + } + assertEquals( + 6.0, meterRegistry.counter("grpc.app_error", "code", "FAILED_PRECONDITION").count()); + } + + private static StreamObserver collecting(List responses) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("Expected an application-level fail-closed response", error); + } + + @Override + public void onCompleted() {} + }; + } + @Test void createPaymentIntentRejectsValidRequestBeforeDispatchAndRecordsErrorMetric() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 93c652916c..2c73d0ff03 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -5,7 +5,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.concurrent.atomic.AtomicReference; +import java.util.ArrayList; +import java.util.List; import net.firedevops.firemud.account.v1.AddCurrencyRequest; import net.firedevops.firemud.account.v1.AddCurrencyResponse; import net.firedevops.firemud.account.v1.GetBalanceRequest; @@ -18,162 +19,103 @@ class VirtualCurrencyGrpcServiceTest { @Test - void getBalanceReturnsResponse() { + void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")).thenReturn(123L); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.getBalance( + StreamObserver observer = collecting(responses); + GetBalanceRequest request = GetBalanceRequest.newBuilder() .setTenantId("1") .setAccountId("2") .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } + .build(); + service.getBalance(request, observer); + service.getBalance(request, observer); - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertEquals(123L, ref.get().getBalance()); - } - - @Test - void getBalanceRuntimeFailureReturnsInternalErrorDetail() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")) - .thenThrow(new IllegalStateException("boom")); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); - } - - @Test - void getBalanceRejectsZeroTenantIdBeforeLookup() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "GetBalance is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void addCurrencyRejectsZeroAccountIdBeforeMutation() { + void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.addCurrency( + StreamObserver observer = collecting(responses); + AddCurrencyRequest request = AddCurrencyRequest.newBuilder() .setTenantId("1") - .setAccountId("0") + .setAccountId("2") .setCurrencyCode("GOLD") .setAmount(10) - .build(), - new StreamObserver<>() { - @Override - public void onNext(AddCurrencyResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + .build(); + service.addCurrency(request, observer); + service.addCurrency(request, observer); - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "AddCurrency is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void spendCurrencyRejectsZeroTenantIdBeforeSpend() { + void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.spendCurrency( + StreamObserver observer = collecting(responses); + SpendCurrencyRequest request = SpendCurrencyRequest.newBuilder() - .setTenantId("0") + .setTenantId("1") .setAccountId("2") .setCurrencyCode("GOLD") .setAmount(5) - .build(), - new StreamObserver<>() { - @Override - public void onNext(SpendCurrencyResponse value) { - ref.set(value); - } + .build(); + service.spendCurrency(request, observer); + service.spendCurrency(request, observer); - @Override - public void onError(Throwable t) {} + assertUnavailable(responses, "SpendCurrency is unavailable"); + Mockito.verifyNoInteractions(currencyService); + } - @Override - public void onCompleted() {} - }); + private static StreamObserver collecting(List responses) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("Expected an application-level fail-closed response", error); + } + + @Override + public void onCompleted() {} + }; + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(currencyService); + private static void assertUnavailable(List responses, String message) { + assertEquals(2, responses.size()); + for (Object response : responses) { + assertNotNull(response); + if (response instanceof GetBalanceResponse getBalanceResponse) { + assertEquals("FAILED_PRECONDITION", getBalanceResponse.getError().getCode()); + assertEquals(message, getBalanceResponse.getError().getMessage()); + } else if (response instanceof AddCurrencyResponse addCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", addCurrencyResponse.getError().getCode()); + assertEquals(message, addCurrencyResponse.getError().getMessage()); + } else if (response instanceof SpendCurrencyResponse spendCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", spendCurrencyResponse.getError().getCode()); + assertEquals(message, spendCurrencyResponse.getError().getMessage()); + } else { + throw new AssertionError("Unexpected response type: " + response.getClass()); + } + } } } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java index c37359c20b..df3e1c58f1 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java @@ -53,6 +53,7 @@ void createResponseKeepsLegacyIdentityAndErrorNumbers() { assertField(descriptor, "payload_digest", 9, FieldDescriptor.Type.STRING); assertField(descriptor, "status", 10, FieldDescriptor.Type.ENUM); assertField(descriptor, "outcome", 11, FieldDescriptor.Type.ENUM); + assertField(descriptor, "audit_projection_version", 12, FieldDescriptor.Type.INT32); assertThat(descriptor.findFieldByName("scope").getEnumType()) .isEqualTo(AccountAuditScope.getDescriptor()); assertThat(descriptor.findFieldByName("status").getEnumType()) @@ -76,6 +77,7 @@ void receiptReadResponseAddsErrorDetailAtTheNextFreeNumber() { assertField(descriptor, "status", 9, FieldDescriptor.Type.ENUM); assertField(descriptor, "outcome", 10, FieldDescriptor.Type.ENUM); assertErrorField(descriptor, "error", 11); + assertField(descriptor, "audit_projection_version", 12, FieldDescriptor.Type.INT32); } private static void assertField( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java index cc92e60dae..1eb72e99dd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java @@ -70,11 +70,19 @@ public GatewayProperties canonicalGatewayProperties(Environment environment) { 2, "GET"), route( - "design", + "design-ping", environment.getProperty( "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), - "/api/design/**", - 2), + "/api/design/ping", + 2, + "GET"), + route( + "design-templates-read", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), + "/api/design/templates", + 2, + "GET"), route( "account-auth", environment.getProperty( diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index d980fa953c..79c4d7cb19 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -9,9 +9,13 @@ import org.springframework.cloud.gateway.filter.FilterDefinition; import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.http.server.PathContainer; +import org.springframework.web.util.pattern.PathPatternParser; final class GatewayRouteTestSupport { + private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); + private GatewayRouteTestSupport() {} static RouteDefinition route(GatewayProperties gatewayProperties, String routeId) { @@ -63,16 +67,53 @@ static void assertNoConfiguredPath(GatewayProperties gatewayProperties, String p .collect(Collectors.toSet()); assertThat(configuredPaths).doesNotContain(path); + if (isConcretePath(path)) { + assertThat(configuredPaths) + .noneMatch(configuredPath -> pathPatternMatches(configuredPath, path)); + } + } + + static void assertNoRouteWithPathAndMethod( + GatewayProperties gatewayProperties, String path, String method) { + assertThat( + gatewayProperties.getRoutes().stream() + .noneMatch( + route -> + route.getPredicates().stream() + .filter(predicate -> "Path".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch( + configuredPath -> pathPatternMatches(configuredPath, path)) + && (route.getPredicates().stream() + .noneMatch( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + || route.getPredicates().stream() + .filter( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch(method::equals)))) + .as("route %s %s must not be configured", method, path) + .isTrue(); } static void assertSocialChatAndFriendsAreEdgeGated(GatewayProperties gatewayProperties) { assertThat(gatewayProperties.getRoutes().stream().map(RouteDefinition::getId)) .doesNotContain("social-chat", "social-friends"); assertNoConfiguredPath(gatewayProperties, "/api/social/**"); + assertNoConfiguredPath(gatewayProperties, "/api/social/chat/messages"); + assertNoConfiguredPath(gatewayProperties, "/api/social/friends"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/chat"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/friends"); } + private static boolean isConcretePath(String path) { + return path.indexOf('*') < 0 && path.indexOf('{') < 0 && path.indexOf('}') < 0; + } + + private static boolean pathPatternMatches(String configuredPath, String probePath) { + return PATH_PATTERN_PARSER.parse(configuredPath).matches(PathContainer.parsePath(probePath)); + } + static void assertHasStripPrefixTwo(GatewayProperties gatewayProperties, String routeId) { assertHasStripPrefix(gatewayProperties, routeId, "2"); } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java new file mode 100644 index 0000000000..0e093e9b69 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; +import org.springframework.cloud.gateway.route.RouteDefinition; + +class GatewayRouteTestSupportTest { + + @Test + void assertNoConfiguredPathRejectsWildcardAndPathVariableMatches() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/{resource}"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoConfiguredPathPreservesExactWildcardPatternAssertion() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/social/**"), null)), "/api/social/**")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodRejectsMatchingWildcardAndPathVariableRoutes() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/{resource}"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodTreatsMissingMethodAsMatchingAndOtherMethodAsNonmatching() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "GET")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/other/**"), "POST")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + } + + @Test + void assertNoRouteWithPathAndMethodChecksEveryConfiguredPathPattern() { + RouteDefinition route = route(List.of("/api/unrelated/**", "/api/design/{resource}"), "POST"); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route), "/api/design/assets", "POST")) + .isInstanceOf(AssertionError.class); + } + + private static GatewayProperties gatewayProperties(RouteDefinition... routes) { + GatewayProperties properties = new GatewayProperties(); + properties.setRoutes(List.of(routes)); + return properties; + } + + private static RouteDefinition route(List paths, String method) { + RouteDefinition route = new RouteDefinition(); + List predicates = new java.util.ArrayList<>(); + PredicateDefinition pathPredicate = new PredicateDefinition(); + pathPredicate.setName("Path"); + LinkedHashMap pathPatterns = new LinkedHashMap<>(); + for (int index = 0; index < paths.size(); index++) { + pathPatterns.put("_genkey_" + index, paths.get(index)); + } + pathPredicate.setArgs(pathPatterns); + predicates.add(pathPredicate); + if (method != null) { + predicates.add(new PredicateDefinition("Method=" + method)); + } + route.setPredicates(predicates); + return route; + } +} diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java index 38e63fb9a4..989f145e1b 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -47,7 +49,8 @@ class GatewayRoutesConfigurationProdTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -120,13 +123,21 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasPath(gatewayProperties, "admin-remote-followups", "/api/admin/remote-followups/**"); assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); assertHasStripPrefixTwo(gatewayProperties, "admin-ping"); assertHasStripPrefixTwo(gatewayProperties, "admin-admission-pointers"); assertHasStripPrefixTwo(gatewayProperties, "admin-remote-followups"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); assertHasStripPrefixTwo(gatewayProperties, "account-auth"); } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java index a15d8e7c9b..519c031387 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -130,8 +133,16 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasStripPrefixTwo(gatewayProperties, "admin-sagas"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java index 84656b3137..e6dec07fda 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefix; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTestProfileTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -111,7 +114,14 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "session-ping", "/api/session/ping"); @@ -133,7 +143,8 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasStripPrefix(gatewayProperties, "admin-remote-followups", "2"); assertHasStripPrefix(gatewayProperties, "admin-sagas", "2"); assertHasStripPrefix(gatewayProperties, "admin-tick-remediation", "2"); - assertHasStripPrefix(gatewayProperties, "design", "2"); + assertHasStripPrefix(gatewayProperties, "design-ping", "2"); + assertHasStripPrefix(gatewayProperties, "design-templates-read", "2"); assertHasStripPrefix(gatewayProperties, "account-auth", "2"); assertHasStripPrefix(gatewayProperties, "account-accounts", "2"); assertHasStripPrefix(gatewayProperties, "account-profiles", "2");