diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3429d36b1c..0ad6a48a97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -509,6 +509,8 @@ jobs: time bash ./dev-tools/tests/kubectl-version-skew-contract.sh TIMEFORMAT='bash ./dev-tools/tests/helm-transaction-proof-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/helm-transaction-proof-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/account-workload-namespace-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/account-workload-namespace-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-image-tag-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/preview-image-tag-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-merge-image-tag-contract.sh: real=%3R user=%3U sys=%3S' @@ -525,6 +527,8 @@ jobs: time bash ./dev-tools/tests/ensure-local-compose-env-contract.sh TIMEFORMAT='bash ./dev-tools/tests/local-compose-mtls-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/local-compose-mtls-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/dev-certs-retention-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/dev-certs-retention-contract.sh TIMEFORMAT='bash ./dev-tools/tests/smoke-image-env-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/smoke-image-env-contract.sh TIMEFORMAT='bash ./dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh: real=%3R user=%3U sys=%3S' diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 01ff15032f..911aea7dac 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,7 +90,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `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, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. 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. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain 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` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which 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 and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and 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. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. 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. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried 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. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -104,7 +104,7 @@ The final ordinary receiving composition carries UUID ordinary JWT subjects/Acco ### 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 returns a synchronous Account/profile-local result. It has no cross-service required-owner fan-in and does not satisfy ADR 0050. The legacy `ExportAccount` gRPC adapter is unavailable before selector parsing or owner reads because no authorized internal caller is configured; this containment does not change the separately authorized REST/service 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. @@ -137,16 +137,16 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `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. The response projection returns `PRIVATE` for a retained legacy `HIDDEN_STAFF` value without rewriting the stored row; normative policy remains in [ADR 0046](../../decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies 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. +- `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 gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. - `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. +- `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 legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - 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. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of completing a security-relevant write; its password update and reset-token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). -- 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. +- 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. The legacy `LinkExternalAccount` gRPC adapter returns `FAILED_PRECONDITION` before parsing, lookup or mutation. 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. @@ -164,8 +164,8 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `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. - `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. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of committing the verification write; the email-verification change and token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). +- `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 unused Account-ID gRPC initiation adapter returns `FAILED_PRECONDITION` before lookup or mail dispatch until an explicit receiving caller policy is supplied; its retained request shape grants no workload or caller-subject permission. Unknown public requests create no token and schedule no delivery. +- `VerifyEmail` – confirm a single-use email verification token while it is strictly unexpired. Token consumption and the verified-email change commit together under the Account owner transaction; a rejected claim cannot mutate the Account. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of committing the verification write; the email-verification change and token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). - `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. @@ -256,6 +256,14 @@ The prepared original activation-protection methods authenticate the exact same- `AccountStartSessionAdmissionProtectionService.AcquireStartSessionAdmissionProtection` is an internal schema-1 Game Session-to-Account method defined by the [acquisition proto](../../../../protos/account/v1/start_session_admission_protection_acquisition.proto). It transports the complete canonical Account protection request, bounded to 768 KiB, and returns complete owner-produced protection evidence, bounded to 8 MiB; the receiver's wire bound includes the codec's finite 8-byte protobuf envelope allowance. The manually constructed receiver requires the exact same-namespace Game Session mTLS identity and rejects authenticated end-user context before decoding or owner work. The request is binding/comparison input, not caller authority or terminal evidence. Account's acquisition owner independently checks the original attempt and current source, retains or replays the immutable protection, and verifies its exact current readback without extending the original lease. The method remains unregistered and is not a public API. Account's terminal settlement is a separate owner operation; its authenticated Game Session read contract is defined in [Game Session API Contracts](../game-session-service/api-contracts.md#account-purpose-initial-admission-settlement-read). +### Legacy credential RPC and local demo fixture + +The registered legacy `Authenticate`, `RequestEmailLoginOtp` and `VerifyEmailLoginOtp` handlers require certificate-derived exact same-namespace Game Session identity before invoking credential owners. The OTP methods have no Entity caller exception. Workload peer authorization does not replace normal credential verification, persisted Account UUID provenance or source-owner checks. + +`Authenticate` alone has a separate local demo fixture branch for the exact same-namespace Entity Management certificate identity. Account must explicitly enable `firemud.account.local-demo-authentication.enabled`, configure the demo email identity, and run with the `local-fixture` profile without `prod`. The flag defaults to false and the configured identity defaults empty; an enabled local fixture with no valid configured identity fails startup. The request must match that configured identity before ordinary Account password verification runs. A caller-side seed flag, bearer or claimed peer header cannot enable the receiving branch, and enabling it never permits Entity OTP requests or general Entity credential access. This is the bounded local/run-fixture used by [Entity demo seeding](../entity-management-service/runtime-and-data.md#implementation-status); it does not activate the separate canonical private LOGIN receiver, production registration or gameplay admission. + +The disabled `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, `RequestEmailVerification`, `GetBalance`, `AddCurrency`, and `SpendCurrency` adapters fail before domain execution with non-OK gRPC `FAILED_PRECONDITION` and one bounded `ErrorDetail` in status trailers. They emit no response body or successful completion. This follows the shared [outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification); the retained response schemas do not make these operations available. + ## REST APIs Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. @@ -269,7 +277,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `POST` | `/auth/request-password-reset` | Request account-scoped password reset by normalized email with a neutral known/unknown response | | `POST` | `/auth/complete-password-reset` | Complete account-scoped password reset | | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | -| `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | +| `POST` | `/auth/verify-email` | **Current public route.** Verify an account-scoped email token without a bearer JWT. The configured verification email still links to `GET /auth/verify-email`, which has no controller mapping; browser handoff to the public POST remains unavailable. See the separate link-routing gap in [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/login-auth-modes` | Read primary login modes for the selected global Account; the current account selector is a canonical lowercase non-nil Account UUID. | @@ -311,7 +319,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco The listed Account UUID representation is implemented through the qualified ordinary receiving boundary, including Account-issued credentials, shared forwarding, caller-bound REST/profile use, and UUID-valued downstream Account references. Private numeric Account rows and the separate legacy numeric GameInstance owner/StartSession boundary remain distinct. Full token-profile/registry qualification, production custody and gameplay admission/activation remain held; proof status is in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). +Current verification routing/auth status: base and production HTTP configurations allowlist public `POST /auth/verify-email`, which has no bearer requirement. The configured verification email remains a `GET /auth/verify-email` link with no controller mapping, and browser handoff to the public POST is not implemented; see the separate [verification-link routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` handlers follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity), including PUT path/body equality. They enforce exact UUID `SessionContext` self-binding before private owner resolution, retaining current tenant-membership checks (`gameplayAdmissionAllowed` is not required), public policy vocabulary checks, and post-commit update notification. Legacy PUT rejects `HIDDEN_STAFF` before persistence; a successful update stores the supplied selectable policy. Normalizing retained legacy policy to `PRIVATE` applies to read/export projection without rewriting that row, not acceptance of the retired policy on update. These selectors do not authorize another Account's profile or activate the canonical tenant-qualified route, scoped tenant roles, or membership-authority-generation checks. The legacy route and its route/policy shape remain implementation drift. @@ -349,7 +357,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | +| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | | Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` validates bootstrap identity and scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, or cached-result reads and token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index ac85376d71..ce8775571a 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -22,6 +22,14 @@ In player-facing environments, the interim `jwt-signing-keys` private bundle is The configurable cleanup margin controls issued-token registry retention only. Gameplay continuity is a separate Game Session policy documented in [Reconnection](../../system-architecture-reconnection.md); Account configuration does not derive or widen that lifetime. +### Kubernetes Workload Namespace + +The Account Helm Deployment supplies `FIREMUD_GRPC_WORKLOAD_NAMESPACE` from the pod's `metadata.namespace` through the Kubernetes downward API. The chart reserves this variable and rejects an `extraEnv` entry with the same name; other `extraEnv` entries remain available. Account uses this configured namespace for the workload-peer checks described in the [Account API contract](./api-contracts.md). + +### Local Demo Authentication Fixture + +The Account receiving flag `FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED` defaults to `false`, and `FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL` defaults empty. Local/run-owned Compose explicitly enables the flag, configures its demo email and selects `local-fixture` for Account. Active `prod` excludes this fixture even when the flag is set. These settings supply only the Account-local delivery described by the [credential fixture contract](./api-contracts.md#legacy-credential-rpc-and-local-demo-fixture); the Entity seeding flag supplies no receiving authority. + ## Implementation Status The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index cd41e4b505..0586f05eaa 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -348,9 +348,11 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b ### Email and Notification Design -This service sends verification and password reset emails using a configured SMTP provider. 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 a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). +This service sends verification and password reset emails using a configured SMTP provider. 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 a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector. The internal Account-ID gRPC initiation method currently returns `FAILED_PRECONDITION` before account lookup or mail dispatch because no authorized internal caller is configured; its retained request shape does not grant caller permission. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). -The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. +Email verification uses the token association only to locate the Account, then locks the current complete Account row before claiming the exact original token. The conditional SQL consumption matches token row ID, opaque token, Account owner and original expiry, requiring expiry strictly after the captured process-local time. The claim and Account/source update share the writable owner transaction; losing, changed or expired claims cannot mutate Account state, and a failed source update rolls the claim back. Current password, role, email, login modes and UUID provenance come from that locked owner rather than the earlier partial token join. This preserves the existing local timestamp basis described above; it adds no cross-node timezone or retained-row migration claim. Focused implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment). + +The configured default verification URL is a `GET /auth/verify-email` link, but Account exposes only `POST /auth/verify-email`; the GET has no controller mapping. Although the base and production HTTP configurations allow the POST as public, the configured mail link still requires an explicit browser handoff or matching GET handler to reach it. The default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). Deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live; see the canonical route/auth contract in [Account API Contracts](./api-contracts.md#rest-apis). ## Original StartSession Source-Protection Storage diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index f64797775a..09ea58ca5c 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -5,7 +5,9 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status - Ordinary Account ownership uses the existing `characters.account_uuid` carrier; V1024 permits fresh ordinary rows without fabricated numeric source evidence and adds an ordinary UUID roster index. It leaves retained numeric/unresolved rows unchanged and does not promote canonical actor provenance. Representation and admission consequences belong to [API Contracts](./api-contracts.md#ordinary-account-ownership); implementation/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). -- Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. +- Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. Account separately enables its narrowly gated [local credential fixture](../account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture); Entity seed enablement alone grants no receiving authority, OTP access or general credential permission. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. + +The explicitly enabled local demo owner-authentication client makes at most three Account calls, each with the existing five-second deadline and a 250 ms delay between attempts. Only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` may retry; domain credential failures, authorization refusal and invalid returned ownership still fail before Entity seeding. Interruption and exhausted retries abort startup without substituting an identity. This is bounded fixture startup resilience, not production authentication or permission to rewrite retained owners. - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World owns guarded, manually composed initial `character_location` storage and its unregistered placement/read boundary. General movement, occupancy and NPC location remain unqualified; `room_instance` is topology, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c77266ec98..82164229d2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -10,3 +10,9 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Java filesystem read-only checks can miss same-device bind mounts. - A proposed `Files.getFileStore(path).isReadOnly()` guard was rejected before implementation: OpenJDK 21 discovers Linux boundaries using device changes and can attribute a bind mount to an ancestor with different read-only state. Exact current-process mountinfo, visible ancestry and pre/post comparison now preserve the readers’ owner/AtomicWriter guards; twelve physical mount cases pass. Next: qualify actual kubelet projection provenance at the existing held deployment boundary; local read-only evidence does not establish it. See [Game Session projection compatibility](../architecture/microservices/game-session-service/operations.md#protected-readiness-projection-compatibility). + +- `2026-11-01` (Pacific/Auckland): A transient demo-owner authentication deadline terminated Entity startup. + - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh canonical image-lane held smoke at `6c63d74546` also passes, with independent empty-project cleanup. Remote replacement CI remains required. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. + +- `2026-11-01` (Pacific/Auckland): Local executable mode loss and a later successful check masked certificate-contract failure. + - During #3367 CLI4 qualification, `generate-dev-certs.sh` was tracked as `100755` but locally `0644` with `core.filemode=false`; `ensure-dev-certs.sh` therefore failed to execute it. The multi-command caller lacked failure propagation and returned the later documentation check’s success. Root inspected the failed contract log, restored only the generator’s tracked executable permission, and reran the contract and ShellCheck with explicit fail-fast propagation; both pass. The original failure remains retained in R1425 and was reported to Overseer. The mode-change cause is unproven; on recurrence, capture the affected file’s mode before and after the scoped mutation rather than changing unrelated worktrees. 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 0ec60507d4..380998ed89 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -374,6 +374,12 @@ Focused controlled proof includes 427 selected catalog, menu, SQL-ordering and h The companion retains original LOGIN-linked scope and JOIN attempts. Focused scope/lobby proof covers Account evaluation/expiry bytes independently of the injected Game Session clock, and menu proof covers separate transport correlations, original-expiry retention and refusal to recreate lost or changed preimages. The storage and recovery contracts remain at the linked architecture owners. Uncertain JOIN originals and the existing SQL retention hold are preserved; expiry or selection replacement does not release them. Bounded REALMS scope intake and capacity qualification, complete negative/unknown-result recovery, lawful release, and a retention/archival horizon remain open. Production source registration, protected receiving custody, issuer/PKI custody, deployed Redis ACL/connection binding, activation, and first `OPEN` remain held at their owning gates, including ADR 0185 and Unit 1B constraints. No successful public admission or readiness/merge state is claimed. +The separately received caller-bound Account scope, frozen JOIN original and current-selection proof remains in the [detailed #3366/R1414 qualification](#3366-direct-text-proof). + +#### #3366 direct-text proof + +The #3366 direct-text preparation adds the separately owned [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion), retaining the exact caller-bound Account scope and a durable frozen JOIN original before dispatch. Its current-selection pointer cannot replace earlier unknown attempts, and the existing original LOGIN journal/codec and retention hold remain. R1414 passes 29 focused unit cases and 16 real-PostgreSQL cases with zero failures, errors or skips. Physical proof migrates a populated pre-companion LOGIN journal, preserves its complete original row, exercises both abandonment/claim lock orders and concurrent dispatch claims, retains uncertain outcomes across owner replacement, rejects direct identity/transition/retention violations, and bounds positive membership identifiers to Account’s canonical positive BIGINT domain. Selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Game Session packaging pass for that controlled source. The manually composed owner can issue scope and dispatch the frozen original through the existing Account client under a required protected-custody port, but no genuine producer for that port or text-command registration is supplied. Fresh source-built held-admission smoke on `85d4568536` passes the actual backend WORLDS → LOGIN → PLAY → LOOK → LOGOUT flow and Gateway/Telnet denial checks. Canonical cleanup completes, and independent exact-project checks find no containers, networks or volumes. This proves startup and the isolated held flow, not successful public admission or a production custody producer. This does not wire live REALMS/JOIN text dispatch, prove genuine receiving custody, register a production owner, settle negative/unknown results, release retained rows or establish admission. + ### Account operation and signer source preparation [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql) adds one immutable cleanup deadline to newly prepared Control-UI owner rows, separate from the JWT `exp` horizon and bound to the same registry bytes and Redis readback receipt. The retained-row migration case in [AccountControlUiIssuancePostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java) confirms that a pre-deadline row keeps its original fields, retains a null deadline, and is denied current use and advancement after migration. Direct PostgreSQL proof that a newly recorded deadline cannot be changed is still missing. The preparation remains source-only under AA-1.3; bounded cleanup and late revocation remain incomplete, and token issuance is not activated. @@ -468,7 +474,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; tenant IDs remain numeric and full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [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.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); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.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); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | @@ -628,6 +634,22 @@ Gateway owns the downstream `/ws/game/**` socket and a stable edge transport ses Shared coordination state carries reconnect/connect-context tracking, disconnect deduplication, gameplay-identity screen-buffer access, and bounded takeover information, while the in-process socket remains local. These stores do not produce authenticated first-party ingress. Shipped close-metadata proof covers missing or unattributed metadata on a public WebSocket emitting close `1011`/`internal_error`, and missing or invalid top-level metadata on an established authenticated TCP Proxy bridge rendering `DISCONNECT backend_unavailable ...`; it does not establish a successful first-party handshake, command/byte replay, the broader handler taxonomy, or the complete continuity contract. Remaining gaps are tracked in [TCP Proxy Operations](../../architecture/microservices/tcp-proxy-service/operations.md#implementation-status); duplicate and missing disconnect hints remain separately metered. +### Account email verification and deferred currency containment + +Local receiving work for #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. The later R1418 held-smoke result below supplies fresh local runtime qualification. The remaining #2848 JOIN reconciliation, receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. + +R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC before selector parsing or owner reads; five focused gRPC/REST cases pass, with the separate REST/service authorization retained. The local Helm namespace render and development-certificate retention contracts pass, together with scoped ShellCheck and documentation checks. New credential receivers use exact Game Session certificate identity for OTP and the separately gated [Account-local Entity demo fixture](../../architecture/microservices/account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture) for Authenticate only. The first credential aggregate fails a missing test assertion import before test execution. Its corrected source passes 162 fresh Account cases, including eleven physical loopback-mTLS cases with a mocked credential owner; six unchanged Entity demo cases are up to date, not fresh executions. Subsequent main/test analysis recoveries pass after removing an unnecessary constructor suppression and retaining the channel shutdown return value; the eleven physical cases pass again without failures, errors or skips. These are separate scoped results across retained failed aggregates, not one complete Account suite or genuine credential verification. The later R1418 held-smoke result below supplies the current local runtime result. + +The same local containment suspends the unused `ExportAccount`, caller-asserted `LinkExternalAccount` and Account-ID `RequestEmailVerification` gRPC adapters before request parsing or owner access. Target export/link capabilities and an authorized internal verification-initiation caller remain incomplete. Separately authorized REST/service exports, neutral email-based initiation and the stronger token-based reset/verification owners remain. The combined current gate passes all 172 selected cases (163 Account unit/loopback cases, including eleven physical mTLS and six actual-profile HTTP wiring cases, plus nine actual PostgreSQL/Spring cases) with zero failures, errors or skips, selected main/test/integration static analysis, full formatting, fresh packaging and documentation checks. The three public-v1 JOIN cases prove actual commit followed by lost acknowledgement/readback, rollback followed by same-original continuation, and unchanged retained committed evidence after scope expiry. Controlled routing/caller inputs and injected failures establish no deployed RPC recovery or production authority. Public POST verification is selected by actual base/prod YAML; GET supplies no verification route or bypass. The email-link/browser handoff remains outside this local API proof. + +R1425 corrects the seven disabled Account/currency adapters to non-OK `FAILED_PRECONDITION` with bounded structured status details, retaining error metrics and no owner access. The Account RPC unit cases and a repeated-call loopback transport fixture cover this boundary; OpenAPI now declares the existing bearerless verification POST, with its base/prod HTTP wiring proof retained. All 154 selected cases pass with zero failures, errors or skips: 143 Account RPC, four currency adapter, one repeated-call real loopback gRPC, and six base/prod HTTP composition cases. The loopback fixture checks all seven adapters twice, precise status/details, zero injected owner calls and bounded error-counter labels/counts, with checked transport cleanup. After correcting the fixture compilation and replacing retained mutable-Throwable capture with immutable status capture, the fresh consolidated gate passes all 154 cases, enabled Account main/test Checkstyle and SpotBugs, full formatting, boot-jar packaging and documentation checks. Fresh jars and all eleven images at `13953d4c18f452dc84f748d3f625e1eeb9220ca0` pass the canonical held-admission smoke. Authenticated teardown and independent exact-project checks find no remaining containers, networks or volumes. A later diagnostic-only certificate recovery message changes no application/image behavior. These fixtures do not establish workload TLS, supported export/link/currency operations or browser email-link handoff. + +R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76ee2056b9503` into local receiving source `863797ec59361deee0225a40804dcdaf08fd0d86` and freshly rebuilds jars and images for the canonical held-admission smoke. The direct backend LOGIN → PLAY → LOOK proof and Gateway/Telnet denial qualification pass; authenticated teardown succeeds, and independent exact-project checks find no containers, networks or volumes. This qualifies the bounded local Entity credential fixture and current contained startup, not successful public Gateway/Telnet admission, production credential authority, audit delivery, unknown-outcome observation or lawful release. The 172-case aggregate above retains its earlier code-source attribution; the inherited direct-text carry does not change those Account implementation or test bytes. + +The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. + +Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. + ### Fail-Closed Boundary Convergence The auth/session/routing guardrail family is complete at its current bounded seams and is now a standing regression boundary, not a claim that every future ingress path has been audited. Shared helpers and direct adopters cover: @@ -706,6 +728,10 @@ Restricted original-claim evidence continuation remains inactive and preparation At local source `0a685173e0982ba3c0006acb3e378d228daeadbb`, normally reconciled to published parent `7b2ce6340309198ed4fabd0e58629102ba717706`, the focused gate passed in 2m36s: 150 fresh unit cases and 35 physical Redis-context/PostgreSQL-journal cases, all with zero failures, errors or skips, plus Game Session Checkstyle, SpotBugs, formatting and documentation checks. The subsequent two composed-owner test additions on that local baseline passed all 28 physical Redis-context/PostgreSQL cases in the 57-second affected gate, with zero failures, errors or skips and affected static/format checks. The initial test-package compilation failures remain failed history; production constructor visibility was preserved. The unregistered [InitialGameplayLoginOwner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) reserves and independently reads back distinct server UUIDv4 request/context coordinates at fence 1 before create-only `PENDING`, then calls the [canonical Account client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java) with its bounded same-deadline retry guarded by current original credential custody. It records and reads back the verified nonsecret witness before exact-result installation and transfers the still-live private result to its caller; uncertain results and actual original pre-admission custody loss retain exact-original cleanup. This original-attempt lifecycle remains separate from already-admitted retained-edge rebind. The [owner proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java), [Redis integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java), and [journal integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java) exercise controlled composition and physical storage fixtures only. The composed physical cases check independently committed original coordinates before the first Redis mutation, actual PENDING creation and non-admitting installation, and same-invocation credential closure after a controlled Account response followed by exact-original Redis closure, frozen witness-bearing retirement, a PENDING disposal receipt and owned-result erasure. Account signing/disposal responses and external Redis qualification remain controlled inputs. The later 28-case evidence belongs to the local changed test postimage, not an authenticated production receiving chain. Caller registration, trusted Gateway/Proxy identity and protected custody, production Redis qualification, real Account mTLS/signing, qualified retained binding-history recovery, runtime activation, gameplay admission, and LOGIN wire success remain unproved; `AA-2.1` remains partial. See the canonical [session and identity model](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes), [plain-text LOGIN mapping](../../architecture/system-architecture-authentication.md#plain-text-login-logon-command-mapping), [original-attempt coordination](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination), [bounded non-edge recovery](../../architecture/system-architecture-reconnection.md#bounded-non-edge-restart-recovery), [initial-context aggregate](../../architecture/system-architecture-redis.md#initial-login-context-aggregate), and [Redis operation](../../architecture/system-architecture-redis-ops-access.md) owners. +### Entity fixture startup qualification + +The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. + ## Active Gaps - 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. diff --git a/dev-tools/README.md b/dev-tools/README.md index 1c5800aeb0..ac578f83ba 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -49,6 +49,8 @@ FireController is maintained outside this repository. Use the `firecontroller-us - `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/account-workload-namespace-contract.sh` – offline Helm-render contract for Account's Kubernetes workload namespace binding and reserved environment variable. +- `tests/dev-certs-retention-contract.sh` – validates retained development certificate bundles and proves refusal/preservation for incomplete material and linked paths. - `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..54fe3dba50 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -6,10 +6,11 @@ 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. +- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed without automatic replacement. For disposable generated local material, including the default bundle after its 365-day validity expires, explicitly run `bash dev-tools/certs/clean-dev-certs.sh` with the same target (or no target for the default) and retry. Preserve externally managed material and select a fresh dedicated directory instead. The implicit script-local default resolves its directory physically. Explicit caller paths and all managed certificate entries and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for any of the eleven Java application workload identities, with the exact SPIFFE URI and service DNS SANs. This mode requires fresh output paths; callers stage replacement leaves before installing them. Ordinary local development uses the dedicated per-workload helper described below; run-owned smoke uses the qualified fixture described below. 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-local-compose-mtls.sh` owns ordinary local development certificates for all eleven application workloads. See [ordinary local Compose setup and retained-certificate recovery](../../docker/README.md#local-compose-mtls-certificate-recovery); this authority remains separate from run-owned smoke fixtures. - `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. +- `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, World Management, and Game Design 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 local development layers `docker/docker-compose.local-mtls.override.yml` over its base local settings; see the [Docker guide](../../docker/README.md). 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 only recognized generated regular files without hardlinks from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. It refuses a symlinked directory or ancestor, never recurses, and reports preserved entries, including foreign files, directories, and symlinks. Symlink targets are untouched. diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 3139c39eb0..0f3844ca11 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 "$(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,6 +12,18 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi +directory_path="$CERT_DIR" +[[ "$directory_path" == /* ]] || directory_path="$PWD/$directory_path" +while [[ "$directory_path" != / && "$directory_path" == */ ]]; do directory_path="${directory_path%/}"; done +while :; do + if [[ -L "$directory_path" || ( -e "$directory_path" && ! -d "$directory_path" ) ]]; then + echo "Certificate cleanup refuses linked or non-directory paths: $directory_path" >&2 + exit 1 + fi + [[ "$directory_path" != / ]] || break + directory_path="$(dirname -- "$directory_path")" +done + if [ ! -d "$CERT_DIR" ]; then echo "No certificate directory at $CERT_DIR" exit 0 @@ -34,8 +46,10 @@ generated_files=( removed_any=false for filename in "${generated_files[@]}"; do - if [ -e "$CERT_DIR/$filename" ]; then - rm -f "$CERT_DIR/$filename" + entry="$CERT_DIR/$filename" + [[ "$entry" == /* ]] || entry="$PWD/$entry" + if [[ -f "$entry" && ! -L "$entry" && -n "$(find "$entry" -prune -type f -links 1 -print)" ]]; then + rm -f -- "$entry" removed_any=true fi done @@ -45,3 +59,8 @@ if [ "$removed_any" = true ]; then else echo "No generated certificates found in $CERT_DIR" fi + +# Never recurse: scripts, foreign files, directories and links belong to callers. +while IFS= read -r -d '' entry; do + echo "Preserved certificate-directory entry: $entry" +done < <(find "$CERT_DIR" -mindepth 1 -maxdepth 1 -print0) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 4da960bbc7..f7220f129c 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CERT_DIR="${1:-$SCRIPT_DIR}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" +CERT_DIR="${1:-${CERT_DIR:-$SCRIPT_DIR}}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" COMPOSE_MTLS_STAGE_ROOT="" COMPOSE_MTLS_STAGE_DIR="" @@ -246,28 +246,5 @@ 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" -) - -missing=0 -for file in "${required_files[@]}"; do - if [[ ! -f "$file" ]]; then - missing=1 - break - fi -done - -if [[ "$missing" == "0" ]]; then - echo "Development certificates already exist in $CERT_DIR" - exit 0 -fi - +# The generator owns complete-bundle validation and read-only retained reuse. "$GENERATOR" "$CERT_DIR" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 99fef4c51a..772f7d8fa0 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -1,7 +1,39 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" + +# Check lexical ancestors before mkdir/OpenSSL can follow a retained link. +require_safe_directory_path() { + local path="$1" + [[ "$path" == /* ]] || path="$PWD/$path" + while [[ "$path" != / && "$path" == */ ]]; do path="${path%/}"; done + while :; do + if [[ -L "$path" || ( -e "$path" && ! -d "$path" ) ]]; then + echo "Certificate directory and ancestors must be real directories: $path" >&2 + return 1 + fi + [[ "$path" != / ]] || break + path="$(dirname -- "$path")" + done +} + +require_safe_file_path() { + local path="$1" + [[ "$path" == /* ]] || path="$PWD/$path" + require_safe_directory_path "$(dirname -- "$path")" || return 1 + if [[ -L "$path" || ( -e "$path" && ( ! -f "$path" || -z "$(find "$path" -prune -type f -links 1 -print)" ) ) ]]; then + echo "Certificate paths must be regular files without symlinks or hardlinks: $path" >&2 + return 1 + fi +} + +certificate_matches_key() { + local cert_public key_public + cert_public="$(openssl x509 -in "$1" -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum)" || return 1 + key_public="$(openssl pkey -in "$2" -passin pass: -pubout -outform DER | sha256sum)" || return 1 + [[ "$cert_public" == "$key_public" ]] +} if [[ "${1:-}" == "--workload" ]]; then umask 077 @@ -16,6 +48,24 @@ if [[ "${1:-}" == "--workload" ]]; then output_key="$5" runtime_namespace="$6" workload="$7" + # Preflight every input/output before creating directories or writing a key. + for managed_file in "$ca_cert" "$ca_key" "$output_cert" "$output_key"; do + require_safe_file_path "$managed_file" + done + for output_file in "$output_cert" "$output_key"; do + if [[ -e "$output_file" ]]; then + echo "Refusing to overwrite retained workload output: $output_file" >&2 + exit 1 + fi + done + certificate_matches_key "$ca_cert" "$ca_key" || { + echo "Invalid workload certificate authority or mismatched key." >&2 + exit 1 + } + openssl verify -check_ss_sig -CAfile "$ca_cert" "$ca_cert" >/dev/null 2>&1 || { + echo "Invalid or expired workload certificate authority; refusing to sign workload certificate." >&2 + exit 1 + } for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 @@ -90,7 +140,50 @@ 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 +required_files=(ca.crt ca.key server.crt server.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem) +managed_files=("${required_files[@]}" ca.srl server.csr dev-cert.cnf) +require_safe_directory_path "$CERT_DIR" +retained=0 +for filename in "${managed_files[@]}"; do + require_safe_file_path "$CERT_DIR/$filename" + if [[ -e "$CERT_DIR/$filename" ]]; then + retained=1 + fi +done + +if ((retained)); then + for filename in "${required_files[@]}"; do + if [[ ! -f "$CERT_DIR/$filename" ]]; then + echo "Incomplete retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + echo "Only for disposable generated local material (for example interrupted generation), explicitly clean and retry:" >&2 + printf ' bash %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + echo "Preserve externally managed material; select a fresh dedicated directory instead." >&2 + exit 1 + fi + done + # Validate without changing retained bytes, modes, or directory permissions. + valid=1 + certificate_matches_key "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" || valid=0 + openssl verify -check_ss_sig -CAfile "$CERT_DIR/ca.crt" "$CERT_DIR/ca.crt" >/dev/null 2>&1 || valid=0 + cmp -s "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem" || valid=0 + for name in server client dev; do + if [[ "$name" == dev ]]; then + certificate="$CERT_DIR/dev-cert.pem" + private_key="$CERT_DIR/dev-key.pem" + else + certificate="$CERT_DIR/$name.crt" + private_key="$CERT_DIR/$name.key" + fi + certificate_matches_key "$certificate" "$private_key" || valid=0 + openssl verify -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || valid=0 + done + if (( ! valid )); then + echo "Invalid retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + echo "Only for disposable generated local material (for example expired), explicitly clean and retry:" >&2 + printf ' bash %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + echo "Preserve externally managed material; select a fresh dedicated directory instead." >&2 + exit 1 + fi echo "Dev certificates already exist in $CERT_DIR" exit 0 fi @@ -151,13 +244,15 @@ cp "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem" cp "$CERT_DIR/client.crt" "$CERT_DIR/dev-cert.pem" cp "$CERT_DIR/client.key" "$CERT_DIR/dev-key.pem" -rm -f "$CERT_DIR"/*.csr "$CERT_DIR"/*.srl +rm -f -- "$CERT_DIR/server.csr" "$CERT_DIR/ca.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. chmod 755 "$CERT_DIR" -chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/*.key "$CERT_DIR"/*.pem +for filename in "${required_files[@]}"; do + chmod 644 "$CERT_DIR/$filename" +done echo "Certificates generated in $(cd "$CERT_DIR" && pwd)" 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..e4348c5a1c --- /dev/null +++ b/dev-tools/tests/account-workload-namespace-contract.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/account-service" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_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 + +render_and_check() { + local namespace="$1" + local rendered="$2" + local check_extra_env="$3" + shift 3 + + helm template "account-contract-$namespace" "$CHART_DIR" \ + --namespace "$namespace" \ + "$@" \ + >"$rendered" + + python3 - "$rendered" "$namespace" "$check_extra_env" <<'PY' +import pathlib +import sys + +import yaml + +rendered_path = pathlib.Path(sys.argv[1]) +namespace = sys.argv[2] +check_extra_env = sys.argv[3] == "true" +documents = [ + document + for document in yaml.safe_load_all(rendered_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"render in namespace {namespace!r} omitted Account Deployment") + +containers = deployment.get("spec", {}).get("template", {}).get("spec", {}).get("containers", []) +account_container = next( + (container for container in containers if container.get("name") == "account-service"), + None, +) +if account_container is None: + raise SystemExit(f"render in namespace {namespace!r} omitted Account container") + +env = account_container.get("env", []) +namespace_entries = [ + entry + for entry in env + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +] +expected = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +} +if namespace_entries != [expected]: + raise SystemExit( + f"render in namespace {namespace!r} must derive exactly one workload namespace " + f"from metadata.namespace, found {namespace_entries!r}" + ) + +if check_extra_env: + sentinel = [entry for entry in env if entry.get("name") == "ACCOUNT_CONTRACT_SENTINEL"] + if sentinel != [{"name": "ACCOUNT_CONTRACT_SENTINEL", "value": "preserved"}]: + raise SystemExit(f"ordinary extraEnv value was not preserved: {sentinel!r}") +PY +} + +render_and_check default "$TMP_DIR/default.yaml" false +render_and_check account-contract-custom "$TMP_DIR/custom.yaml" true \ + --set-string extraEnv.ACCOUNT_CONTRACT_SENTINEL=preserved + +if helm template account-contract-collision "$CHART_DIR" \ + --namespace account-contract-collision \ + --set-string extraEnv.FIREMUD_GRPC_WORKLOAD_NAMESPACE=override \ + >"$TMP_DIR/collision.out" 2>"$TMP_DIR/collision.err"; then + echo "Account chart accepted extraEnv collision with FIREMUD_GRPC_WORKLOAD_NAMESPACE" >&2 + exit 1 +fi +if ! grep -Fq \ + "extraEnv must not set FIREMUD_GRPC_WORKLOAD_NAMESPACE; Account derives it from the pod namespace" \ + "$TMP_DIR/collision.err"; then + echo "Account chart collision failure omitted its explicit reason" >&2 + cat "$TMP_DIR/collision.err" >&2 + exit 1 +fi + +echo "Account workload namespace Helm contract passed" diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh new file mode 100644 index 0000000000..5ae5f18ba5 --- /dev/null +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -0,0 +1,231 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +GENERATOR="$REPO_ROOT/dev-tools/certs/generate-dev-certs.sh" +ENSURE="$REPO_ROOT/dev-tools/certs/ensure-dev-certs.sh" +CLEAN="$REPO_ROOT/dev-tools/certs/clean-dev-certs.sh" +TEST_ROOT="$(cd "$(mktemp -d)" && pwd -P)" +trap 'rm -rf -- "$TEST_ROOT"' EXIT + +# Only inspect this test's own fixture; record links without following targets. +snapshot() { + python3 - "$1" <<'PY' +import hashlib +import os +import pathlib +import stat +import sys + +root = pathlib.Path(sys.argv[1]) +for directory, subdirs, files in os.walk(root, followlinks=False): + for path in [pathlib.Path(directory)] + sorted(pathlib.Path(directory) / name for name in subdirs + files): + info = path.lstat() + value = "" + if stat.S_ISLNK(info.st_mode): + value = os.readlink(path) + elif stat.S_ISREG(info.st_mode): + value = hashlib.sha256(path.read_bytes()).hexdigest() + print(path.relative_to(root), info.st_mode, info.st_nlink, value) +PY +} + +expect_unchanged_failure() { + local fixture="$1" marker="$2" before after + shift 2 + before="$(snapshot "$fixture")" + if "$@" >"$TEST_ROOT/failure-stdout" 2>"$TEST_ROOT/failure-stderr"; then + echo "Expected certificate operation to refuse retained fixture: $*" >&2 + exit 1 + fi + if ! grep -Fq -- "$marker" "$TEST_ROOT/failure-stderr"; then + echo "Missing refusal marker '$marker' for: $*" >&2 + exit 1 + fi + after="$(snapshot "$fixture")" + if [[ "$before" != "$after" ]]; then + echo "Fixture changed during refused operation: $fixture" >&2 + exit 1 + fi +} + +expired_ca="$TEST_ROOT/expired-ca" +mkdir -p "$expired_ca/new-certs" +: >"$expired_ca/index.txt" +printf '1000\n' >"$expired_ca/serial" +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$expired_ca/ca.key" >/dev/null 2>&1 +openssl req -new -key "$expired_ca/ca.key" -subj '/CN=Expired-Workload-CA' -out "$expired_ca/ca.csr" +cat >"$expired_ca/openssl.cnf" </dev/null 2>&1 +openssl verify -no_check_time -check_ss_sig -CAfile "$expired_ca/ca.crt" "$expired_ca/ca.crt" >/dev/null +if openssl verify -check_ss_sig -CAfile "$expired_ca/ca.crt" "$expired_ca/ca.crt" >/dev/null 2>&1; then + echo 'Expired workload CA fixture unexpectedly verifies at the current time.' >&2 + exit 1 +fi +expect_unchanged_failure "$expired_ca" "Invalid or expired workload certificate authority" bash "$GENERATOR" --workload \ + "$expired_ca/ca.crt" "$expired_ca/ca.key" "$expired_ca/output/nested/client.crt" \ + "$expired_ca/output/nested/client.key" dev world-management-service +[[ ! -e "$expired_ca/output" ]] + +fresh="$TEST_ROOT/fresh" +mkdir "$fresh" +printf 'foreign material\n' >"$fresh/foreign.pem" +chmod 600 "$fresh/foreign.pem" +bash "$GENERATOR" "$fresh" >"$TEST_ROOT/generation-output" 2>&1 +[[ "$(stat -c %a "$fresh/foreign.pem")" == 600 ]] +[[ "$(cat "$fresh/foreign.pem")" == 'foreign material' ]] +for name in ca.crt ca.key server.crt server.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem; do + [[ -s "$fresh/$name" ]] + chmod 640 "$fresh/$name" +done +chmod 750 "$fresh" +before="$(snapshot "$fresh")" +bash "$GENERATOR" "$fresh" >/dev/null +bash "$ENSURE" "$fresh" >/dev/null +[[ "$before" == "$(snapshot "$fresh")" ]] + +partial="$TEST_ROOT/partial" +mkdir "$partial" +printf 'retained CA\n' >"$partial/ca.crt" +for command in "$GENERATOR" "$ENSURE"; do + expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$command" "$partial" + grep -Fq 'Only for disposable generated local material' "$TEST_ROOT/failure-stderr" + grep -Fq 'clean-dev-certs.sh ' "$TEST_ROOT/failure-stderr" + grep -Fq 'Preserve externally managed material' "$TEST_ROOT/failure-stderr" +done + +other="$TEST_ROOT/other" +bash "$GENERATOR" "$other" >"$TEST_ROOT/other-output" 2>&1 +for corruption in malformed key ca ca-key; do + fixture="$TEST_ROOT/$corruption" + cp -a -- "$fresh" "$fixture" + case "$corruption" in + malformed) printf 'invalid certificate\n' >"$fixture/client.crt" ;; + key) cp -- "$other/client.key" "$fixture/dev-key.pem" ;; + ca) cp -- "$other/ca.crt" "$fixture/ca.crt"; cp -- "$other/ca.key" "$fixture/ca.key"; cp -- "$other/dev-ca.pem" "$fixture/dev-ca.pem" ;; + ca-key) cp -- "$other/ca.key" "$fixture/ca.key" ;; + esac + for command in "$GENERATOR" "$ENSURE"; do + expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$command" "$fixture" + grep -Fq 'Only for disposable generated local material' "$TEST_ROOT/failure-stderr" + grep -Fq 'clean-dev-certs.sh ' "$TEST_ROOT/failure-stderr" + grep -Fq 'Preserve externally managed material' "$TEST_ROOT/failure-stderr" + done +done + +links="$TEST_ROOT/links" +mkdir "$links" "$links/outside" "$links/partial" "$links/hard" "$links/nonregular" +printf 'outside retained material\n' >"$links/outside/material" +ln -s "$links/outside/material" "$links/partial/dev-key.pem" +ln "$links/outside/material" "$links/hard/ca.key" +mkdir "$links/nonregular/ca.crt" +ln -s "$links/outside" "$links/directory" +for target in "$links/partial" "$links/hard" "$links/nonregular" "$links/directory/" "$links/directory/new"; do + marker="Certificate paths must be regular files without symlinks or hardlinks" + case "$target" in + "$links/directory/"|"$links/directory/new") marker="Certificate directory and ancestors must be real directories" ;; + esac + expect_unchanged_failure "$links" "$marker" bash "$GENERATOR" "$target" + expect_unchanged_failure "$links" "$marker" bash "$ENSURE" "$target" +done +# A link in an otherwise complete bundle is also refused without a mode change. +linked_complete="$TEST_ROOT/linked-complete" +cp -a -- "$fresh" "$linked_complete" +rm -- "$linked_complete/ca.key" +ln -s "$fresh/ca.key" "$linked_complete/ca.key" +expect_unchanged_failure "$linked_complete" "Certificate paths must be regular files without symlinks or hardlinks" bash "$ENSURE" "$linked_complete" + +workloads="$TEST_ROOT/workloads" +mkdir "$workloads" +printf 'retained output\n' >"$workloads/existing.crt" +ln -s "$links/outside/material" "$workloads/linked.key" +ln "$links/outside/material" "$workloads/hard.key" +for key in linked.key hard.key; do + expect_unchanged_failure "$workloads" "Certificate paths must be regular files without symlinks or hardlinks" bash "$GENERATOR" --workload \ + "$fresh/ca.crt" "$fresh/ca.key" "$workloads/new/client.crt" "$workloads/$key" dev world-management-service +done +expect_unchanged_failure "$workloads" "Refusing to overwrite retained workload output" bash "$GENERATOR" --workload \ + "$fresh/ca.crt" "$fresh/ca.key" "$workloads/existing.crt" "$workloads/new/client.key" dev world-management-service + +cleanup="$TEST_ROOT/cleanup" +cp -a -- "$fresh" "$cleanup" +rm -- "$cleanup/client.key" "$cleanup/server.key" +ln -s "$links/outside/material" "$cleanup/client.key" +ln "$links/outside/material" "$cleanup/server.key" +printf 'foreign certificate\n' >"$cleanup/foreign.crt" +mkdir "$cleanup/foreign-directory" +outside_before="$(snapshot "$links/outside")" +bash "$CLEAN" "$cleanup" >"$TEST_ROOT/cleanup-output" +[[ ! -e "$cleanup/ca.crt" && ! -e "$cleanup/dev-key.pem" ]] +[[ -L "$cleanup/client.key" && -f "$cleanup/server.key" && -d "$cleanup/foreign-directory" ]] +[[ "$(cat "$cleanup/foreign.crt")" == 'foreign certificate' ]] +[[ "$(cat "$cleanup/foreign.pem")" == 'foreign material' ]] +[[ "$outside_before" == "$(snapshot "$links/outside")" ]] +for entry in client.key server.key foreign.crt foreign-directory; do + grep -Fq "Preserved certificate-directory entry: $cleanup/$entry" "$TEST_ROOT/cleanup-output" +done +for target in "$links/directory/" "$links/directory/new"; do + expect_unchanged_failure "$links" "Certificate cleanup refuses linked or non-directory paths" bash "$CLEAN" "$target" +done + +# Resolve the implicit script root physically while refusing explicit linked paths. +physical_root="$TEST_ROOT/physical-root" +mkdir -p "$physical_root/certs" +cp -p -- "$GENERATOR" "$ENSURE" "$CLEAN" "$physical_root/certs/" +ln -s "$physical_root" "$TEST_ROOT/workspace-link" +printf 'retained checkout material\n' >"$physical_root/certs/foreign.pem" +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/generate-dev-certs.sh >"$TEST_ROOT/default-generation-output" 2>&1 +) +[[ -s "$physical_root/certs/ca.crt" && -s "$physical_root/certs/server.key" ]] +before="$(snapshot "$physical_root")" +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/ensure-dev-certs.sh >"$TEST_ROOT/default-ensure-output" 2>&1 +) +[[ "$before" == "$(snapshot "$physical_root")" ]] +for operation in "$GENERATOR" "$ENSURE" "$CLEAN"; do + marker="Certificate directory and ancestors must be real directories" + if [[ "$operation" == "$CLEAN" ]]; then + marker="Certificate cleanup refuses linked or non-directory paths" + fi + expect_unchanged_failure "$physical_root" "$marker" bash "$operation" "$TEST_ROOT/workspace-link/certs" +done +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/clean-dev-certs.sh >"$TEST_ROOT/default-cleanup-output" 2>&1 +) +[[ ! -e "$physical_root/certs/ca.crt" && ! -e "$physical_root/certs/server.key" ]] +[[ "$(cat "$physical_root/certs/foreign.pem")" == 'retained checkout material' ]] +for script in generate-dev-certs.sh ensure-dev-certs.sh clean-dev-certs.sh; do + cmp -s "$physical_root/certs/$script" "$REPO_ROOT/dev-tools/certs/$script" +done + +echo 'Development certificate retention and physical-default contracts passed.' diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index b4d72c86df..6e0cf3c33f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -64,6 +64,9 @@ services: SPRING_FLYWAY_TABLE: flyway_schema_history_account_service FIREMUD_DATABASE_ENABLED: "true" FIREMUD_SMOKE_SEED_DEMO_ACCOUNT_ENABLED: "true" + SPRING_PROFILES_ACTIVE: local-fixture + FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED: "true" + FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL: demo@example.com env_file: *service-env-file volumes: *service-vols restart: unless-stopped diff --git a/k8s/helm/account-service/templates/deployment.yaml b/k8s/helm/account-service/templates/deployment.yaml index bde01874a2..95f0d96d5b 100644 --- a/k8s/helm/account-service/templates/deployment.yaml +++ b/k8s/helm/account-service/templates/deployment.yaml @@ -23,10 +23,17 @@ spec: ports: - containerPort: 8080 env: + {{- if hasKey (default dict .Values.extraEnv) "FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} + {{- fail "extraEnv must not set FIREMUD_GRPC_WORKLOAD_NAMESPACE; Account derives it from the pod namespace" }} + {{- end }} {{- range $key, $value := .Values.extraEnv }} - name: {{ $key }} value: "{{ $value }}" {{- end }} + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace readinessProbe: httpGet: path: {{ .Values.readinessProbe.path }} diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 2149e6f927..922f3b881c 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -25,12 +25,16 @@ service AccountService { rpc ListPresenceVisibilityPolicies(ListPresenceVisibilityPoliciesRequest) returns (ListPresenceVisibilityPoliciesResponse); rpc UpdateProfile(UpdateProfileRequest) returns (UpdateProfileResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc ExportAccount(ExportAccountRequest) returns (ExportAccountResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc ExportTenantData(ExportTenantDataRequest) returns (ExportTenantDataResponse); rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse); rpc RequestPasswordReset(RequestPasswordResetRequest) returns (RequestPasswordResetResponse); rpc CompletePasswordReset(CompletePasswordResetRequest) returns (CompletePasswordResetResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc LinkExternalAccount(LinkExternalAccountRequest) returns (LinkExternalAccountResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc RequestEmailVerification(RequestEmailVerificationRequest) returns (RequestEmailVerificationResponse); rpc VerifyEmail(VerifyEmailRequest) returns (VerifyEmailResponse); } diff --git a/protos/account/v1/virtual_currency_service.proto b/protos/account/v1/virtual_currency_service.proto index e459eb93a9..6e43d87c5f 100644 --- a/protos/account/v1/virtual_currency_service.proto +++ b/protos/account/v1/virtual_currency_service.proto @@ -7,6 +7,8 @@ import "shared/v1/errors.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; +// These deferred methods currently fail before domain execution with non-OK +// FAILED_PRECONDITION and bounded ErrorDetail status trailers, without a response. service VirtualCurrencyService { rpc GetBalance(GetBalanceRequest) returns (GetBalanceResponse); rpc AddCurrency(AddCurrencyRequest) returns (AddCurrencyResponse); 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..cfa661c7e2 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 @@ -10,6 +10,9 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -67,6 +70,34 @@ public void deleteByAccountId(Long accountId) { .execute(); } + /** Claims only the exact original, still-valid token in the Account owner's transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean consumeIfUnexpired(EmailVerificationToken token, LocalDateTime capturedNow) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Email verification requires an active writable owner transaction"); + } + if (token == null + || token.getId() == null + || token.getAccount() == null + || token.getAccount().getId() == null + || capturedNow == 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.ACCOUNT_ID.eq(token.getAccount().getId())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.eq(token.getExpiresAt())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.gt(capturedNow))) + .execute() + == 1; + } + /** Deletes at most {@code batchSize} expired rows in deterministic expiry/id order. */ public int deleteExpired(LocalDateTime capturedNow, int batchSize) { return JooqAccountRepositorySupport.deleteExpired( 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 29d8c1bb0a..cd964043bb 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 @@ -1,7 +1,9 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -61,6 +63,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; import org.springframework.transaction.TransactionException; @@ -79,6 +83,8 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private final AccountService accountService; private final MeterRegistry meterRegistry; private final String workloadNamespace; + private final boolean localDemoAuthenticationEnabled; + private final String localDemoEmail; public AccountGrpcService(PingService pingService, AccountService accountService) { this(pingService, accountService, null, null); @@ -89,6 +95,14 @@ public AccountGrpcService( this(pingService, accountService, meterRegistry, null); } + public AccountGrpcService( + PingService pingService, + AccountService accountService, + MeterRegistry meterRegistry, + String workloadNamespace) { + this(pingService, accountService, meterRegistry, workloadNamespace, null, false, ""); + } + @Autowired @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -97,11 +111,22 @@ public AccountGrpcService( PingService pingService, AccountService accountService, MeterRegistry meterRegistry, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + Environment environment, + @Value("${firemud.account.local-demo-authentication.enabled:false}") + boolean localDemoAuthenticationEnabled, + @Value("${firemud.account.local-demo-authentication.email:}") String localDemoEmail) { this.pingService = pingService; this.accountService = accountService; this.meterRegistry = meterRegistry; this.workloadNamespace = workloadNamespace; + this.localDemoAuthenticationEnabled = + localDemoAuthenticationEnabled + && environment != null + && environment.acceptsProfiles(Profiles.of("local-fixture")) + && !environment.acceptsProfiles(Profiles.of("prod")); + this.localDemoEmail = + this.localDemoAuthenticationEnabled ? EmailCanonicalization.normalize(localDemoEmail) : ""; } @Override @@ -217,6 +242,30 @@ private void requireGameSessionPeer() { "Verified Game Session workload identity is required", "game-session-service"); } + private void requireCredentialPeer(AuthenticateRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(workloadNamespace)) { + requireGameSessionPeer(); + return; + } + requireWorkloadPeer( + "Verified Game Session or local-fixture Entity Management workload identity is required", + "entity-management-service"); + if (!localDemoAuthenticationEnabled) { + throw new AdminAuthorizationException("Local demo authentication is unavailable"); + } + try { + if (localDemoEmail.equals(EmailCanonicalization.normalize(request.getEmail()))) { + return; + } + } catch (IllegalArgumentException ignored) { + // Invalid fixture identity does not authorize credential verification. + } + throw new AdminAuthorizationException("Configured local demo account identity is required"); + } + private void requireRuntimeEntitlementsPeer() { requireWorkloadPeer( "Verified Game Session or World Management workload identity is required", @@ -377,6 +426,7 @@ public void createAccount( public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { + requireCredentialPeer(request); net.firedevops.firemud.accountservice.dto.AuthenticationResult result = accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = @@ -386,6 +436,12 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { AuthenticateResponse response = AuthenticateResponse.newBuilder() @@ -423,8 +479,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() @@ -439,12 +501,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(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() @@ -936,97 +1004,14 @@ public void updateProfile( @Timed(value = "accountGrpc.exportAccount") public void exportAccount( ExportAccountRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportAccountData( - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - 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 (AccountUuidReadbackUnavailableException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(accountUuidReadbackUnavailableError("ExportAccount")) - .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 (AuthenticationException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", ex.getCode(), 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(); - } + refuseUnconfiguredInternalCaller("ExportAccount", responseObserver); } @Override @Timed(value = "accountGrpc.exportTenantData") public void exportTenantData( ExportTenantDataRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportTenantData( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - 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 (AccountUuidReadbackUnavailableException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(accountUuidReadbackUnavailableError("ExportTenantData")) - .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 (AuthenticationException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", ex.getCode(), 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(); - } + refuseUnconfiguredInternalCaller("ExportTenantData", responseObserver); } @Override @@ -1151,44 +1136,7 @@ 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"), - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId())), - request.getProvider(), - request.getExternalId())); - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(accountUuidReadbackUnavailableError("LinkExternalAccount")) - .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(); - } + refuseUnconfiguredInternalCaller("LinkExternalAccount", responseObserver); } @Override @@ -1197,40 +1145,7 @@ public void requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest request, StreamObserver responseObserver) { - try { - accountService.requestEmailVerification( - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(accountUuidReadbackUnavailableError("RequestEmailVerification")) - .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(); - } + refuseUnconfiguredInternalCaller("RequestEmailVerification", responseObserver); } @Override @@ -1297,6 +1212,18 @@ private AccountUuidReadbackUnavailableException(Throwable cause) { } } + private void refuseUnconfiguredInternalCaller(String operation, StreamObserver observer) { + String message = "No authorized internal caller is configured"; + var detail = appError(operation, "FAILED_PRECONDITION", message); + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.FAILED_PRECONDITION.value()) + .setMessage(message) + .addDetails(Any.pack(detail)) + .build())); + } + private net.firedevops.firemud.shared.v1.ErrorDetail appError( String operation, String code, String message) { return meterRegistry == null 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 4da20b561c..13fefe53f3 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 @@ -3184,13 +3184,33 @@ public void verifyEmail(VerifyEmailRequest request) { emailVerificationTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + if (token.getId() == null + || token.getId() <= 0L + || token.getAccount() == null + || token.getAccount().getId() == null + || token.getAccount().getId() <= 0L + || token.getExpiresAt() == null + || !request.token().equals(token.getToken())) { + throw new IllegalArgumentException("Invalid token"); + } + // The token join supplies a locator, not the current full Account to mutate. + Long accountId = token.getAccount().getId(); + Account account = + accountRepository + .findByIdForUpdate(accountId) + .orElseThrow(() -> new IllegalArgumentException("Invalid token")); + if (!accountId.equals(account.getId())) { + throw new IllegalArgumentException("Invalid token"); + } + LocalDateTime capturedNow = LocalDateTime.now(); + if (!token.getExpiresAt().isAfter(capturedNow)) { throw new IllegalArgumentException("Token expired"); } - Account account = token.getAccount(); + if (!emailVerificationTokenRepository.consumeIfUnexpired(token, capturedNow)) { + throw new IllegalArgumentException("Invalid token"); + } 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..03af9c2861 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 @@ -1,6 +1,9 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -11,12 +14,10 @@ import net.firedevops.firemud.account.v1.SpendCurrencyRequest; import net.firedevops.firemud.account.v1.SpendCurrencyResponse; 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; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -24,24 +25,12 @@ public class VirtualCurrencyGrpcService extends VirtualCurrencyServiceGrpc.VirtualCurrencyServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(VirtualCurrencyGrpcService.class); - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "CurrencyService is injected and not exposed") - private final VirtualCurrencyService currencyService; - private final MeterRegistry meterRegistry; - public VirtualCurrencyGrpcService(VirtualCurrencyService currencyService) { - this(currencyService, null); - } - - @Autowired @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "Injected service and registry remain internal collaborators.") - public VirtualCurrencyGrpcService( - VirtualCurrencyService currencyService, MeterRegistry meterRegistry) { - this.currencyService = currencyService; + justification = "Injected registry remains an internal collaborator.") + public VirtualCurrencyGrpcService(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } @@ -49,98 +38,34 @@ 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.onError(unavailable("GetBalance")); } @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.onError(unavailable("AddCurrency")); } @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.onError(unavailable("SpendCurrency")); + } + + private RuntimeException unavailable(String operation) { + String message = operation + " is unavailable"; + ErrorDetail detail = + meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.FAILED_PRECONDITION.value()) + .setMessage(message) + .addDetails(Any.pack(detail)) + .build()); } } diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 138a962cd0..07b28a5463 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -54,7 +54,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 790568480b..99eadbdc10 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -42,6 +42,9 @@ firemud: ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} account: + local-demo-authentication: + enabled: ${FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED:false} + email: ${FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL:} credentials: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} @@ -86,7 +89,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index d0b963a010..4745356dd3 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -586,13 +586,11 @@ paths: summary: Verify email token operationId: verifyEmail description: >- - Target state is a public token-verification endpoint. In the current - deployment the POST route is not in the public-route allowlist and - therefore requires bearer authentication; the allowlisted GET route - has no controller mapping. Do not treat this operation as publicly - reachable until the HTTP configuration and link handoff converge. - security: - - bearerAuth: [] + The public POST verifies an account-scoped email token without bearer + authentication. The configured verification email still links to + GET /auth/verify-email, which has no controller mapping; browser + handoff to the public POST remains unavailable. + security: [] requestBody: required: true content: 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 0cf8542d4b..e6ab3e3767 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,17 +1,35 @@ 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.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; import java.util.List; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +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.CreateAccountRequest; +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.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; @@ -32,6 +50,7 @@ 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.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -80,6 +99,14 @@ static void configure(DynamicPropertyRegistry registry) { @org.springframework.test.context.bean.override.mockito.MockitoSpyBean private net.firedevops.firemud.accountservice.repository.AccountRepository accountRepository; + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository + emailVerificationTokenRepository; + + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository + joinOperationRepository; + @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -98,6 +125,592 @@ void pingEndpointReturnsPong() { assertThat(body).contains("pong"); } + @Test + void concurrentEmailVerificationClaimsTheExactTokenOnce() throws Exception { + var fixture = emailVerificationFixture(); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var located = new CountDownLatch(2); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + located.countDown(); + if (!located.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Both verification attempts must read the token"); + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + var executor = Executors.newFixedThreadPool(2); + try { + Callable attempt = + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Email verification start was not released"); + } + try { + verifyEmail(fixture.token()); + return true; + } catch (IllegalArgumentException consumed) { + return false; + } + }; + var first = executor.submit(attempt); + var second = executor.submit(attempt); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(30, TimeUnit.SECONDS)).isNotEqualTo(second.get(30, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", fixture.accountId())) + .isEqualTo(true); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM email_verification_token WHERE token = ?", fixture.token())) + .isEqualTo(0L); + } + + @Test + void expiredAndExactlyExpiringEmailVerificationTokensCannotMutateAccount() { + for (boolean equality : List.of(false, true)) { + var fixture = emailVerificationFixture(); + var expiry = LocalDateTime.now().minusSeconds(1); + dsl.execute( + "UPDATE email_verification_token SET expires_at = ? WHERE token = ?", + expiry, + fixture.token()); + var before = emailVerificationState(fixture); + if (equality) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + accountRepository.findByIdForUpdate(fixture.accountId()).orElseThrow(); + var token = + emailVerificationTokenRepository.findByToken(fixture.token()).orElseThrow(); + assertThat( + emailVerificationTokenRepository.consumeIfUnexpired( + token, token.getExpiresAt())) + .isFalse(); + }); + } else { + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Token expired"); + } + assertThat(emailVerificationState(fixture)).isEqualTo(before); + } + } + + @Test + void changedOriginalEmailVerificationTokenCannotMutateAccount() { + for (String field : List.of("token", "expires_at", "account_id")) { + var fixture = emailVerificationFixture(); + var other = emailVerificationFixture(); + var before = emailVerificationState(fixture); + var changed = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + if (changed.compareAndSet(false, true)) { + switch (field) { + case "token" -> + dsl.execute( + "UPDATE email_verification_token SET token = ? WHERE token = ?", + fixture.token() + "-changed", + fixture.token()); + case "expires_at" -> + dsl.execute( + "UPDATE email_verification_token SET expires_at = expires_at + INTERVAL '1 second' WHERE token = ?", + fixture.token()); + case "account_id" -> + dsl.execute( + "UPDATE email_verification_token SET account_id = ? WHERE token = ?", + other.accountId(), + fixture.token()); + default -> throw new AssertionError(field); + } + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid token"); + + // The injected change shares the owner transaction and rolls back with the rejected claim. + assertThat(emailVerificationState(fixture)).isEqualTo(before); + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", other.accountId())) + .isEqualTo(false); + } + } + + @Test + void emailVerificationRollbackRestoresTokenAccountAndSourceEvidence() { + var fixture = emailVerificationFixture(); + var before = emailVerificationState(fixture); + var transaction = new TransactionTemplate(transactionManager); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + verifyEmail(fixture.token()); + throw new IllegalStateException("failure after verification source update"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("failure after verification source update"); + assertThat(emailVerificationState(fixture)).isEqualTo(before); + verifyEmail(fixture.token()); + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", fixture.accountId())) + .isEqualTo(true); + } + + @Test + void emailVerificationWithoutOwnerBaselineRollsBackClaimWithoutEnrollingRetainedAccount() { + String suffix = UUID.randomUUID().toString(); + // A raw retained-style row deliberately lacks repository-owned V40 source initialization. + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "retained-" + suffix.substring(0, 8), + suffix + "@example.com", + "retained-password") + .fetchOne(0, Long.class)); + var fixture = insertEmailVerificationToken(accountId); + var before = emailVerificationState(fixture); + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(SourceEvidenceUnavailableException.class); + assertThat(emailVerificationState(fixture)).isEqualTo(before); + } + + @Test + void emailVerificationUsesFreshOwnerAfterConcurrentAccountUpdate() throws Exception { + var fixture = emailVerificationFixture(); + var changed = new AtomicBoolean(); + var executor = Executors.newSingleThreadExecutor(); + try { + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + if (changed.compareAndSet(false, true)) { + executor + .submit( + () -> + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + var current = + accountRepository + .findByIdForUpdate(fixture.accountId()) + .orElseThrow(); + current.setUsername("current-" + fixture.accountId()); + current.setEmail( + "current-" + fixture.accountId() + "@example.com"); + current.setPasswordHash("current-password-hash"); + current.setRole("player"); + current.setLoginAuthModes("EMAIL_OTP"); + accountRepository.save(current); + })) + .get(30, TimeUnit.SECONDS); + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + UUID originalUuid = + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", fixture.accountId()) + .fetchOne(0, UUID.class); + + verifyEmail(fixture.token()); + + var current = accountRepository.findById(fixture.accountId()).orElseThrow(); + assertThat(current.isEmailVerified()).isTrue(); + assertThat(current.getUsername()).isEqualTo("current-" + fixture.accountId()); + assertThat(current.getEmail()).isEqualTo("current-" + fixture.accountId() + "@example.com"); + assertThat(current.getPasswordHash()).isEqualTo("current-password-hash"); + assertThat(current.getRole()).isEqualTo("player"); + assertThat(current.getAccountUuid()).isEqualTo(originalUuid); + assertThat(current.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); + assertThat(current.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(current.getLoginAuthModes()).isEqualTo("EMAIL_OTP"); + } finally { + executor.shutdownNow(); + } + } + + private EmailVerificationFixture emailVerificationFixture() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + var account = + accountService.createAccount( + new CreateAccountRequest( + "verify-" + suffix, "verify-" + suffix + "@example.com", "password123")); + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) + .fetchOne(0, Long.class)); + return insertEmailVerificationToken(accountId); + } + + private EmailVerificationFixture insertEmailVerificationToken(long accountId) { + String token = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO email_verification_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + token, + LocalDateTime.now().plusHours(1)); + return new EmailVerificationFixture(accountId, token); + } + + private void verifyEmail(String token) { + accountService.verifyEmail(new VerifyEmailRequest(token)); + } + + private List emailVerificationState(EmailVerificationFixture fixture) { + return List.of( + dsl.resultQuery( + "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(t)::text FROM email_verification_token t WHERE token = ?", + fixture.token()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " + + "FROM account_authority_source_records s WHERE account_uuid = " + + "(SELECT account_uuid FROM accounts WHERE id = ?)", + fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COUNT(*)::text FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = 'account:auth-authority:v1:account/' || " + + "(SELECT account_uuid::text FROM accounts WHERE id = ?)", + fixture.accountId()) + .fetchOne(0, String.class)); + } + + private record EmailVerificationFixture(long accountId, String token) {} + + @Test + void publicJoinLostCommitAcknowledgementAndReadbackReplayTheSameOriginalOnce() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + + assertPublicJoinUnavailable(fixture); + + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var replay = publicJoin(fixture); + + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.outcomeCode()).isEqualTo("JOINED"); + assertThat(replay.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @Test + void publicJoinFailureBeforeCommitRollsBackEffectsAndContinuesTheOriginalIntent() { + var fixture = publicJoinFixture(); + var failOnce = new AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + if (failOnce.compareAndSet(true, false)) { + // The real terminal UPDATE ran, but its owner transaction has not committed. + throw new IllegalStateException("Injected failure before public JOIN commit"); + } + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + + assertPublicJoinUnavailable(fixture); + + assertThat(failOnce).isFalse(); + var pending = + dsl.fetchOne( + "SELECT status, outcome, intent_digest, request_digest, membership_id " + + "FROM account_join_operations WHERE request_id = ?", + fixture.caller().requestId()); + assertThat(pending).isNotNull(); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("intent_digest", String.class)).startsWith("sha256:"); + assertThat(pending.get("outcome")).isNull(); + assertThat(pending.get("request_digest")).isNull(); + assertThat(pending.get("membership_id")).isNull(); + assertThat(publicJoinMembershipCount(fixture)).isZero(); + assertThat(publicJoinAuditCount(fixture)).isZero(); + + var continued = publicJoin(fixture); + + assertThat(continued.success()).isTrue(); + assertThat(continued.replayed()).isFalse(); + assertThat(continued.outcomeCode()).isEqualTo("JOINED"); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + } + + @Test + void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + assertPublicJoinUnavailable(fixture); + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + String retainedExpiry = + dsl.resultQuery( + "SELECT s.connect_scope_expires_at FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class); + assertThat(retainedExpiry).isNotBlank(); + Instant expiredNow = Instant.parse(retainedExpiry).plusSeconds(1); + + // Advance only the owner clock; never rewrite the original scope, intent or terminal row. + try (org.mockito.MockedStatic clock = + org.mockito.Mockito.mockStatic(Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + clock.when(Instant::now).thenReturn(expiredNow); + var refused = publicJoin(fixture); + assertThat(refused.success()).isFalse(); + assertThat(refused.replayed()).isFalse(); + assertThat(refused.outcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + } + + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertPublicJoinCommittedOnce(fixture); + } + + private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { + var committed = new AtomicBoolean(); + var readbackDropped = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCommit() { + committed.set(true); + throw new IllegalStateException("Injected lost public JOIN commit ACK"); + } + }); + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doAnswer( + invocation -> { + if (committed.get() && readbackDropped.compareAndSet(false, true)) { + throw new org.springframework.dao.DataAccessResourceFailureException( + "Injected unavailable first post-commit JOIN readback"); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .find(fixture.caller().requestId()); + return readbackDropped; + } + + private void assertPublicJoinUnavailable(PublicJoinFixture fixture) { + var unavailable = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, () -> publicJoin(fixture)); + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } + + private JoinPublicProductionResult publicJoin(PublicJoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.caller().requestId())); + } + + private PublicJoinFixture publicJoinFixture() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String world = "join-" + suffix; + var account = + accountService.createAccount( + new CreateAccountRequest(world, world + "@example.com", "password123")); + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) + .fetchOne(0, Long.class)); + long tenantId = 6000000000L + accountId; + dsl.execute( + "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) " + + "VALUES(?,'join-proof','active',?,1)", + accountId, + tenantId); + UUID realmId = UUID.randomUUID(); + String namespace = UUID.randomUUID().toString(); + var realm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + var pointer = + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + org.mockito.Mockito.when(gameSessionClient.listGameplayRealms(world)) + .thenReturn(List.of(realm)); + org.mockito.Mockito.when(gameSessionClient.getAdmissionPointer(tenantId, world, "production")) + .thenReturn(pointer); + var caller = + new DirectTextCallerContext( + accountId, + tenantId, + realmId, + namespace, + "SHARED", + 44L, + "controlled-join-session-" + suffix, + "original-join-" + suffix); + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, realmId, world, "production", namespace, "SHARED", 44L, 23L, 17L)); + return new PublicJoinFixture(accountId, account.id(), tenantId, caller, scope.connectScopeId()); + } + + private long publicJoinMembershipCount(PublicJoinFixture fixture) { + return java.util.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 UUID publicJoinAuditId(PublicJoinFixture fixture) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.caller().requestId()).getBytes(StandardCharsets.UTF_8)); + } + + private long publicJoinAuditCount(PublicJoinFixture fixture) { + return java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, Long.class)); + } + + private void assertPublicJoinCommittedOnce(PublicJoinFixture fixture) { + assertThat(publicJoinMembershipCount(fixture)).isEqualTo(1L); + assertThat(publicJoinAuditCount(fixture)).isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations j " + + "JOIN account_tenant_membership m ON m.id = j.membership_id " + + "WHERE j.request_id = ? AND j.status = 'COMMITTED' AND j.outcome = 'JOINED' " + + "AND j.account_id = ? AND j.tenant_id = ? " + + "AND m.account_id = j.account_id AND m.tenant_id = j.tenant_id " + + "AND m.lifecycle_state = 'ACTIVE' AND m.authority_provenance = 'EXPLICIT_JOIN' " + + "AND m.membership_version = 1 AND m.membership_authority_generation = 1 " + + "AND j.outcome_membership_version = m.membership_version " + + "AND j.outcome_membership_authority_generation = m.membership_authority_generation", + fixture.caller().requestId(), + fixture.accountId(), + fixture.tenantId())) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "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::jsonb ->> 'requestId' = ? " + + "AND payload::jsonb ->> 'accountId' = ? " + + "AND payload::jsonb ->> 'membershipVersion' = '1'", + publicJoinAuditId(fixture), + fixture.tenantId(), + fixture.caller().requestId(), + Long.toString(fixture.accountId()))) + .isEqualTo(1L); + } + + private List publicJoinState(PublicJoinFixture fixture) { + return List.of( + dsl.resultQuery( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(m)::text FROM account_tenant_membership m " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, String.class), + dsl.resultQuery( + // Delivery retry diagnostics may advance independently of original JOIN evidence. + "SELECT (to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text " + + "FROM account_audit_outbox a WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(s)::text FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class)); + } + + private record PublicJoinFixture( + long accountId, + String accountUuid, + long tenantId, + DirectTextCallerContext caller, + String connectScopeId) {} + @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java new file mode 100644 index 0000000000..da8d99a809 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java @@ -0,0 +1,174 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.controller.AuthController; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.common.GlobalExceptionHandler; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.yaml.snakeyaml.Yaml; + +/** Actual Account YAML and servlet-auth composition with a mocked verification owner. */ +class EmailVerificationHttpAuthWiringTest { + private static final String PATH = "/auth/verify-email"; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void publicPostReachesMappedVerificationOwnerWithoutBearer(boolean productionLayer) { + assertOpenApiDeclaresPublicPost(); + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpAuthProperties properties = context.getBean(HttpAuthProperties.class); + assertThat(properties.isEnabled()).isTrue(); + assertThat(properties.getPublicRoutes()) + .filteredOn(route -> PATH.equals(route.getPathPattern())) + .extracting(HttpAuthProperties.HttpPublicRoute::getMethod) + .containsExactly("POST"); + AccountService owner = mock(AccountService.class); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); + + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"exact-verification-token\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("SUCCESS")); + + verify(owner).verifyEmail(new VerifyEmailRequest("exact-verification-token")); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void publicPostPreservesVerificationOwnersInvalidTokenOutcome(boolean productionLayer) { + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + AccountService owner = mock(AccountService.class); + VerifyEmailRequest invalid = new VerifyEmailRequest("invalid-token"); + doThrow(new IllegalArgumentException("Invalid token")) + .when(owner) + .verifyEmail(invalid); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .setControllerAdvice(new GlobalExceptionHandler()) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); + + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"invalid-token\"}")) + .andExpect(status().isBadRequest()); + + verify(owner).verifyEmail(invalid); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void getIsNotWhitelistedWithoutBearer(boolean productionLayer) { + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpJwtAuthInterceptor interceptor = context.getBean(HttpJwtAuthInterceptor.class); + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertThat(interceptor.preHandle(request, response, new Object())).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(jwtUtil); + }); + } + + private static WebApplicationContextRunner configuredRunner( + boolean productionLayer, JwtUtil jwtUtil) { + return new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class, + CommonSecurityServletAutoConfiguration.class)) + .withBean("jwtUtil", JwtUtil.class, () -> jwtUtil) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + for (var source : + loader.load( + "account-application", + new FileSystemResource("src/main/resources/application.yml"))) { + context.getEnvironment().getPropertySources().addLast(source); + } + if (productionLayer) { + context.getEnvironment().setActiveProfiles("prod"); + for (var source : + loader.load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml"))) { + context.getEnvironment().getPropertySources().addFirst(source); + } + } + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account HTTP auth YAML", exception); + } + }); + } + + private static void assertOpenApiDeclaresPublicPost() { + try (var input = + EmailVerificationHttpAuthWiringTest.class.getResourceAsStream("/openapi.yaml")) { + Map document = new Yaml().load(input); + Map paths = (Map) document.get("paths"); + Map verifyEmailPath = (Map) paths.get(PATH); + Map operation = (Map) verifyEmailPath.get("post"); + + assertThat(operation.get("operationId")).isEqualTo("verifyEmail"); + assertThat(operation.containsKey("security")).isTrue(); + assertThat(operation.get("security")).isEqualTo(List.of()); + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account OpenAPI YAML", exception); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java new file mode 100644 index 0000000000..716f4eef16 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java @@ -0,0 +1,337 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; +import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; +import net.firedevops.firemud.accountservice.dto.AuthenticationResult; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.mock.env.MockEnvironment; + +/** + * Physical TLS caller-policy proof with a mocked Account credential owner, not credential proof. + */ +class AccountCredentialPeerGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String DEMO_EMAIL = "demo@example.com"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + + @TempDir static Path temporaryDirectory; + + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "FireMUD Account credential peer test CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec("game-session", GAME_SESSION_URI, false), + new IdentitySpec("entity", ENTITY_URI, false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "other-game-session", "spiffe://firemud/ns/other/sa/game-session-service", false), + new IdentitySpec( + "other-entity", "spiffe://firemud/ns/other/sa/entity-management-service", false)); + } + + @Test + void gameSessionCertificateAuthorizesAllThreeCredentialMethodsWithoutFixtureSettings() + throws Exception { + AccountService owner = credentialOwner(GAME_SESSION_URI); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), owner, null, NAMESPACE); + try (TransportServer server = startServer(service); + ClientTransport client = newClient(server.port(), "game-session")) { + var stub = client.stub(); + assertAuthenticated(stub.authenticate(authentication(DEMO_EMAIL))); + var challenge = stub.requestEmailLoginOtp(challenge()); + assertThat(challenge.hasError()).isFalse(); + assertThat(challenge.getAccepted()).isTrue(); + assertAuthenticated(stub.verifyEmailLoginOtp(verification())); + + verify(owner).authenticateForGameplay(DEMO_EMAIL, "password"); + verify(owner).requestEmailLoginOtp(DEMO_EMAIL); + verify(owner).verifyEmailLoginOtp(DEMO_EMAIL, "123456"); + verifyNoMoreInteractions(owner); + } + } + + @Test + void exactEntityCertificateAuthenticatesOnlyDemoFixtureAndNeverAuthorizesOtp() throws Exception { + AccountService owner = credentialOwner(ENTITY_URI); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "entity")) { + var stub = client.stub(); + assertAuthenticated(stub.authenticate(authentication(DEMO_EMAIL))); + assertOtpDenied(stub); + + verify(owner).authenticateForGameplay(DEMO_EMAIL, "password"); + verifyNoMoreInteractions(owner); + } + } + + @ParameterizedTest + @MethodSource("unavailableFixtureSettings") + void entityCertificateCannotBypassReceivingFlagOrProfileGates(boolean enabled, String[] profiles) + throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, enabled, profiles)); + ClientTransport client = newClient(server.port(), "entity")) { + assertAllDenied(client.stub(), authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + private static Stream unavailableFixtureSettings() { + return Stream.of( + Arguments.of(false, new String[] {"local-fixture"}), + Arguments.of(true, new String[] {}), + Arguments.of(true, new String[] {"prod"}), + Arguments.of(true, new String[] {"local-fixture", "prod"})); + } + + @Test + void defaultConstructorDoesNotAuthorizeEntityFixture() throws Exception { + AccountService owner = mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), owner, null, NAMESPACE); + try (TransportServer server = startServer(service); + ClientTransport client = newClient(server.port(), "entity")) { + assertAllDenied(client.stub(), authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + @Test + void trustedWrongWorkloadAndNamespaceCertificatesAreDeniedBeforeAccountInvocation() + throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture"))) { + for (String alias : List.of("world", "other-game-session", "other-entity")) { + try (ClientTransport client = newClient(server.port(), alias)) { + var response = client.stub().authenticate(AuthenticateRequest.getDefaultInstance()); + assertAuthenticationDenied(response); + assertThat(response.getError().getMessage()) + .isEqualTo( + "Verified Game Session or local-fixture Entity Management workload identity is required"); + assertOtpDenied(client.stub()); + } + } + verifyNoInteractions(owner); + } + } + + @Test + void entityCertificateCannotAuthenticateAnotherEmail() throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "entity")) { + assertAuthenticationDenied(client.stub().authenticate(authentication("other@example.com"))); + verifyNoInteractions(owner); + } + } + + @Test + void callerSuppliedPeerHeadersCannotReplaceWrongWorkloadCertificate() throws Exception { + AccountService owner = mock(AccountService.class); + Metadata spoofed = new Metadata(); + for (String header : List.of("x-peer-identity", "x-spiffe-id", "x-workload-identity")) { + spoofed.put(Metadata.Key.of(header, Metadata.ASCII_STRING_MARSHALLER), GAME_SESSION_URI); + } + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "world")) { + var stub = client.stub().withInterceptors(MetadataUtils.newAttachHeadersInterceptor(spoofed)); + assertAllDenied(stub, authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + @Test + void missingClientCertificateFailsHandshakeWithoutAccountInvocation() throws Exception { + AccountService owner = mock(AccountService.class); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + // Reuse the fixture's CA projection without supplying its client certificate or key. + var issued = pki.clientProperties(temporaryDirectory, pki.identity("game-session")); + tls.setCaCert(issued.getCaCert()); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), tls)) { + assertThatThrownBy(() -> client.stub().authenticate(authentication(DEMO_EMAIL))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + verifyNoInteractions(owner); + } + } + + private static AccountService credentialOwner(String expectedPeerUri) { + AccountService owner = mock(AccountService.class); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return new AuthenticationResult(ACCOUNT_UUID, "test-owner-token"); + }) + .when(owner) + .authenticateForGameplay(DEMO_EMAIL, "password"); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return new AuthenticationResult(ACCOUNT_UUID, "test-owner-token"); + }) + .when(owner) + .verifyEmailLoginOtp(DEMO_EMAIL, "123456"); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return null; + }) + .when(owner) + .requestEmailLoginOtp(DEMO_EMAIL); + return owner; + } + + private static AccountGrpcService fixtureService( + AccountService owner, boolean enabled, String... profiles) { + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profiles); + return new AccountGrpcService( + mock(PingService.class), owner, null, NAMESPACE, environment, enabled, DEMO_EMAIL); + } + + private static AuthenticateRequest authentication(String email) { + return AuthenticateRequest.newBuilder().setEmail(email).setPassword("password").build(); + } + + private static RequestEmailLoginOtpRequest challenge() { + return RequestEmailLoginOtpRequest.newBuilder().setEmail(DEMO_EMAIL).build(); + } + + private static VerifyEmailLoginOtpRequest verification() { + return VerifyEmailLoginOtpRequest.newBuilder().setEmail(DEMO_EMAIL).setCode("123456").build(); + } + + private static void assertAuthenticated(AuthenticateResponse response) { + assertThat(response.hasError()).isFalse(); + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getAuthToken()).isEqualTo("test-owner-token"); + } + + private static void assertAuthenticationDenied(AuthenticateResponse response) { + assertThat(response.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(response.getAccountId()).isEmpty(); + assertThat(response.getAuthToken()).isEmpty(); + } + + private static void assertOtpDenied(AccountServiceGrpc.AccountServiceBlockingStub stub) { + var challenge = stub.requestEmailLoginOtp(RequestEmailLoginOtpRequest.getDefaultInstance()); + assertThat(challenge.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(challenge.getAccepted()).isFalse(); + assertAuthenticationDenied( + stub.verifyEmailLoginOtp(VerifyEmailLoginOtpRequest.getDefaultInstance())); + } + + private static void assertAllDenied( + AccountServiceGrpc.AccountServiceBlockingStub stub, AuthenticateRequest request) { + assertAuthenticationDenied(stub.authenticate(request)); + assertOtpDenied(stub); + } + + private static TransportServer startServer(AccountGrpcService service) throws Exception { + var identity = pki.identity("account"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server); + } + + private static ClientTransport newClient(int port, String alias) throws Exception { + return newClient(port, pki.clientProperties(temporaryDirectory, pki.identity(alias))); + } + + private static ClientTransport newClient(int port, CommonGrpcClientProperties tls) + throws Exception { + return new ClientTransport( + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false)); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account credential server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private AccountServiceGrpc.AccountServiceBlockingStub stub() { + return AccountServiceGrpc.newBlockingStub(channel).withDeadlineAfter(5, TimeUnit.SECONDS); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account credential client did not terminate"); + } + } + } +} 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 3d69ec90e0..10d8482cf3 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 @@ -3,10 +3,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; @@ -67,10 +69,12 @@ import org.junit.jupiter.api.AfterEach; 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.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.mock.env.MockEnvironment; import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { @@ -670,23 +674,30 @@ 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()); @@ -700,15 +711,19 @@ void authenticateConvertsIllegalStateToBoundedAuthorityUnavailableError() { .thenThrow(new IllegalStateException("private provenance detail")); SimpleMeterRegistry registry = new SimpleMeterRegistry(); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, registry, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -726,15 +741,19 @@ void authenticatePreservesAccountOwnerUnavailableAsApplicationError() { .thenThrow( new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals("Account authority is unavailable", observer.response().getError().getMessage()); @@ -750,15 +769,19 @@ void verifyEmailLoginOtpPreservesAccountOwnerUnavailableAsApplicationError() { .thenThrow( new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + new AccountGrpcService( + Mockito.mock(PingService.class), 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)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -772,23 +795,27 @@ void verifyEmailLoginOtpPreservesAccountOwnerUnavailableAsApplicationError() { 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()); @@ -799,11 +826,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()); @@ -822,26 +853,30 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { .thenReturn( new net.firedevops.firemud.accountservice.dto.AuthenticationResult( ACCOUNT_UUID, "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(ACCOUNT_UUID, ref.get().getAccountId()); @@ -856,15 +891,19 @@ void authenticateReturnsCanonicalUuid() { .thenReturn( new net.firedevops.firemud.accountservice.dto.AuthenticationResult( ACCOUNT_UUID, "jwt")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals("jwt", observer.response().getAuthToken()); @@ -879,15 +918,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( @@ -903,15 +946,19 @@ void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() .thenThrow(new IllegalStateException("private provenance detail")); SimpleMeterRegistry registry = new SimpleMeterRegistry(); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, registry, 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)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -922,6 +969,243 @@ void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); } + @Test + void credentialMethodsRejectMissingAndWrongPeersBeforePayloadAccess() { + for (GrpcPeerIdentity peer : + java.util.Arrays.asList( + null, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/unknown-service").orElse(null), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/spring-cloud-gateway") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/game-session-service") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/entity-management-service") + .orElseThrow())) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + localDemoService(owner, true, "demo@example.com", "local-fixture"); + withPeer(peer, () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void credentialMethodsRejectBlankReceivingNamespace(String namespace) { + AccountService owner = Mockito.mock(AccountService.class); + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles("local-fixture"); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), + owner, + null, + namespace, + environment, + true, + "demo@example.com"); + withPeer(GAME_SESSION_PEER, () -> assertCredentialMethodsDeniedBeforePayload(service)); + withPeer(entityPeer(), () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + + @Test + void defaultConstructorDoesNotAuthorizeEntityDemoFixture() { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + withPeer(entityPeer(), () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + + private static void assertCredentialMethodsDeniedBeforePayload(AccountGrpcService service) { + RecordingObserver authenticate = new RecordingObserver<>(); + RecordingObserver request = new RecordingObserver<>(); + RecordingObserver verify = new RecordingObserver<>(); + service.authenticate(null, authenticate); + service.requestEmailLoginOtp(null, request); + service.verifyEmailLoginOtp(null, verify); + assertEquals("PERMISSION_DENIED", authenticate.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", request.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verify.response().getError().getCode()); + assertTrue(authenticate.response().getAuthToken().isEmpty()); + assertTrue(authenticate.response().getAccountId().isEmpty()); + assertFalse(request.response().getAccepted()); + assertTrue(verify.response().getAuthToken().isEmpty()); + assertTrue(verify.response().getAccountId().isEmpty()); + for (RecordingObserver observer : List.of(authenticate, request, verify)) { + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + } + } + + @ParameterizedTest + @MethodSource("deniedLocalDemoAuthenticationSettings") + void entityDemoAuthenticationRequiresEveryReceivingFixtureGate( + boolean enabled, String[] profiles, String email) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = localDemoService(owner, enabled, "demo@example.com", profiles); + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> + service.authenticate( + AuthenticateRequest.newBuilder().setEmail(email).setPassword("password").build(), + observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.response().getAuthToken().isEmpty()); + assertTrue(observer.response().getAccountId().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(owner); + } + + private static Stream deniedLocalDemoAuthenticationSettings() { + return Stream.of( + Arguments.of(false, new String[] {"local-fixture"}, "demo@example.com"), + Arguments.of(true, new String[] {}, "demo@example.com"), + Arguments.of(true, new String[] {"prod"}, "demo@example.com"), + Arguments.of(true, new String[] {"local-fixture", "prod"}, "demo@example.com"), + Arguments.of(true, new String[] {"local-fixture"}, "other@example.com"), + Arguments.of(true, new String[] {"local-fixture"}, " ")); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void enabledLocalFixtureRequiresConfiguredDemoIdentity(String email) { + AccountService owner = Mockito.mock(AccountService.class); + assertThrows( + IllegalArgumentException.class, + () -> localDemoService(owner, true, email, "local-fixture")); + Mockito.verifyNoInteractions(owner); + } + + @Test + void gameSessionAuthenticationRemainsAvailableWithProductionFixtureExclusion() { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.authenticateForGameplay("player@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + AccountGrpcService service = + localDemoService(owner, true, "demo@example.com", "local-fixture", "prod"); + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("player@example.com") + .setPassword("password") + .build(), + observer)); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertFalse(observer.response().hasError()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(owner).authenticateForGameplay("player@example.com", "password"); + Mockito.verifyNoMoreInteractions(owner); + } + + @Test + void entityDemoFixturePreservesCredentialVerificationAndCanonicalUuid() { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.authenticateForGameplay("demo@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + Mockito.when(owner.authenticateForGameplay("demo@example.com", "bad")) + .thenThrow( + new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); + AccountGrpcService service = + localDemoService(owner, true, " DEMO@EXAMPLE.COM ", "local-fixture"); + RecordingObserver success = new RecordingObserver<>(); + RecordingObserver failure = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> { + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + success); + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("bad") + .build(), + failure); + }); + assertEquals(ACCOUNT_UUID, success.response().getAccountId()); + assertEquals("jwt", success.response().getAuthToken()); + assertFalse(success.response().hasError()); + assertEquals( + AuthenticationErrorCodes.INVALID_CREDENTIALS, failure.response().getError().getCode()); + assertTrue(failure.response().getAuthToken().isEmpty()); + assertTrue(failure.response().getAccountId().isEmpty()); + assertTrue(success.completed()); + assertTrue(failure.completed()); + assertFalse(success.receivedTransportError()); + assertFalse(failure.receivedTransportError()); + Mockito.verify(owner).authenticateForGameplay("demo@example.com", "password"); + Mockito.verify(owner).authenticateForGameplay("demo@example.com", "bad"); + Mockito.verifyNoMoreInteractions(owner); + } + + @Test + void enabledEntityDemoFixtureNeverAuthorizesOtpMethods() { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = localDemoService(owner, true, "demo@example.com", "local-fixture"); + RecordingObserver request = new RecordingObserver<>(); + RecordingObserver verify = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> { + service.requestEmailLoginOtp(null, request); + service.verifyEmailLoginOtp(null, verify); + }); + assertEquals("PERMISSION_DENIED", request.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verify.response().getError().getCode()); + assertFalse(request.response().getAccepted()); + assertTrue(verify.response().getAuthToken().isEmpty()); + assertTrue(verify.response().getAccountId().isEmpty()); + assertTrue(request.completed()); + assertTrue(verify.completed()); + assertFalse(request.receivedTransportError()); + assertFalse(verify.receivedTransportError()); + assertEquals(1, request.nextCalls); + assertEquals(1, request.completedCalls); + assertEquals(1, verify.nextCalls); + assertEquals(1, verify.completedCalls); + Mockito.verifyNoInteractions(owner); + } + + private static GrpcPeerIdentity entityPeer() { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/entity-management-service") + .orElseThrow(); + } + + private static AccountGrpcService localDemoService( + AccountService owner, boolean enabled, String email, String... profiles) { + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profiles); + return new AccountGrpcService( + Mockito.mock(PingService.class), + owner, + null, + WORKLOAD_NAMESPACE, + environment, + enabled, + email); + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -2471,136 +2755,73 @@ public void onCompleted() {} } @Test - void exportAccountErrorReturnsDetail() { + void exportAccountDeniesCanonicalSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new IllegalArgumentException("missing")); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = new FailureObserver<>(); - AtomicReference ref = new AtomicReference<>(); service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), - new StreamObserver() { - @Override - public void onNext(ExportAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); - assertNotNull(ref.get()); - assertEquals("NOT_FOUND", ref.get().getError().getCode()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportAccountPreservesUnavailableOwnerProjectionResponse() { + void exportAccountDeniesAbsentSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - String message = "Account owner projection is unavailable"; - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); - AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = new FailureObserver<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + service.exportAccount(ExportAccountRequest.getDefaultInstance(), observer); - assertEquals(1, observer.nextCalls); - assertEquals(0, observer.receivedTransportError() ? 1 : 0); - assertEquals(1, observer.completedCalls); - assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); - assertEquals(message, observer.response().getError().getMessage()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportTenantDataPreservesUnavailableOwnerProjectionResponse() { + void exportTenantDataDeniesCanonicalRequestBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - String message = "Account owner projection is unavailable"; - Mockito.when(accountService.exportTenantData(1L, 2L)) - .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportTenantData( ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), observer); - assertEquals(1, observer.nextCalls); - assertEquals(0, observer.receivedTransportError() ? 1 : 0); - assertEquals(1, observer.completedCalls); - assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); - assertEquals(message, observer.response().getError().getMessage()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportAccountRejectsZeroAccountIdBeforeLookup() { + void exportAccountDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = new FailureObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(ExportAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + service.exportAccount(ExportAccountRequest.newBuilder().setAccountId("0").build(), observer); - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportTenantDataRejectsZeroTenantIdBeforeLookup() { + void exportTenantDataDeniesMalformedRequestBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - AtomicReference ref = new AtomicReference<>(); + FailureObserver observer = new FailureObserver<>(); service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(ExportTenantDataResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), observer); - @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(accountService); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test @@ -2663,15 +2884,13 @@ public void onCompleted() {} } @Test - void linkExternalAccountSuccess() { + void linkExternalAccountDeniesCanonicalSelectorsBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("1") @@ -2679,31 +2898,20 @@ void linkExternalAccountSuccess() { .setProvider("google") .setExternalId("abc") .build(), - new StreamObserver() { - @Override - public void onNext(net.firedevops.firemud.account.v1.LinkExternalAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void linkExternalAccountRejectsZeroTenantIdBeforeLink() { + void linkExternalAccountDeniesMalformedSelectorsBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("0") @@ -2711,91 +2919,54 @@ void linkExternalAccountRejectsZeroTenantIdBeforeLink() { .setProvider("google") .setExternalId("abc") .build(), - new StreamObserver() { - @Override - public void onNext(net.firedevops.firemud.account.v1.LinkExternalAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { + void requestEmailVerificationDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() .setAccountId("0") .build(), - new StreamObserver() { - @Override - public void onNext( - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void exportAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); - RecordingObserver observer = new RecordingObserver<>(); + @Test + void exportAccountDeniesAbsentRequestBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = new FailureObserver<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + service.exportAccount(null, observer); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).exportAccountData(Mockito.anyLong()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void exportTenantDataSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + @Test + void exportTenantDataDeniesAbsentSelectorsBeforeOwnerLookup() { + AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(Mockito.mock(PingService.class), accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); - service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), - observer); + service.exportTenantData(ExportTenantDataRequest.getDefaultInstance(), observer); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()) - .exportTenantData(Mockito.anyLong(), Mockito.anyLong()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService); } @ParameterizedTest @@ -2816,38 +2987,29 @@ void deleteAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failu Mockito.verify(accountService, Mockito.never()).deleteAccount(Mockito.anyLong()); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void linkExternalAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); - RecordingObserver observer = - new RecordingObserver<>(); + @Test + void linkExternalAccountDeniesAbsentSelectorsBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); service.linkExternalAccount( - net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() - .setTenantId("1") - .setAccountId(ACCOUNT_UUID) - .setProvider("google") - .setExternalId("external-1") - .build(), + net.firedevops.firemud.account.v1.LinkExternalAccountRequest.getDefaultInstance(), observer); - assertFalse(observer.response().getSuccess()); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).linkExternalAccount(Mockito.any()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void requestEmailVerificationSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); - RecordingObserver observer = - new RecordingObserver<>(); + @Test + void requestEmailVerificationDeniesCanonicalSelectorBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() @@ -2855,10 +3017,24 @@ void requestEmailVerificationSanitizesUnavailableAccountUuidReadback(RuntimeExce .build(), observer); - assertFalse(observer.response().getSuccess()); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).requestEmailVerification(Mockito.anyLong()); + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); + } + + @Test + void requestEmailVerificationDeniesAbsentSelectorBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + FailureObserver observer = + new FailureObserver<>(); + + service.requestEmailVerification( + net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.getDefaultInstance(), + observer); + + observer.assertUnconfiguredCallerRefusal(); + Mockito.verifyNoInteractions(accountService, pingService); } @Test @@ -2889,6 +3065,50 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); } + private static final class FailureObserver implements StreamObserver { + private Status transportStatus; + private com.google.rpc.Status rpcStatus; + private int nextCalls; + private int errorCalls; + private int completedCalls; + + @Override + public void onNext(T value) { + nextCalls++; + } + + @Override + public void onError(Throwable throwable) { + transportStatus = Status.fromThrowable(throwable); + rpcStatus = StatusProto.fromThrowable(throwable); + errorCalls++; + } + + @Override + public void onCompleted() { + completedCalls++; + } + + private void assertUnconfiguredCallerRefusal() { + assertEquals(0, nextCalls); + assertEquals(0, completedCalls); + assertEquals(1, errorCalls); + assertNotNull(transportStatus); + assertEquals(Status.Code.FAILED_PRECONDITION, transportStatus.getCode()); + assertNotNull(rpcStatus); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), rpcStatus.getCode()); + assertEquals("No authorized internal caller is configured", rpcStatus.getMessage()); + assertEquals(1, rpcStatus.getDetailsCount()); + assertEquals( + com.google.protobuf.Any.pack( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("No authorized internal caller is configured") + .build()), + rpcStatus.getDetails(0)); + } + } + private static final class RecordingObserver implements StreamObserver { private T response; private boolean receivedTransportError; 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 8993441a4f..50849be523 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 @@ -6316,17 +6316,122 @@ void requestEmailVerificationByEmailContainsDeliveryFailureAfterSavingToken() { } @Test - void verifyEmailSetsFlag() { + void verifyEmailClaimsTokenBeforeSavingOnlyTheFreshLockedAccount() { + EmailVerificationToken token = emailVerificationToken(); Account account = new Account(); - EmailVerificationToken token = new EmailVerificationToken(); - token.setAccount(account); - token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); - when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + account.setId(1L); + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(1L); + account.setUsername("current-name"); + account.setEmail("current@example.com"); + account.setPasswordHash("current-password"); + account.setRole("player"); + account.setLoginAuthModes("PASSWORD"); + Account expected = new Account(); + org.springframework.beans.BeanUtils.copyProperties(account, expected); + expected.setEmailVerified(true); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(account)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any())) + .thenReturn(true); service.verifyEmail(new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok")); - assertTrue(account.isEmailVerified()); - org.mockito.Mockito.verify(emailVerificationTokenRepository).delete(token); + assertEquals(expected, account); + assertFalse(token.getAccount().isEmailVerified()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order.verify(emailVerificationTokenRepository).findByToken("tok"); + order.verify(accountRepository).findByIdForUpdate(1L); + order + .verify(emailVerificationTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any()); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + } + + @Test + void verifyEmailRejectsLostOrChangedTokenClaimBeforeAccountMutation() { + EmailVerificationToken token = emailVerificationToken(); + Account current = new Account(); + current.setId(1L); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(current)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any())) + .thenReturn(false); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertFalse(current.isEmailVerified()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void verifyEmailRejectsExpiredAndExactlyExpiringTokenAfterAccountLock(boolean equality) { + EmailVerificationToken token = emailVerificationToken(); + java.time.LocalDateTime now = java.time.LocalDateTime.of(2026, 11, 1, 12, 0); + token.setExpiresAt(equality ? now : now.minusNanos(1)); + Account current = new Account(); + current.setId(1L); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(current)); + + try (org.mockito.MockedStatic clock = + org.mockito.Mockito.mockStatic( + java.time.LocalDateTime.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + clock.when(java.time.LocalDateTime::now).thenReturn(now); + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + } + + assertFalse(current.isEmailVerified()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order.verify(emailVerificationTokenRepository).findByToken("tok"); + order.verify(accountRepository).findByIdForUpdate(1L); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + + @Test + void verifyEmailRejectsMalformedTokenOwnerBeforeLockOrMutation() { + EmailVerificationToken token = emailVerificationToken(); + token.getAccount().setId(null); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + } + + private EmailVerificationToken emailVerificationToken() { + Account locator = new Account(); + locator.setId(1L); + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setToken("tok"); + token.setAccount(locator); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + return token; } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java new file mode 100644 index 0000000000..a450ac7b7a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.protobuf.StatusProto; +import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AddCurrencyRequest; +import net.firedevops.firemud.account.v1.ExportAccountRequest; +import net.firedevops.firemud.account.v1.ExportTenantDataRequest; +import net.firedevops.firemud.account.v1.GetBalanceRequest; +import net.firedevops.firemud.account.v1.LinkExternalAccountRequest; +import net.firedevops.firemud.account.v1.RequestEmailVerificationRequest; +import net.firedevops.firemud.account.v1.SpendCurrencyRequest; +import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +import net.firedevops.firemud.common.grpc.MetricsInterceptor; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +/** Transport-only loopback proof; workload TLS and authorization belong to the peer fixtures. */ +class DeferredAccountGrpcTransportTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String CALLER_UNAVAILABLE = "No authorized internal caller is configured"; + + @Test + void allSevenDeferredAdaptersReturnNonOkDetailsWithoutOwnerAccessOnRepeatedCalls() + throws Exception { + AccountService owner = mock(AccountService.class); + PingService ping = mock(PingService.class); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + registry.config().commonTags("service", "account-service"); + try (TransportServer server = startServer(owner, ping, registry); + ClientTransport client = + new ClientTransport( + NettyChannelBuilder.forAddress("127.0.0.1", server.port()) + .usePlaintext() + .build())) { + var account = AccountServiceGrpc.newBlockingStub(client.channel()); + var currency = VirtualCurrencyServiceGrpc.newBlockingStub(client.channel()); + List calls = + List.of( + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getBalance( + GetBalanceRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .build()), + "GetBalance is unavailable"), + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .addCurrency( + AddCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(10) + .build()), + "AddCurrency is unavailable"), + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .spendCurrency( + SpendCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(5) + .build()), + "SpendCurrency is unavailable"), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .exportAccount( + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_ID).build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .exportTenantData( + ExportTenantDataRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .linkExternalAccount( + LinkExternalAccountRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setProvider("example") + .setExternalId("untrusted-subject") + .build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .requestEmailVerification( + RequestEmailVerificationRequest.newBuilder() + .setAccountId(ACCOUNT_ID) + .build()), + CALLER_UNAVAILABLE)); + + int refusedCalls = 0; + for (int attempt = 0; attempt < 2; attempt++) { + for (Refusal call : calls) { + assertRefused(call); + refusedCalls++; + verifyNoInteractions(owner, ping); + assertEquals( + (double) refusedCalls, + registry + .get("grpc.app_error") + .tags("service", "account-service", "code", "FAILED_PRECONDITION") + .counter() + .count()); + } + } + List errorMeters = + registry.getMeters().stream() + .filter(meter -> meter.getId().getName().equals("grpc.app_error")) + .toList(); + assertEquals(1, errorMeters.size()); + assertEquals( + List.of("code", "service"), + errorMeters.get(0).getId().getTags().stream().map(tag -> tag.getKey()).toList()); + } + } finally { + registry.close(); + } + } + + private static void assertRefused(Refusal call) throws Exception { + StatusRuntimeException error = assertThrows(StatusRuntimeException.class, call.invoke()::run); + assertEquals(Status.Code.FAILED_PRECONDITION, error.getStatus().getCode()); + assertEquals(call.message(), error.getStatus().getDescription()); + com.google.rpc.Status status = StatusProto.fromThrowable(error); + assertNotNull(status); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), status.getCode()); + assertEquals(call.message(), status.getMessage()); + assertEquals(1, status.getDetailsCount()); + assertEquals( + ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(call.message()).build(), + status.getDetails(0).unpack(ErrorDetail.class)); + } + + private static TransportServer startServer( + AccountService owner, PingService ping, SimpleMeterRegistry registry) throws Exception { + return new TransportServer( + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .intercept(new MetricsInterceptor(registry)) + .addService(new AccountGrpcService(ping, owner, registry)) + .addService(new VirtualCurrencyGrpcService(registry)) + .build() + .start()); + } + + private record Refusal(Runnable invoke, String message) {} + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + if (!server.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback deferred Account server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback deferred Account client did not terminate"); + } + } + } +} 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..c8d24fc805 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 @@ -2,178 +2,157 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.concurrent.atomic.AtomicReference; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; import net.firedevops.firemud.account.v1.AddCurrencyRequest; import net.firedevops.firemud.account.v1.AddCurrencyResponse; import net.firedevops.firemud.account.v1.GetBalanceRequest; import net.firedevops.firemud.account.v1.GetBalanceResponse; import net.firedevops.firemud.account.v1.SpendCurrencyRequest; import net.firedevops.firemud.account.v1.SpendCurrencyResponse; -import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class VirtualCurrencyGrpcServiceTest { - @Test - void getBalanceReturnsResponse() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")).thenReturn(123L); - 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() {} - }); - - assertEquals(123L, ref.get().getBalance()); - } + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; @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()); + void getBalanceFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + GetBalanceRequest request = + GetBalanceRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> service.getBalance(request, observer), + "GetBalance is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } @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()); - Mockito.verifyNoInteractions(currencyService); + void addCurrencyFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + AddCurrencyRequest request = + AddCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(10) + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> service.addCurrency(request, observer), + "AddCurrency is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } @Test - void addCurrencyRejectsZeroAccountIdBeforeMutation() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.addCurrency( - AddCurrencyRequest.newBuilder() - .setTenantId("1") - .setAccountId("0") - .setCurrencyCode("GOLD") - .setAmount(10) - .build(), - new StreamObserver<>() { - @Override - public void onNext(AddCurrencyResponse 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("accountId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(currencyService); + void spendCurrencyFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + SpendCurrencyRequest request = + SpendCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(5) + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> + service.spendCurrency(request, observer), + "SpendCurrency is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } @Test - void spendCurrencyRejectsZeroTenantIdBeforeSpend() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.spendCurrency( - SpendCurrencyRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setCurrencyCode("GOLD") - .setAmount(5) - .build(), - new StreamObserver<>() { - @Override - public void onNext(SpendCurrencyResponse value) { - ref.set(value); - } + void nullRegistryStillRefusesAllOperationsBeforeInspectingRequests() throws Exception { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(null); + assertRepeatedRefusal( + (StreamObserver observer) -> service.getBalance(null, observer), + "GetBalance is unavailable"); + assertRepeatedRefusal( + (StreamObserver observer) -> service.addCurrency(null, observer), + "AddCurrency is unavailable"); + assertRepeatedRefusal( + (StreamObserver observer) -> service.spendCurrency(null, observer), + "SpendCurrency is unavailable"); + } - @Override - public void onError(Throwable t) {} + private static void assertRepeatedRefusal(Consumer> call, String message) + throws Exception { + for (int attempt = 0; attempt < 2; attempt++) { + RecordingObserver observer = new RecordingObserver<>(); + call.accept(observer); + assertTrue(observer.responses.isEmpty()); + assertEquals(0, observer.completions); + assertEquals(1, observer.errors.size()); + Throwable error = observer.errors.get(0); + assertTrue(error instanceof StatusRuntimeException); + assertEquals(Status.Code.FAILED_PRECONDITION, Status.fromThrowable(error).getCode()); + assertEquals(message, Status.fromThrowable(error).getDescription()); + com.google.rpc.Status status = StatusProto.fromThrowable(error); + assertNotNull(status); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), status.getCode()); + assertEquals(message, status.getMessage()); + assertEquals(1, status.getDetailsCount()); + assertEquals( + ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build(), + status.getDetails(0).unpack(ErrorDetail.class)); + } + } - @Override - public void onCompleted() {} - }); + private static void assertAppErrorCount(MeterRegistry registry, int expectedCount) { + assertEquals( + (double) expectedCount, + registry.get("grpc.app_error").tag("code", "FAILED_PRECONDITION").counter().count()); + assertEquals(1, registry.getMeters().size()); + assertEquals( + List.of("code"), + registry.getMeters().get(0).getId().getTags().stream().map(tag -> tag.getKey()).toList()); + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(currencyService); + private static final class RecordingObserver implements StreamObserver { + private final List responses = new ArrayList<>(); + private final List errors = new ArrayList<>(); + private int completions; + + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable error) { + errors.add(error); + } + + @Override + public void onCompleted() { + completions++; + } } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java index 1545213011..e5cad77f30 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.entitymanagement.client; import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import java.io.IOException; @@ -15,6 +17,8 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.JwtClaims; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Lazy; @@ -29,6 +33,10 @@ @Lazy public final class DemoAccountAuthenticationClient extends AbstractReloadingBlockingGrpcClient { + private static final Logger logger = + LoggerFactory.getLogger(DemoAccountAuthenticationClient.class); + private static final int MAX_AUTHENTICATION_ATTEMPTS = 3; + private static final long RETRY_DELAY_MILLIS = 250; private final String namespace; private final String email; private final String password; @@ -79,16 +87,43 @@ protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel } public UUID authenticateDemoOwner() { - var response = - requireInitializedStub("Demo Account client is not initialized") - .withDeadlineAfter(5, TimeUnit.SECONDS) - .authenticate( - AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build()); - if (response.hasError() || response.getAuthToken().isBlank()) { - throw new IllegalStateException("Account demo authentication is unavailable"); + var request = AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build(); + for (int attempt = 1; ; attempt++) { + if (Thread.currentThread().isInterrupted()) { + throw new IllegalStateException("Account demo authentication interrupted"); + } + try { + var response = + requireInitializedStub("Demo Account client is not initialized") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authenticate(request); + if (response.hasError() || response.getAuthToken().isBlank()) { + throw new IllegalStateException("Account demo authentication is unavailable"); + } + return UUID.fromString( + JwtClaims.requireCanonicalAccountUuid(response.getAccountId(), "accountId")); + } catch (StatusRuntimeException ex) { + Status.Code code = ex.getStatus().getCode(); + if (attempt >= MAX_AUTHENTICATION_ATTEMPTS + || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) { + throw ex; + } + if (Thread.currentThread().isInterrupted()) { + throw new IllegalStateException("Account demo authentication interrupted", ex); + } + logger.warn( + "Local demo Account authentication transport retry after attempt {}/{} status={}", + attempt, + MAX_AUTHENTICATION_ATTEMPTS, + code); + try { + Thread.sleep(RETRY_DELAY_MILLIS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Account demo authentication interrupted", interrupted); + } + } } - return UUID.fromString( - JwtClaims.requireCanonicalAccountUuid(response.getAccountId(), "accountId")); } @Override diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java index c03754c23f..167ce139ea 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java @@ -4,10 +4,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.*; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.lang.reflect.Field; import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -15,6 +18,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -49,6 +53,148 @@ void usesCredentialAuthenticationAndExactReturnedUuidWithoutNumericIdentity() th && request.getPassword().equals("swordfish"))); } + @Test + void retriesOnlyTransientTransportFailuresWithTheSameCredentialRequest() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + UUID owner = UUID.randomUUID(); + when(stub.authenticate(any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAccountId(owner.toString()) + .setAuthToken("ordinary-fixture-token") + .build()); + + assertThat(client(stub).authenticateDemoOwner()).isEqualTo(owner); + + var requests = ArgumentCaptor.forClass(AuthenticateRequest.class); + verify(stub, times(3)).authenticate(requests.capture()); + verify(stub, times(3)).withDeadlineAfter(5, TimeUnit.SECONDS); + assertThat(requests.getAllValues()) + .allSatisfy( + request -> { + assertThat(request).isSameAs(requests.getValue()); + assertThat(request.getEmail()).isEqualTo("demo@example.com"); + assertThat(request.getPassword()).isEqualTo("swordfish"); + }); + } + + @Test + void propagatesFinalTransientFailureAfterThreeCalls() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + var failure = Status.DEADLINE_EXCEEDED.asRuntimeException(); + when(stub.authenticate(any())).thenThrow(failure); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner).isSameAs(failure); + + verify(stub, times(3)).authenticate(any()); + } + + @Test + void refusesPermanentAuthorizationStatusesWithoutRetry() throws Exception { + for (Status status : new Status[] {Status.PERMISSION_DENIED, Status.UNAUTHENTICATED}) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + var failure = status.asRuntimeException(); + when(stub.authenticate(any())).thenThrow(failure); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(StatusRuntimeException.class) + .isSameAs(failure); + + verify(stub).authenticate(any()); + } + } + + @Test + void refusesCredentialErrorsAndMissingTokensWithoutRetry() throws Exception { + for (AuthenticateResponse response : + new AuthenticateResponse[] { + AuthenticateResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_INVALID_CREDENTIALS")) + .build(), + AuthenticateResponse.newBuilder().setAccountId(UUID.randomUUID().toString()).build() + }) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.authenticate(any())).thenReturn(response); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner).isInstanceOf(IllegalStateException.class); + + verify(stub).authenticate(any()); + } + } + + @Test + void interruptionStopsRetryAndPreservesInterruptWithoutReturningAnOwner() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.authenticate(any())) + .thenAnswer( + invocation -> { + Thread.currentThread().interrupt(); + throw Status.UNAVAILABLE.asRuntimeException(); + }); + var client = client(stub); + try { + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verify(stub).authenticate(any()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + verifyNoMoreInteractions(stub); + } finally { + Thread.interrupted(); + } + } + + @Test + void interruptedFixtureAuthenticationCannotReachOwnerMutation() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var characters = + mock(net.firedevops.firemud.entitymanagement.repository.CharacterRepository.class); + var items = mock(net.firedevops.firemud.entitymanagement.repository.ItemRepository.class); + var itemInstances = + mock(net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository.class); + var containers = + mock(net.firedevops.firemud.entitymanagement.repository.ContainerInstanceRepository.class); + var equipmentSlots = + mock( + net.firedevops.firemud.entitymanagement.repository.EquipmentSlotDefinitionRepository + .class); + var bodySlots = + mock( + net.firedevops.firemud.entitymanagement.repository.BodyLayoutSlotDefinitionRepository + .class); + var seeder = + new net.firedevops.firemud.entitymanagement.data.TestDataSeeder( + client(stub), characters, items, itemInstances, containers, equipmentSlots, bodySlots); + Thread.currentThread().interrupt(); + try { + assertThatThrownBy( + () -> seeder.run(new org.springframework.boot.DefaultApplicationArguments())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verifyNoInteractions( + stub, characters, items, itemInstances, containers, equipmentSlots, bodySlots); + } finally { + Thread.interrupted(); + } + } + @Test void refusesUnavailableMalformedNilAndNoncanonicalOwners() throws Exception { var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java new file mode 100644 index 0000000000..56bc1f1df5 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java @@ -0,0 +1,173 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.ServerCallStreamObserver; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** + * Physical deadline/retry proof with a controlled Account stub, not real credential-owner proof. + */ +class DemoAccountAuthenticationTransportTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID OWNER = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final AuthenticateRequest REQUEST = + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("controlled-fixture-password") + .build(); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createLoopbackCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "FireMUD demo authentication transport test CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec("entity", ENTITY_URI, false)); + } + + @Test + @Timeout(20) + void realDeadlineCancelsFirstCallAndRetryReturnsOnlyTheExactAccountOwner() throws Exception { + var requests = new CopyOnWriteArrayList(); + var peers = new CopyOnWriteArrayList(); + var firstCancelled = new CountDownLatch(1); + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void authenticate( + AuthenticateRequest request, StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + peers.add(peer == null ? "missing" : peer.uri()); + requests.add(request); + if (!ENTITY_URI.equals(peers.getLast()) || !REQUEST.equals(request)) { + observer.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (requests.size() == 1) { + // Leave the RPC open without blocking a server thread. The real client deadline + // must cancel it before the client can retry with a fresh five-second deadline. + ((ServerCallStreamObserver) observer) + .setOnCancelHandler(firstCancelled::countDown); + return; + } + observer.onNext( + AuthenticateResponse.newBuilder() + .setAccountId(OWNER.toString()) + .setAuthToken("controlled-fixture-token") + .build()); + observer.onCompleted(); + } + }; + var identity = pki.identity("account"); + try (var server = + new TransportServer( + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start()); + var channels = new CapturingChannelFactory()) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.server().getPort()); + try (var client = + new DemoAccountAuthenticationClient( + endpoints, + pki.clientProperties(directory, pki.identity("entity")), + channels, + NAMESPACE, + REQUEST.getEmail(), + REQUEST.getPassword())) { + client.init(); + + assertThat(client.authenticateDemoOwner()).isEqualTo(OWNER); + + assertThat(firstCancelled.await(2, TimeUnit.SECONDS)).isTrue(); + assertThat(requests).hasSize(2); + assertThat(peers).containsExactly(ENTITY_URI, ENTITY_URI); + assertThat(requests) + .allSatisfy( + request -> assertThat(request.toByteArray()).isEqualTo(REQUEST.toByteArray())); + } + } + } + + private record TransportServer(Server server) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + /** Records channels produced by the real factory so teardown also checks physical termination. */ + private static final class CapturingChannelFactory extends GrpcChannelFactory + implements AutoCloseable { + private final List channels = new CopyOnWriteArrayList<>(); + + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial tlsMaterial) + throws SSLException { + ManagedChannel channel = + super.buildChannel(target, defaultPort, properties, keepAlive, tlsMaterial); + channels.add(channel); + return channel; + } + + @Override + public void close() throws InterruptedException { + channels.forEach(ManagedChannel::shutdownNow); + for (ManagedChannel channel : channels) { + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } +}