diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 35317a751e..0a09c53a57 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,13 +54,15 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Explicit `JOIN` / `Join & Play` is not implemented. The current runtime membership response is the current four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with `membershipExists=false` may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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 sole target canonical operation is `JoinPublicProductionMembership`; the obsolete implicit membership-writer surface has been removed and is not a compatibility operation. Runtime convergence remains partial until explicit join is implemented with the target transaction, version, and durable audit/outbox evidence. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, 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. On connect-token cache misses and text `PLAY`, consumers currently proceed only when `membershipExists` and `gameplayAdmissionAllowed` are true; they do not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. Cached-success connect-token replay can return without fresh membership, entitlement, or pointer checks. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`; when membership exists but gameplay admission is false, connect-token issuance instead returns `CONNECT_TOKEN_REJECTED`. On checked paths, consumers therefore do 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, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle @@ -75,9 +77,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. -- `CreateAccount` – registers a new user and returns its `accountId` so internal services can establish their own sessions using the authentication flows described below. +- `CreateAccount` – registers a global Account identity and returns its `accountId`; it does not select a tenant or create membership/profile state. Registration also appends a platform-scoped audit outbox record in the Account transaction. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. +- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -102,13 +105,13 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `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. -- `IssueDirectTextConnectScope` – target-only internal Account API called only by authenticated Game Session mTLS during authenticated `REALMS`. The request carries the authenticated caller context in a typed `PlayerExecutionContext` plus the exact server-resolved `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion}` target, with exact `playtestLifecycleId` and positive `playtestStateGeneration` for every non-public target and both fields absent for a non-grant public-production target. Account validates that authenticated caller context separately from scope validation; the response returns an opaque short-lived `connectScopeId` and `connectScopeExpiresAt` bound to that complete evaluated target and exact `catalogRevision`/`pointerVersion` snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the explicit membership mutation. An unavailable Account or routing authority fails closed as `AUTH_UNAVAILABLE`; reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence is `ADMISSION_POINTER_UNAVAILABLE` before a valid scope comparison, while a valid scope whose exact `catalogRevision`/`pointerVersion` pair differs from the fresh authoritative snapshot returns `CONNECT_SCOPE_MISMATCH`. Fresh Account membership checks remain required separately at the applicable join, connect-token, and admission gates. Detailed scope semantics remain delegated to [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) and [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). +- `IssueDirectTextConnectScope` – implemented local internal Account RPC for issuing a direct-text connect scope. Game Session text `REALMS` dispatch to this RPC remains pending under #2898. The request carries authenticated caller context in typed `PlayerExecutionContext` plus the server-resolved target; Account validates caller context separately from the short-lived scope and returns an opaque `connectScopeId` bound to the evaluated routing snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Reachable missing or invalid routing evidence fails as `ADMISSION_POINTER_UNAVAILABLE`; a changed exact routing pair fails as `CONNECT_SCOPE_MISMATCH`; unavailable authority fails as `AUTH_UNAVAILABLE`. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). -- `JoinPublicProductionMembership` – target-only internal Account API for explicit open-enrollment `JOIN`; its canonical membership lifecycle and freshness contract are owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). The local route remains unimplemented, accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. +- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the response is the four-field admission shape documented above and does not expose lifecycle state or `membershipAuthorityGeneration`. **Target-only:** the response adds `membershipLifecycleState` and opaque `membershipAuthorityGeneration`, with the independent `membershipVersion`, from one fresh atomic Account membership snapshot. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `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. @@ -161,7 +164,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `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/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | -| `POST` | `/accounts` | Create a new user account | +| `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | | `GET` | `/accounts/{accountId}/exports/{exportId}` | **Target-state only.** Read durable portable-data export status, owner contribution state, and the versioned manifest using the same bounded subject/credential branch that initiated the job. | @@ -177,7 +180,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. | -| `POST` | `/internal/runtime/public-production-join` | Target Account-owned boundary for `JoinPublicProductionMembership`, used by explicit text-client `JOIN`; explicit JOIN behavior remains target-only and unimplemented, and no implicit membership-writer route is exposed | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** The local Account `JoinPublicProductionMembership` RPC implements explicit public-production membership creation; Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -188,8 +191,8 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current four-field membership response, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target-state only; not implemented at the current Account Service boundary.** Perform an explicit caller-bound `JoinPublicProductionMembership` / `Join & Play` operation for a discovery-selected public production realm using the exact `connectScopeId` and `requestId`. Account consumes the canonical JOIN digest contract defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative), verifies the scope's exact routing pair at membership commit, and retains only the local operation, membership, audit, and outbox consequences. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A stale pair or digest returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -232,7 +235,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | 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. | | 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, while explicit `/auth/bootstrap/join` remains the unimplemented target-state first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. 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. Account delivers the connect token only through 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. | +| 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 and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. 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. Account delivers the connect token only through 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. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 943f66281f..8fd7459c74 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -8,10 +8,65 @@ This document collects the Account Service operational behavior, readiness model - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented authentication/account slice and must fail when the service cannot safely satisfy new authentication traffic with its required local persistence/session infrastructure. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. +- Expired connect-scope cleanup requires PostgreSQL 16 or later because its deletion predicate uses `pg_input_is_valid`; local Docker Compose and Account integration-test containers use PostgreSQL 16. Keep the guarded delete predicate and do not add a pre-16 compatibility query. + +### V26 membership migration preflight + +Before applying [V26](../../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) to a populated target, take an authoritative read-only inventory of `account_tenant_membership` and its account/tenant identities. The migration retains each original `gameplay_admission_allowed` value in `account_legacy_membership_sources.original_gameplay_admission_allowed` as provenance; it is not current player intent or admission authority. V26 quarantines legacy memberships as `LEGACY_UNVERIFIED` and disables admission. Do not restore access from the retained boolean; membership authority and explicit reconciliation remain owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). + +Quiesce Account mutations and block new admission throughout inventory, migration, and readback so the preflight cannot race with another writer. If that quiescence cannot be proved, do not apply V26. Run these read-only queries before V26 and retain their output with the deployment record: + +```sql +SELECT COUNT(*) AS membership_rows, + COUNT(*) FILTER (WHERE gameplay_admission_allowed) AS legacy_admitting_rows +FROM account_tenant_membership; + +SELECT m.id AS membership_id, + m.account_id, + m.tenant_id, + a.tenant_id AS account_legacy_tenant_id, + m.gameplay_admission_allowed AS original_gameplay_admission_allowed +FROM account_tenant_membership AS m +LEFT JOIN accounts AS a ON a.id = m.account_id +ORDER BY m.tenant_id, m.account_id, m.id; +``` + +Treat rows as run-owned demo data only when an independent deployment/run record proves that ownership; do not infer it from identifiers, account names, or the legacy boolean. If any real memberships exist, keep deployment and gameplay traffic closed pending explicit owner-validated reconciliation. [TestDataSeeder](../../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java) is for explicitly run-owned local smoke data and must not be enabled in production. The current stage has no live target inventory or production reconciliation proof; this preflight is not activation approval. + +After V26 and before any explicitly enabled non-production demo seed, use read-only readback to verify each retained source has its quarantined membership row: + +```sql +SELECT COUNT(membership.id) AS membership_rows, + (SELECT COUNT(*) FROM account_legacy_membership_sources) AS source_rows, + COUNT(*) FILTER (WHERE legacy_source.membership_id IS NULL) AS rows_without_source, + COUNT(*) FILTER ( + WHERE membership.lifecycle_state <> 'LEGACY_UNVERIFIED' + OR membership.authority_provenance <> 'LEGACY_UNVERIFIED' + OR membership.gameplay_admission_allowed + ) AS rows_not_quarantined +FROM account_tenant_membership AS membership +LEFT JOIN account_legacy_membership_sources AS legacy_source + ON legacy_source.membership_id = membership.id; + +SELECT legacy_source.membership_id, + legacy_source.account_id, + legacy_source.tenant_id, + legacy_source.original_gameplay_admission_allowed, + legacy_source.matches_account_legacy_tenant, + legacy_source.disposition, + legacy_source.captured_at, + membership.lifecycle_state, + membership.authority_provenance, + membership.gameplay_admission_allowed +FROM account_legacy_membership_sources AS legacy_source +JOIN account_tenant_membership AS membership + ON membership.id = legacy_source.membership_id +ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.membership_id; +``` ## Saga Participation -The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. Global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits likewise use platform scope and omit `tenantId`. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current runtime:** Account persists the account, profile, and membership locally, then attempts the `CreateLogEvent` RPC post-commit on a best-effort basis. Logging failure is swallowed and does not roll back or compensate the committed creation. The owner-local outbox and corresponding proto/receiver implementation must be implemented and proved before mandatory audit delivery is claimed. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's delivery job sends the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The Logging & Admin receipt receiver, durable receipt persistence/deduplication, exact payload-digest validation, and readback are separate #2848 work and are not implemented in this Account core. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. @@ -19,6 +74,8 @@ The current `PurchaseWorkflowService` implementation for one-time payments and d Prometheus scrapes metrics from `/actuator/prometheus`. Service methods expose `account.*`, `payment.*`, `notification.*`, and `session.*` timers via `@Timed` annotations. OpenTelemetry spans are exported to the collector service so traces can be viewed in Jaeger. No additional configuration is required when running via `./gradlew bootRun` as the default properties target `http://otel-collector:4317`. +Expired connect-scope cleanup exposes `account.connect_scopes.cleanup.deleted` for deleted rows, `account.connect_scopes.cleanup.failure` for failed runs, the `account.connect_scopes.cleanup` timer, and `account.connect_scopes.cleanup.cap_saturation` for runs in which all five batches return the configured full batch size. The job can process at most five times the batch size per scheduled invocation. With fixed delay, the effective start-to-start period is the configured interval plus the prior run's execution time, so long runs reduce how often cleanup can run. Tune the batch size and interval against measured expired, unreferenced scope insertion load. Cap saturation signals cleanup pressure, not an exact backlog count. + ## Integration Test Notes The old disabled GHCR-based cross-service placeholder for Account Service was removed because it did not prove a meaningful current contract. The maintained local application smoke now lives under `src/test/java/integration` and should be treated as the canonical lightweight readiness check for this service. Higher-value cross-service behavior should be covered by targeted current-contract tests rather than by "other container exists" scaffolding. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 107d0b0c62..5eddf58fc7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,11 +16,13 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The live account-creation paths still require a caller-provided `tenantId` and create an admission-enabled `AccountTenantMembership` as part of account creation. Legacy Account migrations also default existing account/profile and billing rows to tenant `1` and backfill membership from that value. This conflicts with the canonical [global-registration and explicit `JoinPublicProductionMembership` flow](../../system-architecture-authentication.md#login-and-session-flow). This is a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. + +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only an absent membership may return non-actionable `JOIN_REQUIRED`, while a present membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. The current response cannot classify that membership as `INACTIVE`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -28,7 +30,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -The direct-text `REALMS`-to-`JOIN` scope handoff is also target-only and unimplemented. Account-local remaining work is to validate the authenticated `PlayerExecutionContext` separately from the short-lived target-bound scope, issue that scope during authenticated realm resolution, and validate its exact routing snapshot at `JoinPublicProductionMembership`; Game Session transport retention and server-generated join-attempt identity are defined by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +Account locally implements `IssueDirectTextConnectScope` for an authenticated caller and the exact Game Session-resolved public-production target from `REALMS`, validating its retained target snapshot and caller binding. Game Session does not yet wire this RPC into text `REALMS` or retain the returned scope in transport context. Account also implements the `JoinPublicProductionMembership` RPC/operation and local HTTP JOIN route, including retained-target and caller-binding validation; Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898. These local Account capabilities do not yet form an end-to-end direct-text `REALMS`-to-`JOIN` flow. Account request retries can resume a committed policy-independent intent across entitlement outages; after an uncertain second-transaction outcome, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -41,8 +43,8 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after exact receipt/readback or reconciliation; unavailable, timeout, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current runtime:** local writes commit first; Account then attempts `CreateLogEvent` post-commit on a best-effort basis, and logging failure is swallowed without compensating or rolling back creation. The current proto and receiver do not yet carry or enforce the target identity, envelope, digest, deduplication, readback, or Account workload authorization contract, so the durable outbox and mandatory receiver implementation remain open. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current runtime:** Account attempts `CreateLogEvent` after its local commit on a best-effort basis and swallows logging failure; that attempt is not delivery proof. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The Logging & Admin receipt receiver, durable deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipt handling are separate #2848 work and are not implemented in this Account core. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -50,7 +52,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - Telnet and other non-WebSocket text transports authenticate through the credential-bearing `LOGIN` flow described in [Authentication & Authorization](../../system-architecture-authentication.md) and do not carry public JWTs or gameplay connect tokens. First-party browser/mobile/server clients use the short-lived `player-bootstrap` profile for HTTPS bootstrap and an HttpOnly-cookie connect token for the WebSocket handshake. Explicitly classified non-first-party/public generic WebSocket clients have no current supported connect-token carrier; the dedicated issuance route, secure-storage response, and `X-Firemud-Connect-Token` handshake header remain target-only until their authorization-matrix, replay, signed-context, response, and carrier proofs are complete. The Game Session Service calls the internal `Authenticate` gRPC method (mTLS-protected) to verify credential-bearing login and obtain `game-session-account-delegation` JWTs for Account, while `/auth/login` remains a browser/control-plane endpoint. - Admin and creator UI authentication is initiated via the `/auth/login` HTTP endpoint, which issues `control-ui` JWTs used only for the exact control-plane audience described in the authentication and frontend architecture designs. - Owns credential brute-force defense and login abuse handling for every password and verified-email-code path. It combines trusted canonical source context with normalized account-candidate and coarse pressure buckets, applies graduated temporary throttles, and emits stable retry outcomes. These buckets are policy signals, not durable authority; any Cache/Rate-Limit Redis use must preserve one-to-one opaque subject isolation or explicitly declare a coarse heuristic, bounded cardinality, eviction/reset behavior, and outage mode under [ADR 0087](../../decisions/adr-0087-isolated-subject-rate-limits-with-explicit-loss-semantics.md). Ordinary failed attempts never transition the account to `security_locked`; that durable state requires evidence supporting a verified or high-confidence compromise assessment, explicit security policy, or audited operator action. Account is also the sole canonical resolver and publisher of the effective versioned security policy; callers do not merge deployment or tenant overrides or fall back to cached/default values, and an unavailable or contradictory policy resolution fails sensitive actions closed. Suspicious activity triggers notification emails and audit events as described in [Security Architecture](../../system-architecture-security.md#brute-force-defense-and-abuse-handling) and [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md). -- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account creation's cross-service audit handoff is target-state owner-local outbox work, not a compensated Saga step; the current post-commit best-effort behavior and its failure semantics are described above. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account registration and explicit JOIN audit handoffs use the owner-local outbox and are not compensated Saga steps. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). - Leverages the [Shared Libraries](../../system-architecture-shared-libraries.md) for common DTOs, logging interceptors, and Micrometer metrics. ## Data Model @@ -139,7 +141,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current runtime uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for absent membership on an eligible public-production target; a present membership with `gameplayAdmissionAllowed=false` is rejected as `CONNECT_TOKEN_REJECTED`. Text `PLAY` may still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. None of these paths creates or restores membership, and explicit `JOIN` remains unavailable. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current runtime uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for absent membership on an eligible public-production target; a present membership with `gameplayAdmissionAllowed=false` is rejected as `CONNECT_TOKEN_REJECTED`. Text `PLAY` may still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. None of these paths creates or restores membership. The Account-owned public-production `JOIN` writer is implemented locally; first-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. @@ -176,7 +178,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. Current generated proto, Account implementation, and runtime callers do not yet expose and prove every target field, including `membershipLifecycleState`, `authorityAvailability`, and the opaque generation; that remains implementation drift. +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, but current runtime callers do not enforce either field. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. @@ -199,14 +201,14 @@ Runtime caller contract: - Account delivers the current connect token only as `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is never returned in the response body or a response-header fallback. Browser/mobile clients and first-party non-browser clients with a protected cookie jar retain and use the cookie normally. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. -- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. Account receives trusted caller context and the exact Game Session-resolved target, validates the current catalog/pointer snapshot, and returns the opaque scope to Game Session for transport-local retention. This target producer path remains unimplemented. +- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. The Account `IssueDirectTextConnectScope` RPC is implemented locally: it receives trusted caller context and the exact Game Session-resolved target, validates the current catalog/pointer snapshot, and returns the opaque scope to Game Session. Game Session wiring from text `REALMS` and transport-local scope retention remain unimplemented, as does the subsequent text `JOIN` dispatch (#2898); the end-to-end producer flow and proof remain incomplete. - `connectScopeExpiresAt` bounds how long the discovery-issued selector may be reused as a convenience token. Once it expires, callers must rerun discovery instead of treating the selector as a durable realm handle. - Account Service must expose bootstrap-discovery endpoints that accept only the `player-bootstrap` token profile and return the canonical caller-visible worlds, realms, characters, and a canonical `connectScopeId` selector for each admissible realm target. - Account Service must use the authoritative realm-routing contract when issuing `/auth/connect-token` so connect-token scope is pinned to the tenant's current admissible instance for the selected realm instead of a caller-supplied guess. - `requestId` is the idempotency key for connect-token issuance. Retrying the same `(accountId, connectScopeId, requestId)` replays the same deterministic application failure directly while its retained failure envelope is available. A stored success returns the same token payload only after current authority and all applicable admission, registry, and issuance postconditions revalidate; failed revalidation returns the applicable canonical denial without reminting or mutating the committed issuance result. If the compact receipt still exists after its encrypted response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`, never remints or reconstructs a JWT, and is terminal for that original issuance attempt; callers must start a fresh authorized request under a new `requestId`. A changed digest remains `IDEMPOTENCY_CONFLICT`. The exact membership freshness baseline used for issuance is bound to that `connectScopeId` and `requestId`; it is immutable comparison evidence, not a duplicate request field. If Gateway may already have consumed the token, the caller must rediscover and use a new `requestId` rather than replaying the prior issuance key. - Existing caller-bound membership is mandatory for every target. For a selected publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. The current implementation provides only the bounded Session Service replay record, so durable database-backed failure replay remains an implementation gap. A private or playtest target additionally requires the current Account-owned realm-access grant; a grant never substitutes for membership or public onboarding. - - `JoinPublicProductionMembership` is the sole target canonical name for the authoritative explicit open-enrollment membership operation. Its target request preserves exactly `connectScopeId` and `requestId`; for direct text, Game Session supplies the retained scope and generates the high-entropy request ID server-side rather than accepting either value from the client. The internal boundary authenticates the exact Game Session mTLS workload and validates its typed caller-bound `PlayerExecutionContext`, including `accountId`, before using the scope. The scope binds the target and exact catalog/pointer pair, not the membership subject. Public player-bootstrap surfaces derive `accountId` from the authenticated caller and do not accept a caller-selected account ID. Account verifies the exact bound catalog/pointer pair at commit, separately from the fresh Account entitlement `allowPublicJoin` check. Connect-token issuance and public-production `PLAY` must require its result but never invoke it implicitly. Explicit `JOIN`/`Join & Play` remains target-only and unimplemented; no implicit membership writer is exposed by connect-token issuance or `PLAY`. + - The target membership-writer contract is `JoinPublicProductionMembership`; its canonical caller, scope, policy, and replay behavior is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Connect-token issuance and public-production `PLAY` require existing membership and never invoke the writer implicitly. The local Account RPC, digest, transaction, and recovery status are recorded under [Implementation Status](#implementation-status). - It is valid only for the default public production realm and only when the caller satisfies the public-production admission policy. - `requestId` is the attempt idempotency key and `connectScopeId` remains a required request field. Account uses the canonical JOIN digest preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). It persists the resulting digest with the verified caller/scope inputs and operation record. Retrying the same `{connectScopeId, requestId}` and digest returns the same membership result or deterministic application failure; a changed digest returns `IDEMPOTENCY_CONFLICT`, while a changed request ID is a distinct operation. - The resulting membership must be immediately visible to `GetTenantMembershipForRuntime`. @@ -268,8 +270,11 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. An existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only, and this response does not make JOIN available for that membership. Current text `PLAY` may still return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target before the fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. Explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. -- Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain target follow-through. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. An existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`; consumers do not yet enforce the emitted lifecycle state or authority generation, so that response is not classified as `INACTIVE`. Current text `PLAY` may still return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target before the fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. The Account-owned explicit public-production JOIN writer and operation controller, including the local `POST /auth/bootstrap/join` REST route, exist locally; its public Gateway exposure remains blocked by the explicit route guard pending production proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof, direct text-client end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. + +The current JOIN implementation re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). + +Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 15a1dc4990..2acb2050f8 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,7 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The current proto and receiver instead expose only the legacy `CreateLogEvent` shape and `AdminRoleGuard`; this is explicitly current drift pending the target convergence. +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The current proto now declares the target envelope and receipt fields, but the `CreateLogEvent` handler remains a fail-closed `AdminRoleGuard` placeholder that returns `UNAVAILABLE` to authorized callers without dispatch, `ReadLogEventReceipt` has no handler, and the target mTLS-only receiver, durable receipt/readback, and runtime proof remain unavailable as separate #2848 work. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index c956fb822e..442adf07a3 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The explicit join action and the required `membershipAuthorityGeneration` reread at connect-token issuance remain unimplemented/proof gaps. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`, and explicit `JOIN` remains unavailable. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result is a fail-closed, non-actionable denial while explicit `JOIN`/`Join & Play` is unimplemented; it must not be presented as proof that the target repair flow is available. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains target-only and individual bootstrap/connect-token endpoints remain partial implementation surfaces. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. Although the live producer now emits `membershipLifecycleState` and `membershipAuthorityGeneration` too, these consumers still use only the four fields above and do not enforce the complete atomic-freshness contract. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. Current consumers therefore cannot classify the returned membership as `INACTIVE`: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing lifecycle states. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently return `JOIN_REQUIRED`; an existing but non-admitting membership cannot be classified as `INACTIVE`. Current connect-token issuance returns `CONNECT_TOKEN_REJECTED` for an existing membership whose `gameplayAdmissionAllowed` value is false, preserving its Account-owned rejection mapping. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. The current `JOIN_REQUIRED` result remains a fail-closed `PLAY` denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. @@ -271,9 +271,31 @@ These modes are complementary: public browse remains available before authentica ``` The field names, `=`, line separators, and final newline are literal ASCII bytes. Values use the owning contract's canonical UTF-8 wire forms (including canonical decimal revisions and UTC RFC3339 timestamps), are not trimmed, case-folded, or Unicode-normalized, and may not contain `=` or a newline. `targetClass` is server-derived and not caller input. The bracket notation in the preimage illustration denotes conditional lines, not literal bytes: for `PUBLIC_PRODUCTION`, both lifecycle lines are omitted entirely, never encoded as empty, null, or sentinel values; for `NON_PUBLIC`, both are required, with a positive `playtestStateGeneration`. Account stores the digest with the scope record, including the immutable `evaluatedAt` value, and exact-compares it with the complete stored field set whenever the scope is consumed; a missing, extra, altered, or differently serialized field fails closed. This Account-owned scope-integrity evidence is distinct from the separately signed Gateway context and the JOIN idempotency digest. -- The canonical `JOIN` idempotency digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order: +- Before consulting entitlement authority, Account durably claims the stable `requestId` as `PENDING` with a policy-independent `joinIntentDigest/v1`. This immutable intent digest binds the request ID, authenticated account, verified caller binding, verified `connectScopeId` and scope snapshot digest, and the complete server-resolved target. It contains no entitlement availability, policy result, or entitlement version. The claim is committed before policy evaluation so an unavailable authority or an uncertain later transaction cannot erase evidence of the logical attempt. The intent digest is `SHA-256` over the UTF-8 bytes of the exact newline-delimited preimage below, including the final newline. Field names, `=`, separators, and the final newline are literal ASCII bytes; values use the canonical UTF-8 wire forms of the validated request and scope and may not contain `=` or a newline. A retry must match this intent exactly; a changed intent under the same request ID returns `IDEMPOTENCY_CONFLICT`. ```text + joinIntentDigestVersion=v1 + operationKind=JOIN + requestId= + accountId= + callerBinding= + connectScopeId= + scopeDigest= + tenantId= + worldSlug= + realmSlug= + realmId= + playableStateNamespaceId= + playableStateScope= + gameInstanceId= + catalogRevision= + pointerVersion= + ``` + + The canonical policy-bound `JOIN` request digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order. It is computed only after a fresh authoritative entitlement evaluation returns `AVAILABLE` with an exact `allowPublicJoin` result and positive `entitlementVersion`: + + ```text + joinDigestVersion=v1 operationKind=JOIN accountId= callerBinding= @@ -282,13 +304,17 @@ These modes are complementary: public browse remains available before authentica realmSlug= playableStateNamespaceId= playableStateScope= + gameInstanceId= connectScopeId= catalogRevision= pointerVersion= + entitlementAuthorityAvailability=AVAILABLE + allowPublicJoin= + entitlementVersion= ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. Account stores the resulting `requestDigest` with the `requestId`; an exact retry replays the stored outcome and a different digest returns `IDEMPOTENCY_CONFLICT`. -- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. +- Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. +- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery; for a retained `PENDING` operation, an expired scope terminally returns `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b2c5844a2f..5c47648bb6 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,8 +25,8 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the current adapter reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; the current adapter does not expose `membershipLifecycleState`, so the latter response cannot be classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Explicit `JOIN` remains unimplemented. -- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Account's explicit JOIN writer is implemented locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play` and durable unknown-outcome recovery remain incomplete. +- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes. Their seed entries are Account Service `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` and Account Service `GetTenantEntitlementsForRuntime`; the latter records the exact Game Session or World Management caller alternatives. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. @@ -215,7 +215,7 @@ For every first public-production text entry, the target command sequence is `LO | Game Session Service | `WORLDS` anonymous browse | `public` | Public-production catalog only; no account-specific membership, grant, or character information | | Game Session Service | `WORLDS` authenticated discovery | `pre_tenant_discovery` | No pre-existing tenant role is required. Tenant visibility is derived server-side from membership or public-production visibility plus entitlement state; global roles do not widen gameplay discovery | | Game Session Service | `REALMS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive branch from the authoritative realm mode: public production permits pre-membership discovery; private/playtest requires caller-bound `membershipLifecycleState=ACTIVE`, current membership authority generation/version, and the current Account-owned grant for the exact target. Private/playtest is never classified as public onboarding, never falls back to public discovery, and never uses a grant to repair membership. Hidden/unauthorized targets are omitted; explicit branch failures use `NON_PUBLIC_ENROLLMENT_REQUIRED`, `REALM_ACCESS_DENIED`, `WORLD_ACCESS_DENIED`, `ADMISSION_POINTER_UNAVAILABLE`, `REALM_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE`, or `AUTH_UNAVAILABLE` as applicable. | -| Game Session Service | `JOIN` | `public_production_onboarding` | **Target-only; not currently implemented.** Explicit caller-bound open-enrollment action for the current public production realm; Account commits durable membership plus audit/outbox idempotently | +| Game Session Service | `JOIN` | `public_production_onboarding` | Account's explicit `JoinPublicProductionMembership` writer is implemented locally and commits membership plus audit/outbox evidence idempotently. Game Session text `JOIN`/`Join & Play` dispatch to that writer remains unimplemented under #2898, so the text flow is unavailable. | | Game Session Service | `CHARS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Public discovery may lead to `JOIN_REQUIRED` for missing or `INACTIVE` membership; private/playtest requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. It applies the current `admission_pointer` check to the selected catalog realm, but does not apply `PLAY`'s exact-binding admission lease, binding fence, or binding-ownership gate; character discovery and creation do not require a selected character. Policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and unavailable or invalid authority uses the applicable unavailable/invalid-authority outcome. Missing or non-`ACTIVE` private/playtest membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, and character discovery is not membership repair. | | Game Session Service | `PLAY` | `gameplay_admission` | **Target:** requires an existing caller-bound membership plus any non-public realm grant, current entitlements, and the current admissible realm pointer; `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when the selected target is confirmed as public production and its joining policy denies entry, and only an admissible, publicly visible public-production target whose joining policy permits entry and whose membership is missing or `INACTIVE` returns `JOIN_REQUIRED`; `ACTIVE` membership does not require `JOIN`, and `PLAY` never creates or restores membership. `PLAY` alone performs the final gameplay-binding CAS. First-party `/ws/game/**` also enforces connect-context scope. Unavailable, ambiguous, stale, or otherwise invalid routing returns `ADMISSION_POINTER_UNAVAILABLE`; a deliberately closed realm returns `REALM_UNAVAILABLE`; entitlement authority outage returns `ENTITLEMENT_UNAVAILABLE`. | | Spring Cloud Gateway | `/ws/game/**` (connect-token bootstrap) | `gameplay_admission` | **Implemented but non-promotable until the named Gateway readiness evidence is complete:** carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. This is one canonical WebSocket entry point with mutually exclusive variants. The current `first_party_web` variant accepts exactly the protected cookie for first-party protected-cookie clients, including native or other nonbrowser clients using a cookie jar. The live `GameplayHandshakeFilter` rejects `X-Firemud-Connect-Token` on this public route with `CONNECT_TOKEN_REJECTED` and reason `unsupported_carrier_or_route`, without falling back to the cookie. A future explicitly classified `non_first_party_public` variant may use the header only after its dedicated matrix entry and issuance, replay, signed-context, response, and carrier proof exist; it cannot select or fall back to `first_party_web`. Gateway consumes exactly one supported carrier, strips it, atomically enforces single use using the dedicated replay record/fence, matches the signed connect scope to the request, and emits the signed connect context for Game Session. Non-`101` outcomes use the bounded `CONNECT_TOKEN_MISSING`, `CONNECT_TOKEN_EXPIRED`, `CONNECT_TOKEN_REPLAYED`, `CONNECT_SCOPE_MISMATCH`, `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, `CONNECT_TOKEN_REJECTED`, `POLICY_DENY`, `POLICY_PRESSURE`, `BACKEND_UNAVAILABLE`, `PROTOCOL_MISMATCH`, or `INTERNAL_ERROR` handshake classes. | @@ -225,10 +225,12 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; applies live realm visibility and runtime entitlement checks, with private/playtest additionally requiring caller-bound `ACTIVE` membership and the applicable Account-owned realm-access grant. Private/playtest is not public onboarding. | | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; this existing-character discovery operation declares `selected_character_requirement: none`, and its target binding and `connect_scope_match` check require the opaque server-issued `connectScopeId` to match the selected route target, alongside live membership, applicable realm-grant, entitlement, and admission-pointer checks. It creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | | Account Service | `POST /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | **Target; not currently routable or implemented.** Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Bootstrap-authenticated Account facade derives `accountId` from the authenticated caller subject, declares `selected_character_requirement: none`, and requires its target binding plus `connect_scope_match` check to match the opaque server-issued discovery `connectScopeId`; existing caller-bound membership, applicable realm visibility/grant, runtime entitlement, and admission-pointer checks precede the retained target delegation to internal Entity Management `CreateCharacter`. Character creation creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | -| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Target; not currently implemented.** Accepts only the caller-bound `player-bootstrap` profile, derives `accountId` from the authenticated subject, and its target binding plus `connect_scope_match` check require the opaque server-issued discovery `connectScopeId` to match the selected public-production target before creating membership atomically | +| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; `target_not_currently_routable` externally.** The explicit Gateway route guard blocks exposure, and the route is absent from publicOpenAPI. Accepts only caller-bound `player-bootstrap`, derives `accountId` from the authenticated subject, and requires the exact opaque server-issued discovery `connectScopeId` to match the selected public-production target. The local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [ADR 0025](./decisions/adr-0025-explicit-open-enrollment-membership.md). | | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | +| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current placeholder retains `AdminRoleGuard` denial ordering and returns `UNAVAILABLE` for authorized callers without dispatching or writing a receipt; the target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | +| Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | **Target-only; handler and proof unavailable.** The target uses the same exact Account Service mTLS-only caller boundary and no bearer token or operator role, then reads the receipt by the complete immutable envelope tuple. The current service has no read handler and returns gRPC `UNIMPLEMENTED`; receipt readback, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | | Logging & Admin | `POST /admission-pointers`, `POST /admission-pointers/cutover`, `POST /admission-pointers/version-upgrades` | `tenant_regular` operator ingress | **Target; not currently routable.** This is a target inventory row only: the public OpenAPI surface no longer exposes the admission-pointer open/close/cutover mutations, and the remaining controller/owner paths are implementation drift. The `GET` read/audit/proof-read routes remain live; the `POST` preparation operation is separately gated. Exact `control-ui` profile and current operator role are required for any future ingress. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Action schemas, shared `mutationDigest/v1` vectors, and Account authorization-reference issuance/redemption are required before external support; the global branch additionally requires target-only `privileged_control`. | | Game Session Service | `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `PrepareVersionUpgrade`, `ExecutePreparedVersionCutover` | `internal_workload` mirrored owner RPCs | **Target; not currently routable.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. These owner RPCs cannot be enabled until the corresponding action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption flow exist. | | Game Session Service | `StartSession` / `RestartSession` / `StopSession` | `internal_workload` operator RPCs | **Status: `target_not_currently_routable` as external operator support.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. The canonical external ingress is Logging & Admin; direct owner edge exposure is denied during migration. | @@ -242,7 +244,8 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `EnterPrivilegedControlWindow` | `account_scoped` | **Target; not currently implemented.** Exact `control-ui` profile plus recent ordinary reauthentication and independent TOTP; this route creates the bounded role-scoped window and does not require an existing elevation window | | Account Service | `IssueHumanOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus a forwarded `control-ui` token with its exact active Account issued-token registry record; Account rereads current account/token generation, operator roles, role-appropriate assurance, the applicable tenant or target-tenant generation, and required `privileged_control` predicate before issuing the bounded reference | | Account Service | `IssueAutomationOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus current versioned automation policy; no end-user JWT or user impersonation. The current branch is tenant-scoped only, binds the exact current tenant generation, and rejects global-role or `privileged_control` action families | -| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Target-only; not currently implemented.** Canonical operation is defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). The local route is called only by the exact Game Session mTLS workload with typed caller-bound player execution context, accepts no end-user token, and requires `verified_connectScopeId_exact_target`. Account revalidates the exact `connectScopeId`, `catalogRevision`, `pointerVersion`, and resolved target immediately before commit; silent retargeting is forbidden. The obsolete implicit membership writer is removed. | +| Account Service | `IssueDirectTextConnectScope` | `internal_workload` | **Implemented locally; end-to-end proof incomplete.** Exact Game Session mTLS and typed caller/target context are required; Account rereads the public-production target and current gameplay entitlement before retaining an opaque short-lived scope. The scope is not caller authority or a JOIN policy decision; see [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) | +| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; proof incomplete.** Account's explicit writer is the sole membership mutation path; the canonical contract and current transaction consequences are defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). Target-only membership-generation snapshot proof, unknown-outcome recovery/reconciliation, audit receipt/retention proof, PostgreSQL runtime proof, and direct-text end-to-end proof remain open. The obsolete implicit membership writer is removed. | | Account Service | `DELETE /tenants/{tenantId}/memberships/me` | `caller_membership_scoped` | Caller-bound membership exit remains available while billing-blocked to any current member role, requires live subject-bound membership, and advances membership authority atomically | | Account Service | `AuthLogout` / `AuthLogoutAll` | `account_scoped` | Accepts `control-ui` (`audience: control-ui`) or `player-bootstrap` (`audience: player-bootstrap`) with registry-backed authenticated account scope. Bounded retries may return no-op success only from a durable committed exact-token tombstone (`AuthLogout`) or durable proof that a prior logout-all superseded the token (`AuthLogoutAll`); registry absence alone is insufficient and the retry exception grants no reusable authorization context | | Account Service | `GET /accounts/{accountId}/deletion` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=deletion_status`; the Account-issued credential is bound to the account and deletion workflow and returns deletion status only | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 2e28ddc04b..a8f6ba0f5d 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -400,7 +400,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - explicit_public_production_JOIN_is_not_implemented; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; the_live_adapter_uses_membershipExists_false_for_missing_and_gameplayAdmissionAllowed_false_for_existing_non_admitting_membership_without_classifying_the_latter_as_INACTIVE; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - Account_explicit_public_production_JOIN_writer_is_implemented_locally_but_Game_Session_text_dispatch_and_direct_text_end_to_end_proof_remain_unavailable; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_but_current_PLAY_consumer_still_uses_membershipExists_gameplayAdmissionAllowed_membershipVersion_and_evaluatedAt_without_consuming_the_new_fields; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support @@ -1933,15 +1933,48 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, IDEMPOTENCY_CONFLICT, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable + implementation_status: + known_drift: + - Account_controller_and_operation_are_implemented_locally_but_the_exact_public_Gateway_path_is_blocked_by_an_explicit_route_guard_and_the_route_is_absent_from_publicOpenAPI + - local_policy_digest_revalidation_does_not_prove_exact_target_validity_through_Account_commit; strict_ADR_0025_commit_gate_remains_incomplete + - service: account-service + route: IssueDirectTextConnectScope + scope: tenant + classification: internal_workload + auth_path: exact_mtls_workload_plus_caller_specific_context + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + delegated_subject: typed_player_execution_context + target_binding: typed_caller_context_and_exact_resolved_target + tenant_billing_authority_generation_applies: false + membership_authority_generation_applies: false + required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer] + canonical_errors: + any_of: [ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, REALM_UNAVAILABLE, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] + end_user_token_required: false + issuance_contract: + result: opaque_short_lived_connect_scope_id + binds: [caller_account, resolved_target, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt] + silent_retarget: forbidden + implementation_status: + known_drift: + - direct_text_client_end_to_end_proof_unavailable - service: account-service route: JoinPublicProductionMembership scope: tenant classification: internal_workload - route_status: target_not_currently_routable auth_path: exact_mtls_workload issued_token_state: none accepted_token_profiles: [] @@ -1975,7 +2008,10 @@ routes: membership_creation: caller_bound_after_validation implementation_status: known_drift: - - explicit_JOIN_and_Join_And_Play_are_not_currently_implemented; connect_token_and_play_now_require_existing_membership_and_do_not_invoke_this_writer + - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only + - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only + - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable - service: account-service route: DELETE /tenants/{tenantId}/memberships/me scope: tenant @@ -3631,6 +3667,48 @@ routes: any_of: [IDEMPOTENCY_CONFLICT] roles: any_of: [tenantAdmin, platformAdmin] + - service: logging-admin-service + route: CreateLogEvent + transport: grpc + scope: account + route_status: target_not_currently_routable + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false + implementation_status: + known_drift: + - current_handler_retains_AdminRoleGuard_and_returns_UNAVAILABLE_without_dispatch; target_Account_mTLS_audit_receipt_receiver_and_runtime_proof_are_unavailable + - service: logging-admin-service + route: ReadLogEventReceipt + transport: grpc + scope: account + route_status: target_not_currently_routable + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false + implementation_status: + known_drift: + - current_service_has_no_ReadLogEventReceipt_handler_and_returns_UNIMPLEMENTED; target_Account_mTLS_receipt_readback_and_runtime_proof_are_unavailable - service: game-session-service route: ToggleFeatureFlag transport: grpc diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 6a0889e5c5..971894fcfe 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -41,6 +41,10 @@ for conventions on schema evolution and error handling. See each service's - [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) - [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) - [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) + - [IssueDirectTextConnectScopeRequest](#account-v1-IssueDirectTextConnectScopeRequest) + - [IssueDirectTextConnectScopeResponse](#account-v1-IssueDirectTextConnectScopeResponse) + - [JoinPublicProductionMembershipRequest](#account-v1-JoinPublicProductionMembershipRequest) + - [JoinPublicProductionMembershipResponse](#account-v1-JoinPublicProductionMembershipResponse) - [LinkExternalAccountRequest](#account-v1-LinkExternalAccountRequest) - [LinkExternalAccountResponse](#account-v1-LinkExternalAccountResponse) - [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) @@ -505,9 +509,15 @@ for conventions on schema evolution and error handling. See each service's - [PingResponse](#logging_admin-v1-PingResponse) - [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) - [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) + - [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) + - [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) - [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) - [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) + - [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) + - [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) + - [AccountAuditScope](#logging_admin-v1-AccountAuditScope) + - [LoggingAdminService](#logging_admin-v1-LoggingAdminService) - [logging-admin/v1/report_service.proto](#logging-admin_v1_report_service-proto) @@ -525,6 +535,9 @@ for conventions on schema evolution and error handling. See each service's - [shared/v1/paging.proto](#shared_v1_paging-proto) - [PagingRequest](#shared-v1-PagingRequest) +- [shared/v1/player_execution_context.proto](#shared_v1_player_execution_context-proto) + - [PlayerExecutionContext](#shared-v1-PlayerExecutionContext) + - [social-groups/v1/social_groups_service.proto](#social-groups_v1_social_groups_service-proto) - [AddFriendRequest](#social_groups-v1-AddFriendRequest) - [AddFriendResponse](#social_groups-v1-AddFriendResponse) @@ -729,7 +742,6 @@ Parameters required to register a new account. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | Tenant that owns the new account. | | username | [string](#string) | | Desired username for login and display. | | email | [string](#string) | | Email address used for notifications and password recovery. | | password | [string](#string) | | Raw password that the server hashes before storage. | @@ -994,6 +1006,90 @@ Result of a CreateAccount call. | evaluated_at | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | | membership_exists | [bool](#bool) | | | +| membership_lifecycle_state | [string](#string) | | | +| membership_authority_generation | [uint64](#uint64) | | | + + + + + + + + +### IssueDirectTextConnectScopeRequest +Game Session supplies its authenticated, transport-local player context and +exact catalog/pointer evidence. Account re-resolves the target before issuance. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| player_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| catalog_revision | [int64](#int64) | | | +| pointer_version | [int64](#int64) | | | + + + + + + + + +### IssueDirectTextConnectScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| connect_scope_id | [string](#string) | | | +| connect_scope_expires_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### JoinPublicProductionMembershipRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| player_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | +| connect_scope_id | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### JoinPublicProductionMembershipResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| outcome_code | [string](#string) | | | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| membership_id | [string](#string) | | | +| membership_version | [uint64](#uint64) | | | +| membership_authority_generation | [uint64](#uint64) | | | +| replayed | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1302,6 +1398,8 @@ Basic ping response containing a greeting and optional error details. | GetTenantMembershipForRuntime | [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) | [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) | | | GetRealmAccessGrantForRuntime | [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) | [GetRealmAccessGrantForRuntimeResponse](#account-v1-GetRealmAccessGrantForRuntimeResponse) | | | GetTenantEntitlementsForRuntime | [GetTenantEntitlementsForRuntimeRequest](#account-v1-GetTenantEntitlementsForRuntimeRequest) | [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) | | +| IssueDirectTextConnectScope | [IssueDirectTextConnectScopeRequest](#account-v1-IssueDirectTextConnectScopeRequest) | [IssueDirectTextConnectScopeResponse](#account-v1-IssueDirectTextConnectScopeResponse) | | +| JoinPublicProductionMembership | [JoinPublicProductionMembershipRequest](#account-v1-JoinPublicProductionMembershipRequest) | [JoinPublicProductionMembershipResponse](#account-v1-JoinPublicProductionMembershipResponse) | | | GetProfile | [GetProfileRequest](#account-v1-GetProfileRequest) | [GetProfileResponse](#account-v1-GetProfileResponse) | | | ListPresenceVisibilityPolicies | [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) | [ListPresenceVisibilityPoliciesResponse](#account-v1-ListPresenceVisibilityPoliciesResponse) | | | UpdateProfile | [UpdateProfileRequest](#account-v1-UpdateProfileRequest) | [UpdateProfileResponse](#account-v1-UpdateProfileResponse) | | @@ -7194,6 +7292,9 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | occurred_at_ms | [int64](#int64) | | | | prepared_version_upgrade_id | [string](#string) | | | | public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | optional | | +| realm_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | +| playable_state_namespace_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | @@ -7425,6 +7526,9 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | state_scope | [string](#string) | | | | character_creation_policy | [string](#string) | | | | public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | @@ -7556,6 +7660,9 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | state_scope | [string](#string) | | | | character_creation_policy | [string](#string) | | | | public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | @@ -9600,9 +9707,15 @@ plus scoped tick pause/resume used for rollback safety. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| type | [string](#string) | | | -| message | [string](#string) | | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | @@ -9619,6 +9732,15 @@ plus scoped tick pause/resume used for rollback safety. | ----- | ---- | ----- | ----------- | | log_event_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | @@ -9719,6 +9841,55 @@ plus scoped tick pause/resume used for rollback safety. + + +### ReadLogEventReceiptRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | + + + + + + + + +### ReadLogEventReceiptResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| log_event_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### ToggleFeatureFlagRequest @@ -9754,6 +9925,48 @@ plus scoped tick pause/resume used for rollback safety. + + +### AccountAuditReceiptOutcome + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE | 2 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE | 3 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT | 4 | | + + + + + +### AccountAuditReceiptStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED | 2 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT | 3 | | + + + + + +### AccountAuditScope + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_AUDIT_SCOPE_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_SCOPE_PLATFORM | 1 | | +| ACCOUNT_AUDIT_SCOPE_TENANT | 2 | | + + + @@ -9768,6 +9981,7 @@ plus scoped tick pause/resume used for rollback safety. | Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | | QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | | CreateLogEvent | [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) | [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) | | +| ReadLogEventReceipt | [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) | [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) | | | ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | | EvaluateModerationPolicy | [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) | [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) | | | ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | @@ -9934,6 +10148,46 @@ Standard paging request for list RPCs. + +

Top

+ +## shared/v1/player_execution_context.proto + + + + + +### PlayerExecutionContext +Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +Receivers validate the required subset and equality with their own authoritative target. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| session_id | [string](#string) | | | +| realm_id | [string](#string) | | | +| request_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | + + + + + + + + + + + + + + +

Top

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 730fba3481..9597372f71 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -29,16 +29,16 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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 identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.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 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql) | [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) | [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. Current non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, 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. 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 text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread at issuance, and generic prompt-mode login remain gaps. Deployment/mTLS and fresh-image proof for the focused `PLAY` changes remain incomplete. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit JOIN, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. On a fresh connect-token issuance or cache miss, issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; a cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not revalidate the applicable non-public grant, so that target grant-validation proof remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. The canonical `JoinPublicProductionMembership` Account writer and `POST /auth/bootstrap/join` controller/operation are implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction; the current Gateway guard still blocks external exposure. Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -143,7 +143,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. First-party proofs cover fresh-token enforcement, bare verified-identity login, `PLAY` scope binding, replay/expiry/context/scope failures, screen-buffer restore, and fresh redraw. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. Explicit `JOIN`/`Join & Play`, transactional join authority, the connect-token membership-authority-generation reread, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. - **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. @@ -160,6 +160,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. - Account deletion currently removes payment and subscription rows after the active-billing precondition, while the canonical data-rights design retains billing/audit records for settlement and compliance. +- Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on #2848 JOIN receipt and unknown-outcome reconciliation. No universal retention duration is selected. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. - The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. @@ -173,7 +174,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and target explicit public-production join/leave | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; target join/leave APIs remain unimplemented | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including the implemented `/auth/bootstrap/join` controller and local JOIN RPC; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index c16a7e416b..b6ea879e90 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; @@ -16,6 +17,8 @@ service AccountService { rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); rpc GetRealmAccessGrantForRuntime(GetRealmAccessGrantForRuntimeRequest) returns (GetRealmAccessGrantForRuntimeResponse); rpc GetTenantEntitlementsForRuntime(GetTenantEntitlementsForRuntimeRequest) returns (GetTenantEntitlementsForRuntimeResponse); + rpc IssueDirectTextConnectScope(IssueDirectTextConnectScopeRequest) returns (IssueDirectTextConnectScopeResponse); + rpc JoinPublicProductionMembership(JoinPublicProductionMembershipRequest) returns (JoinPublicProductionMembershipResponse); rpc GetProfile(GetProfileRequest) returns (GetProfileResponse); rpc ListPresenceVisibilityPolicies(ListPresenceVisibilityPoliciesRequest) returns (ListPresenceVisibilityPoliciesResponse); @@ -30,6 +33,45 @@ service AccountService { rpc VerifyEmail(VerifyEmailRequest) returns (VerifyEmailResponse); } +// Game Session supplies its authenticated, transport-local player context and +// exact catalog/pointer evidence. Account re-resolves the target before issuance. +message IssueDirectTextConnectScopeRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string tenant_id = 2; + string world_slug = 3; + string realm_slug = 4; + string realm_id = 5; + string playable_state_namespace_id = 6; + string playable_state_scope = 7; + string game_instance_id = 8; + int64 catalog_revision = 9; + int64 pointer_version = 10; +} + +message IssueDirectTextConnectScopeResponse { + string connect_scope_id = 1; + string connect_scope_expires_at = 2; + shared.v1.ErrorDetail error = 3; +} + +message JoinPublicProductionMembershipRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string connect_scope_id = 2; + string request_id = 3; +} + +message JoinPublicProductionMembershipResponse { + bool success = 1; + string outcome_code = 2; + string account_id = 3; + string tenant_id = 4; + string membership_id = 5; + uint64 membership_version = 6; + uint64 membership_authority_generation = 7; + bool replayed = 8; + shared.v1.ErrorDetail error = 9; +} + // Empty request used to verify that the service is reachable. message PingRequest {} @@ -43,8 +85,8 @@ message PingResponse { // Parameters required to register a new account. message CreateAccountRequest { - // Tenant that owns the new account. - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; // Desired username for login and display. string username = 2; // Email address used for notifications and password recovery. @@ -108,6 +150,8 @@ message GetTenantMembershipForRuntimeResponse { string evaluated_at = 5; shared.v1.ErrorDetail error = 6; bool membership_exists = 7; + string membership_lifecycle_state = 8; + uint64 membership_authority_generation = 9; } message GetRealmAccessGrantForRuntimeRequest { diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 2902aad35b..210539837f 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package logging_admin.v1; import "shared/v1/errors.proto"; +import "google/protobuf/timestamp.proto"; option java_package = "net.firedevops.firemud.loggingadmin.v1"; option java_multiple_files = true; @@ -11,6 +12,7 @@ service LoggingAdminService { rpc Ping(PingRequest) returns (PingResponse); rpc QueryLogs(QueryLogsRequest) returns (QueryLogsResponse); rpc CreateLogEvent(CreateLogEventRequest) returns (CreateLogEventResponse); + rpc ReadLogEventReceipt(ReadLogEventReceiptRequest) returns (ReadLogEventReceiptResponse); rpc ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse); rpc EvaluateModerationPolicy(EvaluateModerationPolicyRequest) returns (EvaluateModerationPolicyResponse); @@ -35,15 +37,81 @@ message QueryLogsResponse { } message CreateLogEventRequest { + reserved 2 to 4; + reserved "account_id", "type", "message"; + string tenant_id = 1; - string account_id = 2; - string type = 3; - string message = 4; + AccountAuditScope scope = 5; + string audit_event_id = 6; + string producer_service = 7; + string event_type = 8; + google.protobuf.Timestamp occurred_at = 9; + int32 schema_version = 10; + bytes payload = 11; + int32 payload_digest_version = 12; + string payload_digest = 13; } message CreateLogEventResponse { string log_event_id = 1; shared.v1.ErrorDetail error = 2; + AccountAuditScope scope = 3; + string tenant_id = 4; + string audit_event_id = 5; + string receipt_id = 6; + int32 schema_version = 7; + int32 payload_digest_version = 8; + string payload_digest = 9; + AccountAuditReceiptStatus status = 10; + AccountAuditReceiptOutcome outcome = 11; +} + +message ReadLogEventReceiptRequest { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string producer_service = 4; + string event_type = 5; + google.protobuf.Timestamp occurred_at = 6; + int32 schema_version = 7; + bytes payload = 8; + int32 payload_digest_version = 9; + string payload_digest = 10; +} + +message ReadLogEventReceiptResponse { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string receipt_id = 4; + string log_event_id = 5; + int32 schema_version = 6; + int32 payload_digest_version = 7; + string payload_digest = 8; + AccountAuditReceiptStatus status = 9; + AccountAuditReceiptOutcome outcome = 10; + shared.v1.ErrorDetail error = 11; +} + +enum AccountAuditScope { + ACCOUNT_AUDIT_SCOPE_UNSPECIFIED = 0; + ACCOUNT_AUDIT_SCOPE_PLATFORM = 1; + ACCOUNT_AUDIT_SCOPE_TENANT = 2; +} + +enum AccountAuditReceiptStatus { + ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED = 1; + ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED = 2; + ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT = 3; +} + +enum AccountAuditReceiptOutcome { + ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED = 1; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE = 2; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE = 3; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT = 4; } message ApplyModerationActionRequest { diff --git a/protos/shared/v1/player_execution_context.proto b/protos/shared/v1/player_execution_context.proto new file mode 100644 index 0000000000..7dfbf61210 --- /dev/null +++ b/protos/shared/v1/player_execution_context.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package shared.v1; + +option java_package = "net.firedevops.firemud.shared.v1"; +option java_multiple_files = true; + +// Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +// Receivers validate the required subset and equality with their own authoritative target. +message PlayerExecutionContext { + string account_id = 1; + string tenant_id = 2; + string playable_state_namespace_id = 3; + string game_instance_id = 4; + string character_id = 5; + string session_id = 6; + string realm_id = 7; + string request_id = 8; + string playable_state_scope = 9; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 44e168eac5..4eee08dfc8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -1,15 +1,29 @@ package net.firedevops.firemud.accountservice.client; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** Client for communicating with the Logging & Admin Service. */ @@ -17,6 +31,8 @@ public class LoggingAdminClient extends AbstractReloadingBlockingGrpcClient< LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub> { + private static final Logger logger = LoggerFactory.getLogger(LoggingAdminClient.class); + public LoggingAdminClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -47,27 +63,102 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - /** Log that a new account was created. */ - public void logAccountCreation(long tenantId, long accountId) { - CreateLogEventRequest request = + /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ + public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { + AccountAuditScope scope; + if ("platform".equals(envelope.scope())) { + if (envelope.tenantId() != null) { + throw new IllegalArgumentException("Platform audit events must not carry a tenant ID"); + } + scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + } else if ("tenant".equals(envelope.scope())) { + if (envelope.tenantId() == null || envelope.tenantId() <= 0) { + throw new IllegalArgumentException("Tenant audit events require a positive tenant ID"); + } + scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + } else { + throw new IllegalArgumentException("Account audit scope must be platform or tenant"); + } + + CreateLogEventRequest.Builder builder = CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(); - stub().createLogEvent(request); + .setScope(scope) + .setAuditEventId(envelope.auditEventId().toString()) + .setProducerService(envelope.producerService()) + .setEventType(envelope.eventType()) + .setOccurredAt( + Timestamp.newBuilder() + .setSeconds(envelope.occurredAt().getEpochSecond()) + .setNanos(envelope.occurredAt().getNano()) + .build()) + .setSchemaVersion(envelope.schemaVersion()) + .setPayload(ByteString.copyFrom(envelope.payload(), StandardCharsets.UTF_8)) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()); + if (envelope.tenantId() != null) { + builder.setTenantId(envelope.tenantId().toString()); + } + CreateLogEventResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); + if (response.hasError()) { + String errorCode = response.getError().getCode(); + if (errorCode == null || !errorCode.matches("[A-Z][A-Z0-9_]{0,63}")) { + errorCode = "UNKNOWN"; + } + throw new IllegalStateException("Account audit receiver returned error code " + errorCode); + } + if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) + || !response.getPayloadDigest().equals(envelope.payloadDigest()) + || response.getSchemaVersion() != envelope.schemaVersion() + || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() + || response.getScope() != builder.getScope() + || !response.getTenantId().equals(builder.getTenantId())) { + throw new IllegalStateException( + "Account audit receiver returned mismatched receipt evidence"); + } + boolean minimized = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED + && response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + boolean committed = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED + && (response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED + || response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + if ((!committed && !minimized) + || response.getReceiptId().isBlank() + || response.getLogEventId().isBlank()) { + throw new IllegalStateException("Account audit receiver did not prove a terminal receipt"); + } + return new AuditDeliveryResult(response.getReceiptId(), response.getLogEventId(), minimized); } - /** Log that a payment transaction occurred. */ + /** Existing deferred-commerce path remains best effort until its own outbox convergence. */ public void logPayment(long tenantId, long accountId, long transactionId) { - CreateLogEventRequest request = - CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("PAYMENT_TXN") - .setMessage("txId=" + transactionId) - .build(); - stub().createLogEvent(request); + String payload = "{\"accountId\":" + accountId + ",\"transactionId\":" + transactionId + "}"; + try { + deliver( + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + tenantId, + "account-service", + "PAYMENT_TXN", + Instant.now(), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload)); + } catch (RuntimeException failure) { + logger.warn( + "Deferred payment audit delivery failed; cause={} tenantId={} accountId={} transactionId={}", + failure.getClass().getSimpleName(), + tenantId, + accountId, + transactionId); + } } + + public record AuditDeliveryResult(String receiptId, String logEventId, boolean minimized) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java index afc1eec45a..e51178229b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java @@ -12,6 +12,8 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenResponse; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.EmailVerificationRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.LoginRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; @@ -19,6 +21,7 @@ import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.ApiResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; @@ -89,6 +92,19 @@ public ResponseEntity>> listBootstrapCha bootstrapToken, worldSlug, realmSlug, connectScopeId))); } + @PostMapping("/bootstrap/join") + public ResponseEntity> joinPublicProduction( + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @Valid @RequestBody JoinPublicProductionRequest request) { + JoinPublicProductionResult result = + accountService.joinPublicProduction(extractBearerToken(authorization), request); + if (!result.success()) { + throw new AuthenticationException( + result.outcomeCode(), "JOIN was denied for the selected realm"); + } + return ResponseEntity.ok(ApiResponse.success(result)); + } + @PostMapping("/connect-token") public ResponseEntity> connectToken( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index 024963752f..ac571813e3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -4,6 +4,8 @@ import de.mkammerer.argon2.Argon2Factory; import java.time.LocalDateTime; import java.util.List; +import java.util.Objects; +import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -42,16 +44,19 @@ public class TestDataSeeder implements ApplicationRunner { @Override @Transactional public void run(ApplicationArguments args) { + Optional existingDemoAccount = accountRepository.findByEmail(DEMO_EMAIL); + if (existingDemoAccount.isPresent() + && !DEMO_EMAIL.equals(existingDemoAccount.orElseThrow().getEmail())) { + throw new IllegalStateException("Demo account identity does not match configured email"); + } Account account = - accountRepository - .findByEmail(DEMO_EMAIL) - .orElseGet( - () -> { - Account seeded = new Account(); - seeded.setUsername(DEMO_USERNAME); - seeded.setEmail(DEMO_EMAIL); - return seeded; - }); + existingDemoAccount.orElseGet( + () -> { + Account seeded = new Account(); + seeded.setUsername(DEMO_USERNAME); + seeded.setEmail(DEMO_EMAIL); + return seeded; + }); account.setUsername(DEMO_USERNAME); account.setEmail(DEMO_EMAIL); @@ -60,12 +65,27 @@ public void run(ApplicationArguments args) { account.setEmailVerified(true); account = accountRepository.save(account); - if (!accountTenantMembershipRepository.existsByAccountIdAndTenantId( - account.getId(), DEMO_TENANT_ID)) { - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setAccount(account); - membership.setTenantId(DEMO_TENANT_ID); + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(account.getId(), DEMO_TENANT_ID) + .orElse(null); + if (membership == null) { + AccountTenantMembership seededMembership = new AccountTenantMembership(); + seededMembership.setAccount(account); + seededMembership.setTenantId(DEMO_TENANT_ID); + seededMembership.setGameplayAdmissionAllowed(true); + seededMembership.setLifecycleState("ACTIVE"); + seededMembership.setMembershipVersion(1); + seededMembership.setMembershipAuthorityGeneration(1); + seededMembership.setAuthorityProvenance("SEEDED_DEMO"); + accountTenantMembershipRepository.save(seededMembership); + } else if (isQuarantinedDemoMembership(account, membership)) { membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(Math.addExact(membership.getMembershipVersion(), 1L)); + membership.setMembershipAuthorityGeneration( + Math.addExact(membership.getMembershipAuthorityGeneration(), 1L)); + membership.setAuthorityProvenance("SEEDED_DEMO"); accountTenantMembershipRepository.save(membership); } @@ -98,6 +118,20 @@ public void run(ApplicationArguments args) { } } + private static boolean isQuarantinedDemoMembership( + Account account, AccountTenantMembership membership) { + return membership.getId() != null + && membership.getAccount() != null + && membership.getAccount().getId() != null + && Objects.equals(membership.getAccount().getId(), account.getId()) + && Objects.equals(membership.getTenantId(), DEMO_TENANT_ID) + && "LEGACY_UNVERIFIED".equals(membership.getLifecycleState()) + && "LEGACY_UNVERIFIED".equals(membership.getAuthorityProvenance()) + && !membership.isGameplayAdmissionAllowed() + && membership.getMembershipVersion() > 0L + && membership.getMembershipAuthorityGeneration() > 0L; + } + private String hashPassword(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java new file mode 100644 index 0000000000..ff5e2700d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Receiver-version-1 digest over exact persisted UTF-8 payload bytes. */ +public final class AccountAuditDigest { + private AccountAuditDigest() {} + + public static String ofPayload(String payload) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(payload.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java new file mode 100644 index 0000000000..a99ebc70cb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.time.Instant; +import java.util.UUID; + +/** The immutable Account-owned delivery envelope; the SQL outbox is its authority. */ +public record AccountAuditEnvelope( + UUID auditEventId, + String scope, + Long tenantId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + String payload) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java index d025e43865..ed43a78720 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java @@ -8,5 +8,5 @@ public record AccountDto( Long id, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, - @NotNull @Size(max = 20) String role, + @Size(max = 20) String role, boolean emailVerified) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java new file mode 100644 index 0000000000..bf2147fa79 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Canonical exact-byte digests for retained public-production scope and JOIN attempts. */ +public final class AccountJoinDigest { + private AccountJoinDigest() {} + + public static String scope(VerifiedJoinScope scope) { + return hash( + "scopeDigestVersion=v1\n" + + field("accountId", scope.accountId()) + + "targetClass=PUBLIC_PRODUCTION\n" + + field("connectScopeId", scope.connectScopeId()) + + field("tenantId", scope.tenantId()) + + field("realmId", scope.realmId().toString()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("evaluatedAt", scope.evaluatedAt()) + + field("connectScopeExpiresAt", scope.connectScopeExpiresAt())); + } + + public static String request( + VerifiedJoinScope scope, + String callerBinding, + Boolean allowPublicJoin, + Long entitlementVersion) { + if (allowPublicJoin == null || entitlementVersion == null || entitlementVersion <= 0L) { + throw new IllegalArgumentException("A JOIN policy digest requires exact available evidence"); + } + return hash( + "joinDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("connectScopeId", scope.connectScopeId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("entitlementAuthorityAvailability", "AVAILABLE") + + field("allowPublicJoin", allowPublicJoin) + + field("entitlementVersion", entitlementVersion)); + } + + public static String intent(String requestId, VerifiedJoinScope scope, String callerBinding) { + return hash( + "joinIntentDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("requestId", requestId) + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("connectScopeId", scope.connectScopeId()) + + field("scopeDigest", scope.snapshotDigest()) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("realmId", scope.realmId().toString()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion())); + } + + public static String tokenHash(String connectScopeId) { + return hash(connectScopeId); + } + + private static String field(String name, Object value) { + if (value == null) { + throw new IllegalArgumentException(name + " is required"); + } + String wire = value.toString(); + if (wire.isEmpty() + || wire.indexOf('=') >= 0 + || wire.indexOf('\n') >= 0 + || wire.indexOf('\r') >= 0) { + throw new IllegalArgumentException(name + " has an invalid canonical wire value"); + } + return name + "=" + wire + "\n"; + } + + private static String hash(String preimage) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 796fe0ad76..239ad9298d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -4,10 +4,14 @@ public record BootstrapRealmDto( String worldSlug, String realmSlug, + String realmId, String displayName, long tenantId, long gameInstanceId, long pointerVersion, + long catalogRevision, + String playableStateNamespaceId, + String playableStateScope, boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java index 37bdfe1ea7..9cf32940dd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java @@ -2,11 +2,9 @@ import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; public record CreateAccountRequest( - @NotNull @Positive Long tenantId, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, @NotNull @Size(min = 6, max = 100) String password) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java new file mode 100644 index 0000000000..2638dc9cfb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ +public record DirectTextCallerContext( + long accountId, + long tenantId, + UUID realmId, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + String sessionId, + String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java new file mode 100644 index 0000000000..0f1a2a90ca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.accountservice.dto; + +/** + * Opaque, short-lived Account-issued target scope retained only by Game Session transport state. + */ +public record DirectTextJoinScope(String connectScopeId, String connectScopeExpiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java new file mode 100644 index 0000000000..b4273bf5b5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** + * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. + */ +public record DirectTextJoinTarget( + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java new file mode 100644 index 0000000000..638de32685 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.accountservice.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** Only the Account-issued target scope and caller-stable attempt ID cross the public API. */ +public record JoinPublicProductionRequest( + @NotBlank @Size(max = 2048) String connectScopeId, + @NotBlank @Size(max = JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) String requestId) { + public static final int MAX_REQUEST_ID_LENGTH = 128; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java new file mode 100644 index 0000000000..a5696c235d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.accountservice.dto; + +/** Durable explicit-JOIN outcome; a failure is returned so its receipt can commit first. */ +public record JoinPublicProductionResult( + boolean success, + String outcomeCode, + long accountId, + long tenantId, + long membershipId, + long membershipVersion, + long membershipAuthorityGeneration, + boolean replayed) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java index 50901a2b28..41ed6a0fd3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java @@ -6,4 +6,6 @@ public record RuntimeMembershipDto( boolean membershipExists, boolean gameplayAdmissionAllowed, long membershipVersion, + String membershipLifecycleState, + long membershipAuthorityGeneration, String evaluatedAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java new file mode 100644 index 0000000000..3d96e8c217 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Immutable Account-owned target snapshot retained for an explicit public-production JOIN. */ +public record VerifiedJoinScope( + String connectScopeId, + long accountId, + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + String snapshotDigest) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java index 95038fd526..2fb0e62afe 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java @@ -8,7 +8,7 @@ public class Account { private String username; private String email; private String passwordHash; - private String role = "player"; + private String role; private boolean emailVerified = false; private String loginAuthModes = AccountLoginAuthModes.DEFAULT_SERIALIZED; private AccountLifecycleState lifecycleState = AccountLifecycleState.ACTIVE; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java index 2e1f4a1a38..737251b618 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java @@ -16,6 +16,10 @@ public class AccountTenantMembership { private Long tenantId; private boolean gameplayAdmissionAllowed = true; + private String lifecycleState; + private long membershipVersion; + private long membershipAuthorityGeneration; + private String authorityProvenance; @SuppressFBWarnings( value = "EI_EXPOSE_REP", diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java index db6345c66a..2d4daa7a85 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java @@ -27,4 +27,5 @@ public class Subscription { private LocalDateTime startedAt; private LocalDateTime endedAt; private Long tenantId; + private long entitlementVersion = 1L; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java new file mode 100644 index 0000000000..1a7c649e49 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.tables.AccountAuditOutbox.ACCOUNT_AUDIT_OUTBOX; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +/** Owner-local audit identity, immutable envelope, and durable delivery state. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditOutboxRepository { + private final DSLContext dsl; + + public AccountAuditOutboxRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditEnvelope append( + UUID auditEventId, String scope, Long tenantId, String eventType, String payload) { + if (!("platform".equals(scope) && tenantId == null) + && !("tenant".equals(scope) && tenantId != null && tenantId > 0)) { + throw new IllegalArgumentException("Audit scope and tenant ID must match"); + } + Instant occurredAt = Instant.now(); + String digest = AccountAuditDigest.ofPayload(payload); + AccountAuditOutboxRecord row = dsl.newRecord(ACCOUNT_AUDIT_OUTBOX); + row.setAuditEventId(auditEventId); + row.setScope(scope); + row.setTenantId(tenantId); + row.setProducerService("account-service"); + row.setEventType(eventType); + row.setOccurredAt(toLocalDateTime(occurredAt)); + row.setNextAttemptAt(toLocalDateTime(occurredAt)); + row.setSchemaVersion(1); + row.setPayloadDigestVersion(1); + row.setPayloadDigest(digest); + row.setPayload(payload); + row.setDeliveryStatus("PENDING"); + row.store(); + return toEnvelope(row); + } + + public List pending(int limit, Instant dueBeforeOrAt) { + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where( + ACCOUNT_AUDIT_OUTBOX + .DELIVERY_STATUS + .eq("PENDING") + .and(ACCOUNT_AUDIT_OUTBOX.NEXT_ATTEMPT_AT.le(toLocalDateTime(dueBeforeOrAt)))) + .orderBy( + ACCOUNT_AUDIT_OUTBOX.NEXT_ATTEMPT_AT.asc(), + ACCOUNT_AUDIT_OUTBOX.CREATED_AT.asc(), + ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.asc()) + .limit(limit) + .fetch(this::toEnvelope); + } + + public void markDelivered( + UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + var update = + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) + .set(ACCOUNT_AUDIT_OUTBOX.NEXT_ATTEMPT_AT, (LocalDateTime) null); + if (minimized) { + update.set(ACCOUNT_AUDIT_OUTBOX.PAYLOAD, (String) null); + } + int changed = + update + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING"))) + .execute(); + if (changed == 0) { + AccountAuditOutboxRecord durableRow = + dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) + .fetchOne(); + String expectedStatus = minimized ? "MINIMIZED" : "COMMITTED"; + if (durableRow != null + && expectedStatus.equals(durableRow.getDeliveryStatus()) + && Objects.equals(receiptId, durableRow.getReceiverReceiptId()) + && Objects.equals(logEventId, durableRow.getReceiverLogEventId())) { + return; + } + } + if (changed != 1) { + throw new IllegalStateException("Audit delivery state changed concurrently"); + } + } + + public void recordAttempt(UUID auditEventId) { + LocalDateTime attemptedAt = toLocalDateTime(Instant.now()); + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.ATTEMPT_COUNT, ACCOUNT_AUDIT_OUTBOX.ATTEMPT_COUNT.plus(1)) + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, attemptedAt) + .set( + ACCOUNT_AUDIT_OUTBOX.NEXT_ATTEMPT_AT, + DSL.field( + "CAST({0} AS TIMESTAMP) + make_interval(secs => " + + "LEAST(300, (5 * POWER(2, LEAST({1}, 6)))::INTEGER))", + LocalDateTime.class, DSL.val(attemptedAt), ACCOUNT_AUDIT_OUTBOX.ATTEMPT_COUNT)) + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING"))) + .execute(); + } + + private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { + return new AccountAuditEnvelope( + row.getAuditEventId(), + row.getScope(), + row.getTenantId(), + row.getProducerService(), + row.getEventType(), + toInstant(row.getOccurredAt()), + row.getSchemaVersion(), + row.getPayloadDigestVersion(), + row.getPayloadDigest(), + row.getPayload()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java new file mode 100644 index 0000000000..de441fb2de --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_CONNECT_SCOPE_RECORDS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Optional; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Durable, exact-byte scope evidence; its token hash is only a lookup key, never authority. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountConnectScopeRepository { + private static final String DELETE_EXPIRED_UNREFERENCED_SQL = + "DELETE FROM account_connect_scope_records scope " + + "WHERE scope.ctid IN (" + + " SELECT candidate.ctid " + + " FROM account_connect_scope_records candidate " + + " WHERE CASE " + + " WHEN candidate.connect_scope_expires_at ~ " + + " '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,9})?Z$' " + + " AND pg_input_is_valid(candidate.connect_scope_expires_at, " + + " 'timestamp with time zone') " + + " THEN candidate.connect_scope_expires_at::timestamptz <= CAST(? AS timestamptz) " + + " ELSE FALSE " + + " END " + + " AND NOT EXISTS (" + + " SELECT 1 FROM account_join_operations operation " + + " WHERE operation.scope_token_hash = candidate.scope_token_hash" + + " ) " + + " ORDER BY candidate.account_id, candidate.scope_token_hash " + + " LIMIT ? " + + " FOR UPDATE OF candidate SKIP LOCKED" + + ")"; + + private final DSLContext dsl; + + public AccountConnectScopeRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void insert(VerifiedJoinScope scope) { + dsl.insertInto(ACCOUNT_CONNECT_SCOPE_RECORDS) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH, + AccountJoinDigest.tokenHash(scope.connectScopeId())) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS, "PUBLIC_PRODUCTION") + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID, scope.realmId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG, scope.realmSlug()) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT, scope.evaluatedAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT, scope.connectScopeExpiresAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST, scope.snapshotDigest()) + .execute(); + } + + public Optional find(String connectScopeId) { + return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) + .where( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq( + AccountJoinDigest.tokenHash(connectScopeId))) + .fetchOptional(record -> toScope(record, connectScopeId)); + } + + /** + * Deletes a bounded batch of expired scopes only when no JOIN receipt references them. Malformed + * expiry values are retained. The database FK from JOIN receipts is the concurrent insert fence + * for the anti-join predicate. + */ + public int deleteExpiredUnreferenced(Instant capturedNow, int batchSize) { + if (capturedNow == null) { + throw new IllegalArgumentException("Captured cleanup time is required"); + } + if (batchSize <= 0) { + throw new IllegalArgumentException("Cleanup batch size must be positive"); + } + return dsl.execute( + DELETE_EXPIRED_UNREFERENCED_SQL, + OffsetDateTime.ofInstant(capturedNow, ZoneOffset.UTC), + batchSize); + } + + private VerifiedJoinScope toScope(Record record, String connectScopeId) { + if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { + throw new IllegalStateException("JOIN scope is not public production"); + } + VerifiedJoinScope scope = + new VerifiedJoinScope( + connectScopeId, + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST)); + if (!scope.snapshotDigest().equals(AccountJoinDigest.scope(scope))) { + throw new IllegalStateException("JOIN scope digest mismatch"); + } + return scope; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java new file mode 100644 index 0000000000..a43a4b536b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_JOIN_OPERATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Serializes explicit JOIN on the global account row and retains exact operation outcomes. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountJoinOperationRepository { + private final DSLContext dsl; + + public AccountJoinOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void lockAccount(long accountId) { + Long locked = + dsl.select(ACCOUNTS.ID) + .from(ACCOUNTS) + .where(ACCOUNTS.ID.eq(accountId)) + .forUpdate() + .fetchOne(ACCOUNTS.ID); + if (locked == null) { + throw new IllegalArgumentException("JOIN account does not exist"); + } + } + + public Optional find(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); + } + + public Optional findForUpdate(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .forUpdate() + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); + } + + public boolean hasRetainedOperation(long accountId) { + return dsl.fetchExists( + ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); + } + + public boolean insertIntent( + String requestId, VerifiedJoinScope scope, String callerBinding, String intentDigest) { + int inserted = + dsl.insertInto(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID, requestId) + .set(ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_JOIN_OPERATIONS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_JOIN_OPERATIONS.VERIFIED_CALLER_BINDING, callerBinding) + .set( + ACCOUNT_JOIN_OPERATIONS.SCOPE_TOKEN_HASH, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId())) + .set(ACCOUNT_JOIN_OPERATIONS.CONNECT_SCOPE_DIGEST, scope.snapshotDigest()) + .set(ACCOUNT_JOIN_OPERATIONS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_SLUG, scope.realmSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_ID, scope.realmId()) + .set( + ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_JOIN_OPERATIONS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_JOIN_OPERATIONS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_JOIN_OPERATIONS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST, intentDigest) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, false) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, "PENDING") + .onConflict(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID) + .doNothing() + .execute(); + return inserted == 1; + } + + public void bindPolicyEvidence( + String requestId, String requestDigest, Long entitlementVersion, Boolean allowPublicJoin) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_VERSION, entitlementVersion) + .set(ACCOUNT_JOIN_OPERATIONS.ALLOW_PUBLIC_JOIN, allowPublicJoin) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST, requestDigest) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) + .and(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull())) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed before policy binding"); + } + } + + public void recordAttemptFailure( + String requestId, String authorityAvailability, String failureCode) { + if (failureCode == null || failureCode.isBlank()) { + throw new IllegalArgumentException("JOIN attempt failure code is required"); + } + if (!"AVAILABLE".equals(authorityAvailability) + && !"UNAVAILABLE".equals(authorityAvailability) + && !"NOT_EVALUATED".equals(authorityAvailability)) { + throw new IllegalArgumentException("JOIN attempt authority availability is invalid"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), authorityAvailability) + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, authorityAvailability) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, failureCode) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed while recording attempt failure"); + } + } + + public void finish( + String requestId, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + if (!"COMMITTED".equals(status) && !"FAILED".equals(status)) { + throw new IllegalArgumentException("JOIN terminal status is invalid"); + } + if (outcome == null || outcome.isBlank()) { + throw new IllegalArgumentException("JOIN terminal outcome is required"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, status) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME, outcome) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set( + ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY)) + .set(ACCOUNT_JOIN_OPERATIONS.MEMBERSHIP_ID, membershipId) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_VERSION, membershipVersion) + .set( + ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_AUTHORITY_GENERATION, + membershipAuthorityGeneration) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public void recordCallerBoundAuthorityInvalidation(String requestId) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, true) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public record JoinOperation( + long accountId, + long tenantId, + UUID realmId, + String callerBinding, + String scopeTokenHash, + String connectScopeDigest, + String entitlementAuthorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + Integer requestDigestVersion, + String requestDigest, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration, + int intentDigestVersion, + String intentDigest, + String lastAttemptFailureCode, + String lastAttemptAuthorityAvailability) {} + + private static JoinOperation toJoinOperation( + net.firedevops.firemud.accountservice.jooq.tables.records.AccountJoinOperationsRecord row) { + return new JoinOperation( + row.getAccountId(), + row.getTenantId(), + row.getRealmId(), + row.getVerifiedCallerBinding(), + row.getScopeTokenHash(), + row.getConnectScopeDigest(), + row.getEntitlementAuthorityAvailability(), + row.getAllowPublicJoin(), + row.getEntitlementVersion(), + row.getRequestDigestVersion(), + row.getRequestDigest(), + row.getStatus(), + row.getOutcome(), + row.getMembershipId(), + row.getOutcomeMembershipVersion(), + row.getOutcomeMembershipAuthorityGeneration(), + row.getIntentDigestVersion(), + row.getIntentDigest(), + row.getLastAttemptFailureCode(), + row.getLastAttemptAuthorityAvailability()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 086e84468c..1a4b5e3e10 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -65,6 +65,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .returningResult(ACCOUNT_TENANT_MEMBERSHIP.ID) .fetchOne(ACCOUNT_TENANT_MEMBERSHIP.ID); entity.setId(id); @@ -77,6 +83,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .where(ACCOUNT_TENANT_MEMBERSHIP.ID.eq(entity.getId())) .execute(); if (updated != 1) { @@ -119,6 +131,10 @@ private org.jooq.SelectOnConditionStep baseSelect() { ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, + ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -146,6 +162,11 @@ private AccountTenantMembership toEntity(Record record) { membership.setTenantId(record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID)); membership.setGameplayAdmissionAllowed( Boolean.TRUE.equals(record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED))); + membership.setLifecycleState(record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE)); + membership.setMembershipVersion(record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION)); + membership.setMembershipAuthorityGeneration( + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION)); + membership.setAuthorityProvenance(record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE)); return membership; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java index 1954a5e2e5..c46ead0f48 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java @@ -28,6 +28,16 @@ public List findByTenantId(Long tenantId) { .fetch(this::toEntity); } + /** Shares the row lock with subscription writers through the JOIN commit boundary. */ + public List findByTenantIdForUpdate(Long tenantId) { + return baseSelect() + .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .forUpdate() + .of(SUBSCRIPTION) + .fetch(this::toEntity); + } + public List findByAccountId(Long accountId) { return baseSelect() .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) @@ -46,9 +56,11 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) .returningResult(SUBSCRIPTION.ID) .fetchOne(SUBSCRIPTION.ID); entity.setId(id); + entity.setEntitlementVersion(1L); return entity; } int updated = @@ -59,11 +71,17 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .where(SUBSCRIPTION.ID.eq(entity.getId())) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.ENTITLEMENT_VERSION.add(1L)) + .where( + SUBSCRIPTION + .ID + .eq(entity.getId()) + .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion()))) .execute(); if (updated != 1) { throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); } + entity.setEntitlementVersion(entity.getEntitlementVersion() + 1L); return entity; } @@ -86,6 +104,7 @@ private org.jooq.SelectOnConditionStep baseSelect() { SUBSCRIPTION.STARTED_AT, SUBSCRIPTION.ENDED_AT, SUBSCRIPTION.TENANT_ID, + SUBSCRIPTION.ENTITLEMENT_VERSION, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -115,6 +134,7 @@ private Subscription toEntity(Record record) { entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); + entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); return entity; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java new file mode 100644 index 0000000000..9c0a310a99 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** At-least-once delivery of Account's immutable audit outbox envelopes. */ +@Component +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected collaborators are internal Spring singletons.") +public class AccountAuditDeliveryJob { + private static final Logger logger = LoggerFactory.getLogger(AccountAuditDeliveryJob.class); + private final AccountAuditOutboxRepository outbox; + private final LoggingAdminClient loggingAdminClient; + + public AccountAuditDeliveryJob( + AccountAuditOutboxRepository outbox, LoggingAdminClient loggingAdminClient) { + this.outbox = outbox; + this.loggingAdminClient = loggingAdminClient; + } + + @Scheduled(fixedDelayString = "${firemud.account.audit-delivery-delay-ms:5000}") + public void deliverPending() { + Instant capturedNow = Instant.now(); + for (var envelope : outbox.pending(50, capturedNow)) { + try { + var receipt = loggingAdminClient.deliver(envelope); + outbox.markDelivered( + envelope.auditEventId(), + receipt.receiptId(), + receipt.logEventId(), + receipt.minimized()); + } catch (RuntimeException ex) { + try { + outbox.recordAttempt(envelope.auditEventId()); + } catch (RuntimeException bookkeepingFailure) { + logger.warn( + "Failed to record Account audit attempt for event {}", envelope.auditEventId()); + } + logger.warn("Account audit delivery remains pending for event {}", envelope.auditEventId()); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 83f8fe3f7a..c3d2909abc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -10,6 +10,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -47,6 +52,15 @@ java.util.List listBootstrapCharacters( ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request); + JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request); + + DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target); + + JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request); + RuntimeMembershipDto getTenantMembershipForRuntime( Long accountId, Long tenantId, String requestId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java new file mode 100644 index 0000000000..ed2526420f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.annotation.Timed; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.common.LoggingUtil; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Bounded owner-local cleanup of expired connect scopes not retained by a JOIN receipt. */ +@Component +@SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Injected Spring collaborators are internal; invalid cleanup configuration must fail startup.") +public class ExpiredConnectScopeCleanupJob { + /** + * Caps each scheduled run at five repository batches so continuous churn cannot monopolize it. + */ + private static final int MAX_BATCHES_PER_RUN = 5; + + private static final Logger logger = LoggingUtil.getLogger(ExpiredConnectScopeCleanupJob.class); + + private final AccountConnectScopeRepository connectScopeRepository; + private final int batchSize; + private final Counter deleted; + private final Counter failures; + private final Counter capSaturations; + + public ExpiredConnectScopeCleanupJob( + AccountConnectScopeRepository connectScopeRepository, + MeterRegistry meterRegistry, + @Value("${firemud.account.connect-scopes.cleanup.batch-size:100}") int batchSize, + @Value("${firemud.account.connect-scopes.cleanup.interval-ms:60000}") long intervalMs) { + if (batchSize <= 0) { + throw new IllegalArgumentException( + "firemud.account.connect-scopes.cleanup.batch-size must be positive"); + } + if (intervalMs <= 0) { + throw new IllegalArgumentException( + "firemud.account.connect-scopes.cleanup.interval-ms must be positive"); + } + this.connectScopeRepository = connectScopeRepository; + this.batchSize = batchSize; + this.deleted = + Counter.builder("account.connect_scopes.cleanup.deleted") + .description("Expired unreferenced Account connect-scope rows deleted") + .register(meterRegistry); + this.failures = + Counter.builder("account.connect_scopes.cleanup.failure") + .description("Account connect-scope cleanup failures") + .register(meterRegistry); + this.capSaturations = + Counter.builder("account.connect_scopes.cleanup.cap_saturation") + .description("Cleanup runs that consume every full batch up to the per-run cap") + .register(meterRegistry); + } + + @Timed(value = "account.connect_scopes.cleanup") + @Scheduled( + fixedDelayString = "${firemud.account.connect-scopes.cleanup.interval-ms:60000}", + timeUnit = TimeUnit.MILLISECONDS) + public void cleanupExpiredConnectScopes() { + Instant capturedNow = Instant.now(); + try { + boolean allBatchesFull = true; + for (int batch = 0; batch < MAX_BATCHES_PER_RUN; batch++) { + int removed = connectScopeRepository.deleteExpiredUnreferenced(capturedNow, batchSize); + deleted.increment(removed); + if (removed < batchSize) { + allBatchesFull = false; + break; + } + if (removed != batchSize) { + allBatchesFull = false; + } + } + if (allBatchesFull) { + capSaturations.increment(); + } + } catch (RuntimeException ex) { + failures.increment(); + logger.warn("Expired connect-scope cleanup step failed ({})", ex.getClass().getSimpleName()); + } + } +} 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 56f1696b35..29b6201f11 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 @@ -4,6 +4,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -24,6 +25,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; @@ -32,6 +37,9 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; @@ -41,12 +49,14 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -55,12 +65,20 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(AccountGrpcService.class); private static final int MAX_ACCOUNT_IDS_PER_REQUEST = 100; + private static final String AUTHORITY_UNAVAILABLE_MESSAGE = + "Account authority unavailable; retry later"; private final PingService pingService; private final AccountService accountService; private final MeterRegistry meterRegistry; + private final String workloadNamespace; public AccountGrpcService(PingService pingService, AccountService accountService) { - this(pingService, accountService, null); + this(pingService, accountService, null, null); + } + + public AccountGrpcService( + PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + this(pingService, accountService, meterRegistry, null); } @Autowired @@ -68,10 +86,177 @@ public AccountGrpcService(PingService pingService, AccountService accountService value = "EI_EXPOSE_REP2", justification = "Injected services and registry remain internal collaborators.") public AccountGrpcService( - PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + PingService pingService, + AccountService accountService, + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.pingService = pingService; this.accountService = accountService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; + } + + @Override + @Timed(value = "accountGrpc.issueDirectTextConnectScope") + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + IssueDirectTextConnectScopeResponse.Builder response = + IssueDirectTextConnectScopeResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID realmId = requireCanonicalRealmId(request.getRealmId()); + long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); + if (caller.tenantId() != tenantId + || !caller.realmId().equals(realmId) + || caller.gameInstanceId() != gameInstanceId + || !caller.playableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.playableStateScope().equals(request.getPlayableStateScope())) { + throw new InvalidRequestException("Player context and selected realm disagree", null); + } + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, + realmId, + requireText(request.getWorldSlug(), "worldSlug"), + requireText(request.getRealmSlug(), "realmSlug"), + requireText(request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireText(request.getPlayableStateScope(), "playableStateScope"), + gameInstanceId, + request.getCatalogRevision(), + request.getPointerVersion())); + response + .setConnectScopeId(scope.connectScopeId()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("IssueDirectTextConnectScope", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "INVALID_ARGUMENT", ex.getMessage())); + } catch (RuntimeException ignored) { + response.setError( + appError( + "IssueDirectTextConnectScope", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "accountGrpc.joinPublicProductionMembership") + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + JoinPublicProductionMembershipResponse.Builder response = + JoinPublicProductionMembershipResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + String requestId = requireText(request.getRequestId(), "requestId"); + if (requestId.length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { + throw new InvalidRequestException("JOIN requestId exceeds the maximum length", null); + } + if (!requestId.equals(caller.requestId())) { + throw new InvalidRequestException("Player context and JOIN request ID disagree", null); + } + var result = + accountService.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); + response + .setSuccess(result.success()) + .setOutcomeCode(result.outcomeCode()) + .setAccountId(Long.toString(result.accountId())) + .setTenantId(Long.toString(result.tenantId())) + .setMembershipId(Long.toString(result.membershipId())) + .setMembershipVersion(result.membershipVersion()) + .setMembershipAuthorityGeneration(result.membershipAuthorityGeneration()) + .setReplayed(result.replayed()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("JoinPublicProductionMembership", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("JoinPublicProductionMembership", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("JoinPublicProductionMembership", "INVALID_ARGUMENT", ex.getMessage())); + } catch (RuntimeException ignored) { + response.setError( + appError( + "JoinPublicProductionMembership", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service")) { + throw new AdminAuthorizationException("Verified Game Session workload identity is required"); + } + } + + private DirectTextCallerContext directTextCaller( + net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { + return new DirectTextCallerContext( + requirePositiveRequestId(context.getAccountId(), "accountId"), + requirePositiveRequestId(context.getTenantId(), "tenantId"), + requireCanonicalRealmId(context.getRealmId()), + requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()), + requireText(context.getPlayableStateScope(), "playableStateScope"), + requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), + requireText(context.getSessionId(), "sessionId"), + requireText(context.getRequestId(), "requestId")); + } + + private UUID requireCanonicalRealmId(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("realmId is required"); + } + try { + UUID realmId = UUID.fromString(value); + if (!realmId.toString().equals(value)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + + private String requireCanonicalPlayableStateNamespaceId(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + try { + UUID namespaceId = UUID.fromString(value); + if (!namespaceId.toString().equals(value)) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); + } + } + + private String requireText(String value, String fieldName) { + int maxLength = "connectScopeId".equals(fieldName) ? 2048 : 128; + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new InvalidRequestException(fieldName + " is required and bounded", null); + } + return value; } @Override @@ -90,10 +275,7 @@ public void createAccount( try { net.firedevops.firemud.accountservice.dto.CreateAccountRequest dto = new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getUsername(), - request.getEmail(), - request.getPassword()); + request.getUsername(), request.getEmail(), request.getPassword()); var account = accountService.createAccount(dto); CreateAccountResponse response = CreateAccountResponse.newBuilder().setAccountId(account.id().toString()).build(); @@ -222,6 +404,8 @@ public void getTenantMembershipForRuntime( .setMembershipExists(dto.membershipExists()) .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) .setMembershipVersion(dto.membershipVersion()) + .setMembershipLifecycleState(dto.membershipLifecycleState()) + .setMembershipAuthorityGeneration(dto.membershipAuthorityGeneration()) .setEvaluatedAt(dto.evaluatedAt()) .build(); responseObserver.onNext(response); 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 47d0b6147b..d843608e32 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 @@ -21,11 +21,11 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; 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.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -34,6 +34,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -45,6 +50,7 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -58,7 +64,11 @@ import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -76,9 +86,6 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.saga.SagaBuilder; -import net.firedevops.firemud.common.saga.SagaException; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; @@ -89,11 +96,16 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; +import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -107,8 +119,12 @@ public class AccountServiceImpl implements AccountService { private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private final AccountRepository accountRepository; + private final AccountAuditOutboxRepository accountAuditOutboxRepository; + private final AccountConnectScopeRepository accountConnectScopeRepository; + private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -125,18 +141,20 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; - private final LoggingAdminClient loggingAdminClient; private final GameSessionClient gameSessionClient; private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; - private final SagaRunner sagaRunner; + private final TransactionTemplate joinTransactionTemplate; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Dependencies are injected and kept internal") public AccountServiceImpl( AccountRepository accountRepository, + AccountAuditOutboxRepository accountAuditOutboxRepository, + AccountConnectScopeRepository accountConnectScopeRepository, + AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, @@ -153,13 +171,15 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, - LoggingAdminClient loggingAdminClient, GameSessionClient gameSessionClient, EntityManagementClient entityManagementClient, JwtUtil jwtUtil, net.firedevops.firemud.accountservice.service.session.SessionService sessionService, - SagaRunner sagaRunner) { + PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; + this.accountAuditOutboxRepository = accountAuditOutboxRepository; + this.accountConnectScopeRepository = accountConnectScopeRepository; + this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; @@ -176,65 +196,37 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; - this.loggingAdminClient = loggingAdminClient; this.gameSessionClient = gameSessionClient; this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; - this.sagaRunner = sagaRunner; + this.joinTransactionTemplate = new TransactionTemplate(transactionManager); + this.joinTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); } @Override @Transactional @Timed(value = "account.create") public AccountDto createAccount(CreateAccountRequest request) { - logger.info("Creating account {} for tenant {}", request.username(), request.tenantId()); + logger.info("Creating global account {}", request.username()); Account account = new Account(); account.setUsername(request.username()); account.setEmail(EmailCanonicalization.normalize(request.email())); account.setPasswordHash(hashPassword(request.password())); - account.setRole("player"); - Profile profile = new Profile(); - profile.setTenantId(request.tenantId()); - profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setTenantId(request.tenantId()); - membership.setGameplayAdmissionAllowed(true); - - SagaBuilder builder = new SagaBuilder("accountCreation"); - builder.step( - "persistAccount", - () -> { - Account saved; - try { - saved = accountRepository.save(account); - } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { - throw new AccountAlreadyExistsException(ex); - } - account.setId(saved.getId()); - membership.setAccount(saved); - accountTenantMembershipRepository.save(membership); - profile.setAccount(saved); - profileRepository.save(profile); - }, - () -> { - profileRepository.delete(profile); - accountTenantMembershipRepository.delete(membership); - accountRepository.delete(account); - }); - var saga = builder.build(); + Account saved; try { - sagaRunner.run(saga); - } catch (SagaException e) { - if (e.getCause() instanceof AccountAlreadyExistsException alreadyExists) { - throw alreadyExists; - } - logger.warn("Account creation saga failed", e); - throw new IllegalStateException("Account creation failed", e); + saved = accountRepository.save(account); + } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { + throw new AccountAlreadyExistsException(ex); } - runAfterCommit(() -> safeLogAccountCreation(request.tenantId(), account.getId())); - - return accountMapper.toDto(account); + accountAuditOutboxRepository.append( + UUID.randomUUID(), + "platform", + null, + "ACCOUNT_REGISTERED", + "{\"accountId\":" + saved.getId() + "}"); + return accountMapper.toDto(saved); } @Override @@ -396,33 +388,54 @@ public List listBootstrapWorlds(String bootstrapToken) { } @Override - @Transactional(readOnly = true) + @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); Map discoveryEntitlementMemo = new HashMap<>(); Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - return gameSessionClient.listGameplayRealms(worldSlug).stream() + final List admissibleRealms; + try { + admissibleRealms = + listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug, discoveryEntitlementMemo); + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + return admissibleRealms.stream() .map( - realm -> - readAdmissibleDiscoveryRealm(bootstrapContext, realm, discoveryEntitlementMemo)) - .flatMap(Optional::stream) + discovered -> { + RuntimeRealmTarget current = + requireRealmTarget( + discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); + if (!sameRuntimeRealmAuthority(discovered, current)) { + throw admissionPointerUnavailable( + new IllegalStateException( + "Public realm authority changed during bootstrap discovery")); + } + return current; + }) .map( realm -> new BootstrapRealmDto( realm.worldSlug(), realm.realmSlug(), + realm.realmId().toString(), realm.displayName(), realm.tenantId(), realm.gameInstanceId(), realm.pointerVersion(), + realm.catalogRevision(), + realm.playableStateNamespaceId(), + toPlayableStateScope(realm).name(), realm.requiresCharacterSelection(), realm.stateScope(), realm.characterCreationPolicy(), evaluatedAt.toString(), expiresAt.toString(), - mintConnectScopeId(bootstrapContext, realm, evaluatedAt, expiresAt))) + mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) .toList(); } @@ -456,6 +469,631 @@ public List listBootstrapCharacters( .toList(); } + @Override + @Timed(value = "account.public_production_join") + public JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request) { + BootstrapContext caller = requireBootstrapContext(bootstrapToken); + Claims callerClaims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + String callerBinding; + try { + callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request); + } + + @Override + @Transactional(propagation = Propagation.NOT_SUPPORTED) + @Timed(value = "account.direct_text_connect_scope") + public DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + if (caller == null + || target == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.requestId()) + || caller.tenantId() != target.tenantId() + || !caller.realmId().equals(target.realmId()) + || caller.gameInstanceId() != target.gameInstanceId() + || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !caller.playableStateScope().equals(target.playableStateScope())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + RuntimeRealmTarget current = + requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); + if (!isPublicProductionRealm(current)) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Selected public realm is unavailable"); + } + if (!current.realmId().equals(target.realmId()) + || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !current.stateScope().equals(target.playableStateScope()) + || current.gameInstanceId() != target.gameInstanceId() + || current.catalogRevision() != target.catalogRevision() + || current.pointerVersion() != target.pointerVersion()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + Instant evaluatedAt = Instant.now(); + Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + String scopeId = + mintAndRetainConnectScope( + new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + return new DirectTextJoinScope(scopeId, expiresAt.toString()); + } + + @Override + @Timed(value = "account.public_production_join_internal") + public JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request) { + if (caller == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.sessionId()) + || request == null + || !caller.requestId().equals(request.requestId())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return joinPublicProductionForTrustedCaller( + caller.accountId(), caller.sessionId(), caller, request); + } + + private JoinPublicProductionResult joinPublicProductionForTrustedCaller( + long accountId, + String callerBinding, + DirectTextCallerContext directTextCaller, + JoinPublicProductionRequest request) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { + throw new AuthenticationException( + "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); + } + String requestId = request.requestId(); + String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); + Optional existing = accountJoinOperationRepository.find(requestId); + VerifiedJoinScope retained; + if (existing.isPresent()) { + JoinOperation operation = existing.orElseThrow(); + if (operation.accountId() != accountId + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(scopeTokenHash)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + } else { + ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + validateSignedJoinScope(signedScope, retained, accountId); + String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); + try { + joinTransactionTemplate.execute( + transactionStatus -> + accountJoinOperationRepository.insertIntent( + requestId, retained, callerBinding, intentDigest)); + } catch (RuntimeException ex) { + Optional claimReadback = safeFindJoinOperation(requestId); + if (claimReadback.isEmpty()) { + if (connectScopeEvidenceIsMissing(request.connectScopeId())) { + throw new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable", ex); + } + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); + } + requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); + } + JoinOperation claimed = + accountJoinOperationRepository + .find(requestId) + .orElseThrow( + () -> + new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); + requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); + } + + try { + JoinAttemptOutcome outcome = + joinTransactionTemplate.execute( + transactionStatus -> + executeJoinAttempt(accountId, callerBinding, requestId, retained)); + if (outcome.terminalOperation() != null) { + return replayTerminalJoinSafely(outcome.terminalOperation(), callerBinding, retained); + } + return outcome.result(); + } catch (AuthenticationException ex) { + if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { + throw ex; + } + recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); + return pendingJoinFailure(retained, ex.getCode()); + } catch (RuntimeException ex) { + Optional outcomeReadback = safeFindJoinOperation(requestId); + if (outcomeReadback.isPresent()) { + JoinOperation operation = outcomeReadback.orElseThrow(); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + if (!"PENDING".equals(operation.status())) { + return replayTerminalJoinSafely(operation, callerBinding, retained); + } + recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); + } + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); + } + } + + private JoinAttemptOutcome executeJoinAttempt( + long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { + accountJoinOperationRepository.lockAccount(accountId); + JoinOperation operation = + accountJoinOperationRepository + .findForUpdate(requestId) + .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); + requireMatchingJoinIntent(operation, requestId, callerBinding, scope); + + if (!"PENDING".equals(operation.status())) { + return JoinAttemptOutcome.terminal(operation); + } + return JoinAttemptOutcome.result( + executePendingJoinAttempt(accountId, callerBinding, requestId, scope, operation)); + } + + private JoinPublicProductionResult executePendingJoinAttempt( + long accountId, + String callerBinding, + String requestId, + VerifiedJoinScope scope, + JoinOperation operation) { + if (isConnectScopeExpired(scope)) { + return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + } + + JoinEvaluation evaluation = evaluateJoin(scope, false); + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), evaluation.failureCode()); + return pendingJoinFailure(scope, evaluation.failureCode()); + } + return failedJoin(requestId, scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String requestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (operation.requestDigest() != null + && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(requestDigest))) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (operation.requestDigest() == null) { + accountJoinOperationRepository.bindPolicyEvidence( + requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); + } + if (!evaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!evaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + + JoinEvaluation commitEvaluation = evaluateJoin(scope, true); + if (commitEvaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(commitEvaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); + return pendingJoinFailure(scope, commitEvaluation.failureCode()); + } + return failedJoin(requestId, scope, commitEvaluation.failureCode()); + } + if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String commitDigest = + AccountJoinDigest.request( + scope, + callerBinding, + commitEvaluation.allowPublicJoin(), + commitEvaluation.entitlementVersion()); + if (!requestDigest.equals(commitDigest)) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (!commitEvaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!commitEvaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(accountId, scope.tenantId()) + .orElse(null); + boolean transitioned = false; + if (membership == null) { + membership = new AccountTenantMembership(); + membership.setAccount(requireAccount(accountId)); + membership.setTenantId(scope.tenantId()); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(membership.getMembershipVersion() + 1L); + membership.setMembershipAuthorityGeneration( + membership.getMembershipAuthorityGeneration() + 1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed()) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + if (transitioned) { + String payload = + AUDIT_JSON.writeValueAsString( + new JoinAuditPayload( + accountId, + scope.tenantId(), + scope.worldSlug(), + scope.realmSlug(), + membership.getMembershipVersion(), + requestId)); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + accountAuditOutboxRepository.append( + auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); + } + accountJoinOperationRepository.finish( + requestId, + "COMMITTED", + transitioned ? "JOINED" : "ALREADY_ACTIVE", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + return new JoinPublicProductionResult( + true, + transitioned ? "JOINED" : "ALREADY_ACTIVE", + accountId, + scope.tenantId(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + false); + } + + private JoinPublicProductionResult failedJoin( + String requestId, VerifiedJoinScope scope, String outcomeCode) { + accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private JoinPublicProductionResult pendingJoinFailure( + VerifiedJoinScope scope, String outcomeCode) { + return joinRetryFailure(scope, outcomeCode); + } + + private JoinPublicProductionResult replayTerminalJoin( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + if (isConnectScopeExpired(scope)) { + return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); + } + + boolean replayUnboundFailure = + "FAILED".equals(operation.status()) && operation.requestDigest() == null; + + JoinEvaluation evaluation; + try { + evaluation = evaluateJoin(scope); + } catch (RuntimeException ex) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + return joinRetryFailure(scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + if (replayUnboundFailure) { + return resultFromJoinOperation(operation, true); + } + + String currentRequestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || operation.requestDigest() == null + || operation.allowPublicJoin() == null + || !operation.allowPublicJoin().equals(evaluation.allowPublicJoin()) + || operation.entitlementVersion() == null + || !operation.entitlementVersion().equals(evaluation.entitlementVersion()) + || !operation.requestDigest().equals(currentRequestDigest) + || ("COMMITTED".equals(operation.status()) + && (!evaluation.gameplayAvailable() || !evaluation.allowPublicJoin()))) { + return joinRetryFailure(scope, "IDEMPOTENCY_CONFLICT"); + } + return resultFromJoinOperation(operation, true); + } + + private JoinPublicProductionResult replayTerminalJoinSafely( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + try { + return replayTerminalJoin(operation, callerBinding, scope); + } catch (RuntimeException policyCheckFailure) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + } + + private JoinPublicProductionResult joinRetryFailure(VerifiedJoinScope scope, String outcomeCode) { + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private boolean isConnectScopeExpired(VerifiedJoinScope scope) { + try { + return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); + } catch (RuntimeException ex) { + return true; + } + } + + private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { + return "UNAVAILABLE".equals(evaluation.authorityAvailability()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) + || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) + || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); + } + + private VerifiedJoinScope retainedJoinScope(String connectScopeId) { + return accountConnectScopeRepository + .find(connectScopeId) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + } + + private boolean connectScopeEvidenceIsMissing(String connectScopeId) { + try { + return accountConnectScopeRepository.find(connectScopeId).isEmpty(); + } catch (RuntimeException ex) { + return false; + } + } + + private void validateSignedJoinScope( + ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { + if (retained.accountId() != accountId + || signedScope.accountId() != accountId + || signedScope.tenantId() != retained.tenantId() + || !signedScope.realmId().equals(retained.realmId()) + || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || !signedScope.playableStateScope().equals(retained.playableStateScope()) + || signedScope.gameInstanceId() != retained.gameInstanceId() + || signedScope.catalogRevision() != retained.catalogRevision() + || signedScope.pointerVersion() != retained.pointerVersion() + || !signedScope.worldSlug().equals(retained.worldSlug()) + || !signedScope.realmSlug().equals(retained.realmSlug()) + || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) + || !signedScope + .connectScopeExpiresAt() + .toString() + .equals(retained.connectScopeExpiresAt())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private void requireMatchingJoinIntent( + JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { + String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + if (operation.accountId() != scope.accountId() + || !operation.realmId().equals(scope.realmId()) + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) + || !operation.connectScopeDigest().equals(scope.snapshotDigest()) + || operation.intentDigestVersion() != 1 + || !operation.intentDigest().equals(expectedIntentDigest)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + } + + private JoinPublicProductionResult resultFromJoinOperation( + JoinOperation operation, boolean replayed) { + return new JoinPublicProductionResult( + "COMMITTED".equals(operation.status()), + operation.outcome(), + operation.accountId(), + operation.tenantId(), + operation.membershipId() == null ? 0L : operation.membershipId(), + operation.membershipVersion() == null ? 0L : operation.membershipVersion(), + operation.membershipAuthorityGeneration() == null + ? 0L + : operation.membershipAuthorityGeneration(), + replayed); + } + + private Optional safeFindJoinOperation(String requestId) { + try { + return accountJoinOperationRepository.find(requestId); + } catch (RuntimeException ignored) { + return Optional.empty(); + } + } + + private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { + String availability = + "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + try { + joinTransactionTemplate.execute( + transactionStatus -> { + accountJoinOperationRepository + .findForUpdate(requestId) + .ifPresent( + operation -> { + if ("PENDING".equals(operation.status())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, availability, failureCode); + } + }); + return null; + }); + } catch (RuntimeException ignored) { + // The durable intent stays pending, and the caller retries the same request ID. + } + } + + private void validateDirectTextJoinScope( + DirectTextCallerContext caller, VerifiedJoinScope scope) { + if (caller != null + && (caller.accountId() != scope.accountId() + || caller.tenantId() != scope.tenantId() + || !caller.realmId().equals(scope.realmId()) + || caller.gameInstanceId() != scope.gameInstanceId() + || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !caller.playableStateScope().equals(scope.playableStateScope()))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { + return evaluateJoin(scope, true); + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitlement) { + return evaluateJoin( + new ConnectScopeContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + Instant.parse(scope.evaluatedAt()), + Instant.parse(scope.connectScopeExpiresAt())), + lockEntitlement); + } + + private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntitlement) { + RuntimeRealmTarget target; + try { + target = requireCurrentConnectScopeTarget(scope); + } catch (AuthenticationException ex) { + if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); + } + throw ex; + } + if (!isPublicProductionRealm(target)) { + return new JoinEvaluation( + "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + try { + RuntimeEntitlementsDto entitlement = joinEntitlement(scope.tenantId(), lockEntitlement); + return new JoinEvaluation( + "AVAILABLE", + entitlement.allowPublicJoin(), + entitlement.entitlementVersion(), + entitlement.gameplayAvailable(), + null); + } catch (AuthenticationException ex) { + if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); + } + throw ex; + } + } + + private record JoinEvaluation( + String authorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + boolean gameplayAvailable, + String failureCode) {} + + private record JoinAttemptOutcome( + JoinPublicProductionResult result, JoinOperation terminalOperation) { + private static JoinAttemptOutcome result(JoinPublicProductionResult result) { + return new JoinAttemptOutcome(result, null); + } + + private static JoinAttemptOutcome terminal(JoinOperation operation) { + return new JoinAttemptOutcome(null, operation); + } + } + + private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { + List rows = + lockSubscription + ? subscriptionRepository.findByTenantIdForUpdate(tenantId) + : subscriptionRepository.findByTenantId(tenantId); + if (rows.size() != 1) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); + } + var subscription = rows.getFirst(); + if (subscription.getEntitlementVersion() <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); + } + return new RuntimeEntitlementsDto( + tenantId, + isGameplayAvailableStatus(subscription.getStatus()), + isPublicJoinAllowedStatus(subscription.getStatus()), + subscription.getEntitlementVersion(), + subscription.getEntitlementVersion(), + Instant.now().toString()); + } + @Override @Transactional(readOnly = true) @Timed(value = "account.connect_token") @@ -526,6 +1164,23 @@ private ConnectTokenResult issueConnectTokenFresh( getTenantMembershipForRuntime( bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && isPublicProductionRealm(realm)) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); @@ -634,7 +1289,9 @@ public RuntimeMembershipDto getTenantMembershipForRuntime( tenantId, membership.isPresent(), membership.map(AccountTenantMembership::isGameplayAdmissionAllowed).orElse(false), - membership.map(AccountTenantMembership::getId).orElse(0L), + membership.map(AccountTenantMembership::getMembershipVersion).orElse(0L), + membership.map(AccountTenantMembership::getLifecycleState).orElse("MISSING"), + membership.map(AccountTenantMembership::getMembershipAuthorityGeneration).orElse(0L), Instant.now().toString()); } @@ -730,7 +1387,7 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str subscriptions.getFirst(); boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); - long version = subscription.getId() == null ? 0L : subscription.getId(); + long version = subscription.getEntitlementVersion(); return new RuntimeEntitlementsDto( tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); } @@ -760,7 +1417,14 @@ private RuntimeRealmTarget requireAdmissibleRealm( String worldSlug, String realmSlug) { RuntimeRealmTarget realm = requireRealmTarget(expectedTenantId, worldSlug, realmSlug); - if (!isRealmAdmissible(bootstrapContext, realm)) { + if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(realm.tenantId(), "bootstrap-selected-target"); + if (!entitlements.gameplayAvailable()) { throw new AuthenticationException( "ADMISSION_POINTER_UNAVAILABLE", "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); @@ -772,10 +1436,9 @@ private RuntimeRealmTarget requireRealmTarget( Long expectedTenantId, String worldSlug, String realmSlug) { try { List candidates = - gameSessionClient.listGameplayRealms(worldSlug).stream() - .filter(realm -> java.util.Objects.equals(worldSlug, realm.getWorldSlug())) - .filter(realm -> java.util.Objects.equals(realmSlug, realm.getRealmSlug())) - .map(this::readRuntimeRealmTarget) + listRuntimeRealmTargets(worldSlug, realmSlug).stream() + .filter(realm -> java.util.Objects.equals(worldSlug, realm.worldSlug())) + .filter(realm -> java.util.Objects.equals(realmSlug, realm.realmSlug())) .filter(realm -> expectedTenantId == null || realm.tenantId() == expectedTenantId) .toList(); if (candidates.size() != 1) { @@ -786,6 +1449,14 @@ private RuntimeRealmTarget requireRealmTarget( readRuntimeRealmTarget( gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); if (realm.tenantId() != candidate.tenantId() + || !realm.realmId().equals(candidate.realmId()) + || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) + || !realm.stateScope().equals(candidate.stateScope()) + || realm.gameInstanceId() != candidate.gameInstanceId() + || realm.visible() != candidate.visible() + || realm.publicProductionRealm() != candidate.publicProductionRealm() + || realm.catalogRevision() != candidate.catalogRevision() + || realm.pointerVersion() != candidate.pointerVersion() || !java.util.Objects.equals(worldSlug, realm.worldSlug()) || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { throw new AuthenticationException( @@ -793,11 +1464,10 @@ private RuntimeRealmTarget requireRealmTarget( "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); } return realm; - } catch (IllegalArgumentException | IllegalStateException ex) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - ex); + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); } } @@ -806,22 +1476,87 @@ private boolean hasAdmissibleRealm( String worldSlug, Map discoveryEntitlementMemo) { try { - return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map( - realm -> - readAdmissibleDiscoveryRealm(bootstrapContext, realm, discoveryEntitlementMemo)) - .flatMap(Optional::stream) - .findAny() - .isPresent(); + return !listAdmissibleRuntimeRealmTargets( + bootstrapContext, worldSlug, discoveryEntitlementMemo) + .isEmpty(); } catch (IllegalStateException ex) { return false; } } - private Optional readAdmissibleDiscoveryRealm( + private List listAdmissibleRuntimeRealmTargets( BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm, + String worldSlug, Map discoveryEntitlementMemo) { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + List targets = + realms.stream() + .map(realm -> readReachableDiscoveryRealm(bootstrapContext, realm)) + .flatMap(Optional::stream) + .toList(); + validatePublicRealmCardinality(targets); + return targets.stream() + .filter( + realm -> isDiscoveryRealmAdmissible(bootstrapContext, realm, discoveryEntitlementMemo)) + .toList(); + } + + private List listRuntimeRealmTargets( + String worldSlug, String selectedRealmSlug) { + try { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + var realmStream = realms.stream(); + if (selectedRealmSlug != null) { + realmStream = + realmStream.filter( + realm -> + realm != null + && java.util.Objects.equals(selectedRealmSlug, realm.getRealmSlug())); + } + List targets = realmStream.map(this::readRuntimeRealmTarget).toList(); + validatePublicRealmCardinality(targets); + return targets; + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + } + + private void validatePublicRealmCardinality(List realms) { + // The RPC is world-local: zero local public realms may be a valid private-only world when the + // tenant's public realm is in another world. Game Session owns the tenant-global zero check; + // Account can defensively reject only duplicate visible public targets returned here. + Map visiblePublicRealmCounts = + realms.stream() + .filter(this::isPublicProductionRealm) + .collect( + java.util.stream.Collectors.groupingBy( + RuntimeRealmTarget::tenantId, java.util.stream.Collectors.counting())); + if (realms.stream() + .map(RuntimeRealmTarget::tenantId) + .distinct() + .anyMatch(tenantId -> visiblePublicRealmCounts.getOrDefault(tenantId, 0L) > 1L)) { + throw admissionPointerUnavailable( + new IllegalStateException("Public production realm authority is ambiguous")); + } + } + + private Optional readReachableDiscoveryRealm( + BootstrapContext bootstrapContext, + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + if (realm == null) { + throw admissionPointerUnavailable( + new IllegalArgumentException("Gameplay realm discovery returned a null realm")); + } final RuntimeRealmTarget target; try { target = readRuntimeRealmTarget(realm); @@ -831,9 +1566,7 @@ private Optional readAdmissibleDiscoveryRealm( } return Optional.empty(); } - return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) - ? Optional.of(target) - : Optional.empty(); + return Optional.of(target); } private boolean isMalformedRealmReachable( @@ -869,16 +1602,6 @@ private AuthenticationException admissionPointerUnavailable(Throwable cause) { cause); } - private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { - long tenantId = realm.tenantId(); - if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { - return false; - } - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery"); - return entitlements.gameplayAvailable(); - } - private boolean isDiscoveryRealmAdmissible( BootstrapContext bootstrapContext, RuntimeRealmTarget realm, @@ -915,6 +1638,23 @@ private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { return realm.visible() && realm.publicProductionRealm(); } + private boolean sameRuntimeRealmAuthority( + RuntimeRealmTarget expected, RuntimeRealmTarget actual) { + return expected.tenantId() == actual.tenantId() + && expected.realmId().equals(actual.realmId()) + && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + && expected.gameInstanceId() == actual.gameInstanceId() + && expected.worldSlug().equals(actual.worldSlug()) + && expected.realmSlug().equals(actual.realmSlug()) + && expected.pointerVersion() == actual.pointerVersion() + && expected.catalogRevision() == actual.catalogRevision() + && expected.visible() == actual.visible() + && expected.publicProductionRealm() == actual.publicProductionRealm() + && expected.stateScope().equals(actual.stateScope()) + && expected.characterCreationPolicy().equals(actual.characterCreationPolicy()) + && expected.requiresCharacterSelection() == actual.requiresCharacterSelection(); + } + private String mintConnectScopeId( BootstrapContext bootstrapContext, RuntimeRealmTarget realm, @@ -924,34 +1664,70 @@ private String mintConnectScopeId( return mintToken( String.valueOf(bootstrapContext.accountId()), expirationMs, - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - bootstrapContext.accountId(), - "tenantId", - realm.tenantId(), - "worldSlug", - realm.worldSlug(), - "realmSlug", - realm.realmSlug(), - "gameInstanceId", - realm.gameInstanceId(), - "pointerVersion", - realm.pointerVersion(), - "evaluatedAt", - evaluatedAt.toString(), - "connectScopeExpiresAt", - expiresAt.toString(), - "jti", - stableId( - "connect-scope", - bootstrapContext.accountId(), - Long.toString(realm.tenantId()), - realm.worldSlug(), - realm.realmSlug(), - realm.pointerVersion(), - evaluatedAt.toString()))); + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("tenantId", realm.tenantId()), + Map.entry("realmId", realm.realmId().toString()), + Map.entry("worldSlug", realm.worldSlug()), + Map.entry("realmSlug", realm.realmSlug()), + Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), + Map.entry("playableStateScope", realm.stateScope()), + Map.entry("gameInstanceId", realm.gameInstanceId()), + Map.entry("catalogRevision", realm.catalogRevision()), + Map.entry("pointerVersion", realm.pointerVersion()), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()), + Map.entry( + "jti", + stableId( + "connect-scope", + bootstrapContext.accountId(), + Long.toString(realm.tenantId()), + realm.worldSlug(), + realm.realmSlug(), + realm.pointerVersion(), + evaluatedAt.toString())))); + } + + private String mintAndRetainConnectScope( + BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); + if (isPublicProductionRealm(realm)) { + VerifiedJoinScope pending = + new VerifiedJoinScope( + connectScopeId, + caller.accountId(), + realm.tenantId(), + realm.realmId(), + realm.worldSlug(), + realm.realmSlug(), + realm.playableStateNamespaceId(), + realm.stateScope(), + realm.gameInstanceId(), + realm.catalogRevision(), + realm.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString(), + ""); + accountConnectScopeRepository.insert( + new VerifiedJoinScope( + pending.connectScopeId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.evaluatedAt(), + pending.connectScopeExpiresAt(), + AccountJoinDigest.scope(pending))); + } + return connectScopeId; } private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { @@ -967,16 +1743,25 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { JwtClaims.requireSignedGameplayRoutingClaims( claims, "signed token account subject mismatch"); Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); + Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); if (connectScopeExpiresAt == null) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } + if (evaluatedAt == null) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } return new ConnectScopeContext( routingClaims.accountId(), routingClaims.tenantId(), + requireCanonicalRealmId(claims.get("realmId")), routingClaims.worldSlug(), routingClaims.realmSlug(), + JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), + JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"), routingClaims.gameInstanceId(), + requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"), routingClaims.pointerVersion(), + evaluatedAt, connectScopeExpiresAt); } catch (IllegalArgumentException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); @@ -1032,7 +1817,11 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext requireRealmTarget( scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); if (currentRealm.tenantId() != scopeContext.tenantId() + || !currentRealm.realmId().equals(scopeContext.realmId()) + || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) + || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() + || currentRealm.catalogRevision() != scopeContext.catalogRevision() || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } @@ -1053,6 +1842,16 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( Optional maybeMembership = accountTenantMembershipRepository.findByAccountIdAndTenantId( bootstrapContext.accountId(), currentRealm.tenantId()); + if (maybeMembership.isPresent() + && "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()) + && publicProductionRealm) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); + } if (maybeMembership.isPresent() && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { throw new AuthenticationException( @@ -1196,13 +1995,17 @@ private String mintToken(String subject, long expirationMs, Map } private Map authenticationTokenClaims(String audience, Account account) { + List globalRoles = + account.getRole() == null || account.getRole().isBlank() + ? List.of() + : List.of(account.getRole()); return Map.of( "aud", audience, "accountId", account.getId(), "globalRoles", - List.of(account.getRole()), + globalRoles, "jti", UUID.randomUUID().toString()); } @@ -1257,14 +2060,6 @@ private boolean isPublicJoinAllowedStatus(String status) { }; } - private void safeLogAccountCreation(Long tenantId, Long accountId) { - try { - loggingAdminClient.logAccountCreation(tenantId, accountId); - } catch (RuntimeException ex) { - logger.warn("Account creation logging failed for account {}", accountId, ex); - } - } - @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -1375,6 +2170,11 @@ public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { @Timed(value = "account.delete") public void deleteAccount(Long accountId) { Account account = requireAccount(accountId); + if (accountJoinOperationRepository.hasRetainedOperation(accountId)) { + throw new AccountLifecycleException( + "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", + "Account JOIN receipts require retention and deletion reconciliation"); + } List subscriptions = subscriptionRepository.findByAccountId(accountId); Optional blockingSubscription = @@ -1638,6 +2438,14 @@ public void afterCommit() { private record BootstrapContext(long accountId) {} + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} + private ConnectTokenResult replayedConnectTokenResult(ConnectTokenResult result) { return new ConnectTokenResult( result.accountId(), @@ -1657,7 +2465,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1673,7 +2484,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1687,7 +2501,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( private RuntimeRealmTarget buildRuntimeRealmTarget( String tenantIdText, + String realmIdText, + String playableStateNamespaceId, String gameInstanceIdText, + long catalogRevision, long pointerVersion, String worldSlug, String realmSlug, @@ -1698,7 +2515,13 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( boolean requiresCharacterSelection, String displayName) { long tenantId = requirePositiveLong(tenantIdText, "tenantId"); + UUID realmId = requireCanonicalRealmId(realmIdText); long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); + String canonicalPlayableStateNamespaceId = + requireCanonicalPlayableStateNamespaceId(playableStateNamespaceId); + if (catalogRevision <= 0) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } if (pointerVersion <= 0) { throw new IllegalArgumentException("pointerVersion must be positive"); } @@ -1713,10 +2536,13 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( } return new RuntimeRealmTarget( tenantId, + realmId, + canonicalPlayableStateNamespaceId, gameInstanceId, worldSlug, realmSlug, pointerVersion, + catalogRevision, visible, publicProductionRealm, stateScope, @@ -1739,21 +2565,59 @@ private long requirePositiveLong(Object value, String field) { return JwtClaims.requireLong(value, field, false); } + private UUID requireCanonicalRealmId(Object value) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + try { + UUID realmId = UUID.fromString(text); + if (!realmId.toString().equals(text)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + + private String requireCanonicalPlayableStateNamespaceId(String value) { + if (!StringUtils.hasText(value)) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + try { + UUID namespaceId = UUID.fromString(value); + if (!namespaceId.toString().equals(value)) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); + } + } + private record ConnectScopeContext( long accountId, long tenantId, + UUID realmId, String worldSlug, String realmSlug, + String playableStateNamespaceId, + String playableStateScope, long gameInstanceId, + long catalogRevision, long pointerVersion, + Instant evaluatedAt, Instant connectScopeExpiresAt) {} private record RuntimeRealmTarget( long tenantId, + UUID realmId, + String playableStateNamespaceId, long gameInstanceId, String worldSlug, String realmSlug, long pointerVersion, + long catalogRevision, boolean visible, boolean publicProductionRealm, String stateScope, diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 8ff9882a2d..a0058cdd88 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -74,6 +74,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} @@ -83,6 +85,10 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + connect-scopes: + cleanup: + batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} + interval-ms: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_INTERVAL_MS:60000} tokens: session-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS:3600000} player-bootstrap-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS:300000} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 14e509c126..526520c5d0 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -45,6 +45,10 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + connect-scopes: + cleanup: + batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} + interval-ms: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_INTERVAL_MS:60000} tokens: session-expiration-ms: 3600000 player-bootstrap-expiration-ms: 300000 @@ -96,6 +100,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql new file mode 100644 index 0000000000..7a9d11b724 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -0,0 +1,270 @@ +-- The legacy tenant column is retained as source evidence. New global accounts +-- must not silently acquire tenant 1 through the V3 default. +CREATE TABLE account_legacy_tenant_sources ( + account_id BIGINT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, + legacy_tenant_id BIGINT NOT NULL, + matching_membership_id BIGINT, + matching_membership_admission_allowed BOOLEAN, + profile_tenant_count BIGINT NOT NULL, + matching_profile_count BIGINT NOT NULL, + disposition VARCHAR(32) NOT NULL, + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_tenant_sources_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'TENANT_MISMATCH', 'CONFLICT')) +); + +INSERT INTO account_legacy_tenant_sources ( + account_id, + legacy_tenant_id, + matching_membership_id, + matching_membership_admission_allowed, + profile_tenant_count, + matching_profile_count, + disposition +) +SELECT a.id, + a.tenant_id, + m.id, + m.gameplay_admission_allowed, + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id), + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id AND p.tenant_id = a.tenant_id), + CASE + WHEN EXISTS ( + SELECT 1 FROM account_tenant_membership other + WHERE other.account_id = a.id AND other.tenant_id <> a.tenant_id + ) OR EXISTS ( + SELECT 1 FROM profiles p + WHERE p.account_id = a.id AND p.tenant_id <> a.tenant_id + ) THEN 'TENANT_MISMATCH' + WHEN m.id IS NULL THEN 'CONFLICT' + ELSE 'UNVERIFIED' + END +FROM accounts a +LEFT JOIN account_tenant_membership m + ON m.account_id = a.id AND m.tenant_id = a.tenant_id; + +CREATE TABLE account_legacy_membership_sources ( + membership_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + original_gameplay_admission_allowed BOOLEAN NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_membership_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_membership_sources ( + membership_id, account_id, tenant_id, original_gameplay_admission_allowed, + matches_account_legacy_tenant +) +SELECT m.id, m.account_id, m.tenant_id, m.gameplay_admission_allowed, + m.tenant_id = a.tenant_id +FROM account_tenant_membership m +JOIN accounts a ON a.id = m.account_id; + +CREATE TABLE account_legacy_profile_sources ( + profile_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_profile_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_profile_sources ( + profile_id, account_id, tenant_id, matches_account_legacy_tenant +) +SELECT p.id, p.account_id, p.tenant_id, p.tenant_id = a.tenant_id +FROM profiles p +JOIN accounts a ON a.id = p.account_id; + +ALTER TABLE accounts ALTER COLUMN tenant_id DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN tenant_id DROP NOT NULL; +ALTER TABLE accounts ALTER COLUMN role DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN role DROP NOT NULL; + +-- A subscription row ID is not a policy revision. Retained policy begins at +-- version one and supported writers advance the monotonic value. +ALTER TABLE subscription ADD COLUMN entitlement_version BIGINT NOT NULL DEFAULT 1; +ALTER TABLE subscription ADD CONSTRAINT subscription_entitlement_version_positive + CHECK (entitlement_version > 0); + +-- No pre-JOIN writer proves player intent. Retain every old membership row, +-- but quarantine its authority until an explicit reconciliation disposition. +ALTER TABLE account_tenant_membership + ADD COLUMN lifecycle_state VARCHAR(32), + ADD COLUMN membership_version BIGINT, + ADD COLUMN membership_authority_generation BIGINT, + ADD COLUMN authority_provenance VARCHAR(32); + +UPDATE account_tenant_membership +SET lifecycle_state = 'LEGACY_UNVERIFIED', + membership_version = 1, + membership_authority_generation = 1, + authority_provenance = 'LEGACY_UNVERIFIED', + gameplay_admission_allowed = FALSE; + +ALTER TABLE account_tenant_membership ALTER COLUMN lifecycle_state SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_version SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_authority_generation SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN authority_provenance SET NOT NULL; +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_lifecycle_check + CHECK (lifecycle_state IN ('ACTIVE', 'INACTIVE', 'LEGACY_UNVERIFIED')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_provenance_check + CHECK (authority_provenance IN ('EXPLICIT_JOIN', 'LEGACY_UNVERIFIED', 'SEEDED_DEMO')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_versions_positive_check + CHECK (membership_version > 0 AND membership_authority_generation > 0); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_unverified_not_admitting_check + CHECK (lifecycle_state <> 'LEGACY_UNVERIFIED' OR gameplay_admission_allowed = FALSE); + +CREATE TABLE account_connect_scope_records ( + scope_token_hash VARCHAR(71) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + target_class VARCHAR(20) NOT NULL, + tenant_id BIGINT NOT NULL, + realm_id UUID NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + evaluated_at VARCHAR(40) NOT NULL, + connect_scope_expires_at VARCHAR(40) NOT NULL, + playtest_lifecycle_id VARCHAR(128), + playtest_state_generation BIGINT, + snapshot_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_connect_scope_target_check + CHECK ((target_class = 'PUBLIC_PRODUCTION' + AND playtest_lifecycle_id IS NULL AND playtest_state_generation IS NULL) + OR (target_class = 'NON_PUBLIC' + AND playtest_lifecycle_id IS NOT NULL AND playtest_state_generation > 0)), + CONSTRAINT account_connect_scope_positive_check + CHECK (tenant_id > 0 AND game_instance_id > 0 + AND catalog_revision > 0 AND pointer_version > 0) +); + +CREATE INDEX idx_account_connect_scope_account_expiry + ON account_connect_scope_records(account_id, connect_scope_expires_at); + +CREATE TABLE account_join_operations ( + request_id VARCHAR(128) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id), + tenant_id BIGINT NOT NULL, + verified_caller_binding VARCHAR(128) NOT NULL, + scope_token_hash VARCHAR(71) NOT NULL, + connect_scope_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + realm_id UUID NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + intent_digest_version INTEGER NOT NULL, + intent_digest VARCHAR(71) NOT NULL, + entitlement_version BIGINT, + allow_public_join BOOLEAN, + entitlement_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', + caller_bound_authority_invalidated BOOLEAN NOT NULL, + request_digest_version INTEGER, + request_digest VARCHAR(71), + last_attempt_failure_code VARCHAR(64), + last_attempt_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', + status VARCHAR(16) NOT NULL, + outcome VARCHAR(64), + membership_id BIGINT REFERENCES account_tenant_membership(id), + outcome_membership_version BIGINT, + outcome_membership_authority_generation BIGINT, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_join_operation_status_check + CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED')), + CONSTRAINT account_join_operation_positive_versions_check + CHECK (tenant_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 + AND pointer_version > 0 + AND (entitlement_version IS NULL OR entitlement_version > 0)), + CONSTRAINT account_join_operation_policy_evidence_check + CHECK ((entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL) + OR (entitlement_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND entitlement_version IS NULL AND allow_public_join IS NULL)), + CONSTRAINT account_join_last_attempt_availability_check + CHECK (last_attempt_authority_availability IN ('AVAILABLE', 'UNAVAILABLE', 'NOT_EVALUATED')), + CONSTRAINT account_join_intent_digest_version_check + CHECK (intent_digest_version = 1 AND length(intent_digest) = 71 + AND intent_digest LIKE 'sha256:%'), + CONSTRAINT account_join_policy_digest_check + CHECK ((request_digest_version IS NULL AND request_digest IS NULL + AND entitlement_authority_availability <> 'AVAILABLE' + AND entitlement_version IS NULL AND allow_public_join IS NULL) + OR (request_digest_version = 1 AND request_digest IS NOT NULL + AND length(request_digest) = 71 AND request_digest LIKE 'sha256:%' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL)), + CONSTRAINT account_join_outcome_state_check + CHECK ((status = 'PENDING' AND outcome IS NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome IS NOT NULL + AND membership_id IS NOT NULL + AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL)), + CONSTRAINT account_join_pending_attempt_failure_check + CHECK (last_attempt_failure_code IS NULL + OR (status = 'PENDING' AND btrim(last_attempt_failure_code) <> '')), + CONSTRAINT account_join_committed_policy_check + CHECK (status <> 'COMMITTED' OR (entitlement_version IS NOT NULL + AND entitlement_version > 0 AND allow_public_join = TRUE + AND membership_id IS NOT NULL AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0)) +); + +CREATE INDEX idx_account_join_operations_account_tenant + ON account_join_operations(account_id, tenant_id); + +CREATE TABLE account_audit_outbox ( + audit_event_id UUID PRIMARY KEY, + scope VARCHAR(8) NOT NULL, + tenant_id BIGINT, + producer_service VARCHAR(64) NOT NULL, + event_type VARCHAR(64) NOT NULL, + occurred_at TIMESTAMP NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest VARCHAR(71) NOT NULL, + payload TEXT, + receiver_receipt_id VARCHAR(128), + receiver_log_event_id VARCHAR(128), + delivery_status VARCHAR(32) NOT NULL DEFAULT 'PENDING', + last_attempt_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_audit_outbox_scope_check + CHECK ((scope = 'platform' AND tenant_id IS NULL) + OR (scope = 'tenant' AND tenant_id > 0)), + CONSTRAINT account_audit_outbox_version_check + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT account_audit_outbox_delivery_check + CHECK (delivery_status IN ('PENDING', 'COMMITTED', 'MINIMIZED')), + CONSTRAINT account_audit_outbox_payload_state_check + CHECK ((delivery_status = 'MINIMIZED' AND payload IS NULL) + OR (delivery_status IN ('PENDING', 'COMMITTED') AND payload IS NOT NULL)) +); + +CREATE INDEX idx_account_audit_outbox_pending + ON account_audit_outbox(created_at, audit_event_id) + WHERE delivery_status = 'PENDING'; diff --git a/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql b/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql new file mode 100644 index 0000000000..000416cd86 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql @@ -0,0 +1,10 @@ +-- JOIN operation rows are durable replay evidence and always depend on the exact scope snapshot. +-- Restrictive FK semantics serialize scope reclamation against concurrent intent insertion. +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_scope_reference_fk + FOREIGN KEY (scope_token_hash) + REFERENCES account_connect_scope_records(scope_token_hash) + ON DELETE RESTRICT; + +CREATE INDEX idx_account_join_operations_scope_token_hash + ON account_join_operations(scope_token_hash); diff --git a/services/account-service/src/main/resources/db/migration/V28__account_audit_delivery_backoff.sql b/services/account-service/src/main/resources/db/migration/V28__account_audit_delivery_backoff.sql new file mode 100644 index 0000000000..b4e14f76ae --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V28__account_audit_delivery_backoff.sql @@ -0,0 +1,29 @@ +ALTER TABLE account_audit_outbox + ADD COLUMN attempt_count INTEGER NOT NULL DEFAULT 0, + ADD COLUMN next_attempt_at TIMESTAMP; + +-- jOOQ's H2 DDL simulation cannot parse PostgreSQL's AT TIME ZONE expression. +-- Flyway still applies this UTC backfill against PostgreSQL. +-- [jooq ignore start] +UPDATE account_audit_outbox +SET next_attempt_at = now() AT TIME ZONE 'UTC' +WHERE delivery_status = 'PENDING'; +-- [jooq ignore stop] + +-- [jooq ignore start] +ALTER TABLE account_audit_outbox + ALTER COLUMN next_attempt_at SET DEFAULT (now() AT TIME ZONE 'UTC'); +-- [jooq ignore stop] + +ALTER TABLE account_audit_outbox + ADD CONSTRAINT account_audit_outbox_attempt_count_check + CHECK (attempt_count >= 0); + +ALTER TABLE account_audit_outbox + ADD CONSTRAINT account_audit_outbox_retry_state_check + CHECK ((delivery_status = 'PENDING' AND next_attempt_at IS NOT NULL) + OR (delivery_status IN ('COMMITTED', 'MINIMIZED') AND next_attempt_at IS NULL)); + +CREATE INDEX idx_account_audit_outbox_due + ON account_audit_outbox(next_attempt_at, created_at, audit_event_id) + WHERE delivery_status = 'PENDING'; diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 1aab85bcf3..8411c88db4 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -5,7 +5,11 @@ info: API for user accounts and authentication. The obsolete caller-asserted POST /accounts/{accountId}/external route is removed and denied at the public edge; no provider-linking route is available until the - server-verified global-account flow and its proof converge. + server-verified global-account flow and its proof converge. Account's + POST /auth/bootstrap/join facade and local operation are implemented; + external Gateway exposure remains blocked pending JOIN recovery and + reconciliation (#2848), PostgreSQL runtime proof, and direct text-client + end-to-end proof. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 @@ -37,26 +41,20 @@ components: schemas: CreateAccountRequest: type: object - description: Current API shape requires tenantId; target global registration with explicit JOIN remains unimplemented. + description: Creates a global account. Tenant membership and profiles are established separately. properties: - tenantId: - type: integer - format: int64 - minimum: 1 username: type: string email: type: string password: type: string - required: [tenantId, username, email, password] + required: [username, email, password] AccountDto: type: object properties: id: type: integer - tenantId: - type: string username: type: string email: @@ -168,11 +166,16 @@ components: type: string BootstrapRealmDto: type: object + required: + [worldSlug, realmSlug, realmId, catalogRevision, playableStateNamespaceId, playableStateScope] properties: worldSlug: type: string realmSlug: type: string + realmId: + type: string + format: uuid displayName: type: string tenantId: @@ -181,8 +184,23 @@ components: type: integer pointerVersion: type: integer + catalogRevision: + type: integer + format: int64 + minimum: 1 + playableStateNamespaceId: + type: string + format: uuid + playableStateScope: + type: string + enum: [PLAYABLE_STATE_SCOPE_SHARED, PLAYABLE_STATE_SCOPE_ISOLATED] requiresCharacterSelection: type: boolean + stateScope: + type: string + enum: [SHARED, ISOLATED] + characterCreationPolicy: + type: string evaluatedAt: type: string connectScopeExpiresAt: @@ -568,8 +586,9 @@ paths: description: Invalid request /accounts: post: - summary: Create a new account + summary: Create a new global account operationId: createAccount + description: Registration creates global account and security state only; it does not join a tenant or create a profile. security: [] requestBody: required: true 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 24202a5baf..2207175c8b 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 @@ -6,6 +6,7 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.UUID; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -13,6 +14,7 @@ import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -57,6 +59,7 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; + @Autowired private DSLContext dsl; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -69,6 +72,51 @@ void pingEndpointReturnsPong() { assertThat(body).contains("pong"); } + @Test + void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String username = "global-" + suffix; + String email = username + "@example.com"; + HttpRequest request = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"username\":\"" + + username + + "\",\"email\":\"" + + email + + "\",\"password\":\"password123\",\"tenantId\":999}")) + .build(); + + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode()).isEqualTo(200); + Number accountId = + dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + assertThat(dsl.fetchValue("SELECT tenant_id FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat(dsl.fetchValue("SELECT role FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM profiles WHERE account_id = ?", accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox " + + "WHERE scope = 'platform' AND tenant_id IS NULL " + + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", + "{\"accountId\":" + accountId.longValue() + "}")) + .isEqualTo(1L); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 96242142ea..132564086b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -3,10 +3,28 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.service.ExpiredConnectScopeCleanupJob; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; @@ -21,7 +39,11 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -30,6 +52,7 @@ @SuppressWarnings("resource") @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AccountRepositoryIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String MIGRATION_PROOF_SCHEMA = "account_migration_proof"; @@ -37,6 +60,8 @@ class AccountRepositoryIntegrationTest { "account_migration_collision_proof"; private static final String PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA = "account_profile_identity_migration_proof"; + private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = + "account_global_registration_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -61,9 +86,644 @@ void setUpRepository() { @BeforeEach void cleanTables() { + dsl.execute("TRUNCATE TABLE account_audit_outbox"); dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); } + @Test + void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DSLContext transactionAwareDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(transactionAwareDsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(transactionAwareDsl); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(transactionAwareDsl); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "two-phase-join", + "two-phase-join@example.com", + "hash")); + VerifiedJoinScope scope = joinScope(accountId); + scopes.insert(scope); + String callerBinding = "bootstrap-jti-two-phase"; + String requestId = "join-two-phase-1"; + String intentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + + transaction.executeWithoutResult( + status -> joinOperations.insertIntent(requestId, scope, callerBinding, intentDigest)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).realmId()).isEqualTo(REALM_ID); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat( + jdbc.queryForObject( + "SELECT realm_id FROM account_join_operations WHERE request_id = ?", + UUID.class, + requestId)) + .isEqualTo(REALM_ID); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isNull(); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isNull(); + + String policyDigest = AccountJoinDigest.request(scope, callerBinding, true, 1L); + UUID auditEventId = UUID.randomUUID(); + Account account = new Account(); + account.setId(accountId); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + true))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate second-transaction rollback"); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + Long.class, + accountId, + scope.tenantId())) + .isZero(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + auditEventId)) + .isZero(); + + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + false)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("COMMITTED"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isEqualTo("JOINED"); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isEqualTo(policyDigest); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isEqualTo(1L); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isEqualTo(true); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN'", + Long.class, + accountId, + scope.tenantId())) + .isEqualTo(1L); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND delivery_status = 'PENDING'", + Long.class, + auditEventId)) + .isEqualTo(1L); + } + + @Test + void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID minimizedEventId = UUID.randomUUID(); + String minimizedPayload = "{\"accountId\":42,\"requestId\":\"join-42\"}"; + String minimizedDigest = AccountAuditDigest.ofPayload(minimizedPayload); + UUID committedEventId = UUID.randomUUID(); + String committedPayload = "{\"accountId\":43}"; + + outbox.append( + minimizedEventId, "tenant", 7L, "ACCOUNT_JOINED_PUBLIC_PRODUCTION", minimizedPayload); + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); + outbox.append(committedEventId, "platform", null, "ACCOUNT_REGISTERED", committedPayload); + outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); + outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); + + assertThatThrownBy( + () -> outbox.markDelivered(minimizedEventId, "other-receipt", "log-minimized", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + assertThatThrownBy( + () -> outbox.markDelivered(minimizedEventId, "receipt-minimized", "other-log", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + assertThatThrownBy( + () -> + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + assertThatThrownBy( + () -> outbox.markDelivered(UUID.randomUUID(), "receipt-missing", "log-missing", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isNull(); + assertThat( + jdbc.queryForObject( + "SELECT scope FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("tenant"); + assertThat( + jdbc.queryForObject( + "SELECT audit_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + UUID.class, + minimizedEventId)) + .isEqualTo(minimizedEventId); + assertThat( + jdbc.queryForObject( + "SELECT tenant_id FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + minimizedEventId)) + .isEqualTo(7L); + assertThat( + jdbc.queryForObject( + "SELECT payload_digest FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo(minimizedDigest); + assertThat( + jdbc.queryForObject( + "SELECT receiver_receipt_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("receipt-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_log_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("log-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("MINIMIZED"); + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo(committedPayload); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo("COMMITTED"); + assertThat(outbox.pending(10, Instant.now())) + .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) + .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); + assertThat( + jdbc.queryForObject( + "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + minimizedEventId)) + .isNull(); + assertThat( + jdbc.queryForObject( + "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + committedEventId)) + .isNull(); + } + + @Test + void auditRetryUsesCappedExponentialBackoffAndDoesNotStarveNewDueEvents() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID failingEventId = UUID.randomUUID(); + UUID laterEventId = UUID.randomUUID(); + outbox.append(failingEventId, "platform", null, "ACCOUNT_REGISTERED", "{\"id\":1}"); + assertThat(outbox.pending(50, Instant.now())) + .extracting(envelope -> envelope.auditEventId()) + .contains(failingEventId); + + List expectedDelays = List.of(5, 10, 20, 40, 80, 160, 300, 300); + for (int attempt = 0; attempt < expectedDelays.size(); attempt++) { + outbox.recordAttempt(failingEventId); + + assertThat( + jdbc.queryForObject( + "SELECT attempt_count FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + failingEventId)) + .isEqualTo(attempt + 1); + assertThat( + jdbc.queryForObject( + "SELECT EXTRACT(EPOCH FROM (next_attempt_at - last_attempt_at))::INTEGER " + + "FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + failingEventId)) + .isEqualTo(expectedDelays.get(attempt)); + } + + outbox.append(laterEventId, "platform", null, "ACCOUNT_REGISTERED", "{\"id\":2}"); + + assertThat(outbox.pending(50, Instant.now())) + .extracting(envelope -> envelope.auditEventId()) + .containsExactly(laterEventId); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + failingEventId)) + .isEqualTo("PENDING"); + } + + @Test + void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + TransactionAwareDataSourceProxy transactionAwareDataSource = + new TransactionAwareDataSourceProxy(dataSource); + JdbcTemplate transactionJdbc = new JdbcTemplate(transactionAwareDataSource); + DSLContext transactionDsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionDsl); + UUID appendedEventId = UUID.randomUUID(); + UUID defaultedEventId = UUID.randomUUID(); + + transaction.executeWithoutResult( + status -> { + transactionJdbc.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + assertThat( + transactionJdbc.queryForObject( + "SELECT current_setting('TimeZone')", String.class)) + .isEqualTo("Pacific/Auckland"); + + outbox.append(appendedEventId, "platform", null, "ACCOUNT_REGISTERED", "{}"); + LocalDateTime occurredAt = + transactionJdbc.queryForObject( + "SELECT occurred_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + appendedEventId); + LocalDateTime retryAt = + transactionJdbc.queryForObject( + "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + appendedEventId); + assertThat(retryAt).isEqualTo(occurredAt); + + Instant beforeDefaultInsert = Instant.now(); + transactionJdbc.update( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, producer_service, event_type, occurred_at, " + + "schema_version, payload_digest_version, payload_digest, payload, delivery_status) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', ?, 1, 1, ?, '{}', 'PENDING')", + defaultedEventId, + LocalDateTime.ofInstant(beforeDefaultInsert, ZoneOffset.UTC), + AccountAuditDigest.ofPayload("{}")); + LocalDateTime defaultRetryAt = + Objects.requireNonNull( + transactionJdbc.queryForObject( + "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + defaultedEventId), + "next_attempt_at database default should be populated"); + assertThat( + Duration.between(beforeDefaultInsert, defaultRetryAt.toInstant(ZoneOffset.UTC))) + .isLessThan(Duration.ofSeconds(10)); + assertThat( + Duration.between(defaultRetryAt, LocalDateTime.now(ZoneId.of("Pacific/Auckland"))) + .abs()) + .isGreaterThan(Duration.ofHours(1)); + }); + } + + @Test + void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransaction() + throws Exception { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "subscription-lock", + "subscription-lock@example.com", + "hash")); + long tenantId = 7654321L; + jdbc.update( + "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " + + "VALUES (?, 'test-plan', 'active', ?, 1)", + accountId, + tenantId); + + TransactionAwareDataSourceProxy transactionAwareDataSource = + new TransactionAwareDataSourceProxy(dataSource); + DSLContext transactionDsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); + SubscriptionRepository subscriptions = new SubscriptionRepository(transactionDsl); + TransactionTemplate lockTransaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + CountDownLatch subscriptionLocked = new CountDownLatch(1); + CountDownLatch releaseSubscriptionLock = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future lockHolder = + executor.submit( + () -> + lockTransaction.executeWithoutResult( + status -> { + assertThat(subscriptions.findByTenantIdForUpdate(tenantId)).hasSize(1); + subscriptionLocked.countDown(); + try { + if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Timed out holding subscription row lock"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while holding row lock", ex); + } + })); + + try { + assertThat(subscriptionLocked.await(5, TimeUnit.SECONDS)).isTrue(); + + TransactionTemplate conflictingTransaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + JdbcTemplate conflictingJdbc = new JdbcTemplate(transactionAwareDataSource); + assertThatThrownBy( + () -> + conflictingTransaction.executeWithoutResult( + status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); + conflictingJdbc.update( + "UPDATE subscription SET status = status WHERE tenant_id = ?", + tenantId); + })) + .hasMessageContaining("lock timeout"); + + Integer updatedAccounts = + conflictingTransaction.execute( + status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); + return conflictingJdbc.update( + "UPDATE accounts SET email = ? WHERE id = ?", + "subscription-lock-updated@example.com", + accountId); + }); + assertThat(updatedAccounts).isEqualTo(1); + } finally { + releaseSubscriptionLock.countDown(); + try { + lockHolder.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "scope-uuid", + "scope-uuid@example.com", + "hash")); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + VerifiedJoinScope scope = joinScope(accountId); + + scopes.insert(scope); + + assertThat(scopes.find(scope.connectScopeId()).orElseThrow().realmId()).isEqualTo(REALM_ID); + UUID changedRealmId = UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01"); + jdbc.update( + "UPDATE account_connect_scope_records SET realm_id = ? WHERE scope_token_hash = ?", + changedRealmId, + AccountJoinDigest.tokenHash(scope.connectScopeId())); + + assertThatThrownBy(() -> scopes.find(scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope digest mismatch"); + } + + @Test + void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidence() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(dsl); + AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository(dsl); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "scope-cleanup", + "scope-cleanup@example.com", + "hash")); + Instant capturedNow = Instant.now(); + String expiredAt = capturedNow.minusSeconds(60).toString(); + VerifiedJoinScope unreferenced = joinScope(accountId, "scope-cleanup-free", expiredAt); + VerifiedJoinScope pending = joinScope(accountId, "scope-cleanup-pending", expiredAt); + VerifiedJoinScope committed = joinScope(accountId, "scope-cleanup-committed", expiredAt); + VerifiedJoinScope failed = joinScope(accountId, "scope-cleanup-failed", expiredAt); + VerifiedJoinScope future = + joinScope(accountId, "scope-cleanup-future", capturedNow.plusSeconds(86_400).toString()); + VerifiedJoinScope malformed = joinScope(accountId, "scope-cleanup-malformed", expiredAt); + VerifiedJoinScope invalidCalendarDate = + joinScope(accountId, "scope-cleanup-invalid-date", expiredAt); + for (VerifiedJoinScope scope : + List.of(unreferenced, pending, committed, failed, future, malformed, invalidCalendarDate)) { + scopes.insert(scope); + } + jdbc.update( + "UPDATE account_connect_scope_records SET connect_scope_expires_at = ? WHERE scope_token_hash = ?", + "not-an-instant", + AccountJoinDigest.tokenHash(malformed.connectScopeId())); + jdbc.update( + "UPDATE account_connect_scope_records SET connect_scope_expires_at = ? WHERE scope_token_hash = ?", + "2026-02-30T10:02:00Z", + AccountJoinDigest.tokenHash(invalidCalendarDate.connectScopeId())); + + insertJoinIntent(joinOperations, pending, "join-scope-pending"); + insertJoinIntent(joinOperations, committed, "join-scope-committed"); + insertJoinIntent(joinOperations, failed, "join-scope-failed"); + joinOperations.finish("join-scope-failed", "FAILED", "CONNECT_SCOPE_INVALID", null, null, null); + joinOperations.bindPolicyEvidence( + "join-scope-committed", + AccountJoinDigest.request(committed, "scope-cleanup-committed-caller", true, 1L), + 1L, + true); + Account account = new Account(); + account.setId(accountId); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(committed.tenantId()); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.save(membership); + joinOperations.finish( + "join-scope-committed", + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob cleanupJob = + new ExpiredConnectScopeCleanupJob(scopes, meters, 100, 60_000); + cleanupJob.cleanupExpiredConnectScopes(); + + assertThat(meters.get("account.connect_scopes.cleanup.deleted").counter().count()).isEqualTo(1); + assertThat(meters.get("account.connect_scopes.cleanup.failure").counter().count()).isZero(); + assertThat(scopeCount(jdbc, unreferenced)).isZero(); + assertThat(scopeCount(jdbc, pending)).isEqualTo(1); + assertThat(scopeCount(jdbc, committed)).isEqualTo(1); + assertThat(scopeCount(jdbc, failed)).isEqualTo(1); + assertThat(scopeCount(jdbc, future)).isEqualTo(1); + assertThat(scopeCount(jdbc, malformed)).isEqualTo(1); + assertThat(scopeCount(jdbc, invalidCalendarDate)).isEqualTo(1); + assertThatThrownBy( + () -> + jdbc.update( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(pending.connectScopeId()))) + .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); + assertThatThrownBy( + () -> insertJoinIntent(joinOperations, unreferenced, "join-scope-after-cleanup")) + .isInstanceOf(DataAccessException.class); + assertThat(joinOperations.find("join-scope-after-cleanup")).isEmpty(); + } + + private void commitJoinOutcome( + AccountJoinOperationRepository joinOperations, + AccountTenantMembershipRepository memberships, + AccountAuditOutboxRepository outbox, + Account account, + String requestId, + VerifiedJoinScope scope, + String policyDigest, + UUID auditEventId, + boolean simulateRollback) { + joinOperations.bindPolicyEvidence(requestId, policyDigest, 1L, true); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(scope.tenantId()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.save(membership); + outbox.append( + auditEventId, + "tenant", + scope.tenantId(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + "{\"requestId\":\"" + requestId + "\"}"); + joinOperations.finish( + requestId, + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + if (simulateRollback) { + throw new IllegalStateException("simulate second-transaction rollback"); + } + } + + private void insertJoinIntent( + AccountJoinOperationRepository joinOperations, VerifiedJoinScope scope, String requestId) { + joinOperations.insertIntent( + requestId, + scope, + "scope-cleanup-committed-caller", + AccountJoinDigest.intent(requestId, scope, "scope-cleanup-committed-caller")); + } + + private static long scopeCount(JdbcTemplate jdbc, VerifiedJoinScope scope) { + return Objects.requireNonNull( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_connect_scope_records WHERE scope_token_hash = ?", + Long.class, + AccountJoinDigest.tokenHash(scope.connectScopeId()))); + } + + private AccountJoinOperationRepository.JoinOperation joinOperation( + AccountJoinOperationRepository joinOperations, String requestId) { + return joinOperations.find(requestId).orElseThrow(); + } + + private static VerifiedJoinScope joinScope(long accountId) { + return joinScope(accountId, "two-phase-connect-scope", "2026-09-24T10:02:00Z"); + } + + private static VerifiedJoinScope joinScope( + long accountId, String connectScopeId, String expiresAt) { + VerifiedJoinScope base = + new VerifiedJoinScope( + connectScopeId, + accountId, + 7L, + REALM_ID, + "demo", + "production", + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + expiresAt, + "unused"); + String digest = AccountJoinDigest.scope(base); + return new VerifiedJoinScope( + base.connectScopeId(), + base.accountId(), + base.tenantId(), + base.realmId(), + base.worldSlug(), + base.realmSlug(), + base.playableStateNamespaceId(), + base.playableStateScope(), + base.gameInstanceId(), + base.catalogRevision(), + base.pointerVersion(), + base.evaluatedAt(), + base.connectScopeExpiresAt(), + digest); + } + @ParameterizedTest @EnumSource( value = AccountLifecycleState.class, @@ -286,6 +946,104 @@ void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() .isEqualTo(2L); } + @Test + void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { + String schema = GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("25") + .load() + .migrate(); + + long legacyAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('legacy-global', 'legacy-global@example.com', 'hash', 1) RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + schema + ".profiles (account_id, tenant_id) VALUES (?, ?)", + legacyAccountId, + 7L); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership (account_id, tenant_id, gameplay_admission_allowed) " + + "VALUES (?, ?, TRUE)", + legacyAccountId, + 7L); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", legacyAccountId)) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT disposition FROM " + + schema + + ".account_legacy_tenant_sources " + + "WHERE account_id = ?", + legacyAccountId)) + .isEqualTo("TENANT_MISMATCH"); + assertThat( + dsl.fetchValue( + "SELECT original_gameplay_admission_allowed FROM " + + schema + + ".account_legacy_membership_sources WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(true); + assertThat( + dsl.fetchValue( + "SELECT gameplay_admission_allowed FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(false); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".profiles WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(1L); + + long newAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash) " + + "VALUES ('new-global', 'new-global@example.com', 'hash') RETURNING id")) + .longValue(); + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue("SELECT role FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + newAccountId)) + .isEqualTo(0L); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java index d6184c5a08..064af7e88b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -173,6 +173,27 @@ void reachableResponseErrorRemainsDomainFailure() throws Exception { verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @Test + void reachableAdmissionPointerUnavailableResponsePropagatesAsDomainFailure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayWorlds(any())) + .thenReturn( + ListGameplayWorldsResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("ADMISSION_POINTER_UNAVAILABLE") + .setMessage("incomplete authority")) + .build()); + GameSessionClient client = newClient(stub); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, client::listGameplayWorlds); + + assertThat(failure) + .hasMessage("Gameplay world discovery failed: ADMISSION_POINTER_UNAVAILABLE"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + @Test void gameplayRealmDiscoveryPreservesNonRetryableApplicationError() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java new file mode 100644 index 0000000000..cc3ebf0e79 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.service.AccountAuditDeliveryJob; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.slf4j.LoggerFactory; + +class LoggingAdminClientTest { + private static final long TENANT_ID = 20L; + private static final long ACCOUNT_ID = 10L; + private static final long TRANSACTION_ID = 30L; + private static final String PAYMENT_PAYLOAD = "{\"accountId\":10,\"transactionId\":30}"; + + @Test + void logPaymentIgnoresTransportFailureAndPreservesAuditEnvelope() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE.withDescription("receiver down"))); + LoggingAdminClient client = newClient(stub); + + assertDoesNotThrow(() -> client.logPayment(TENANT_ID, ACCOUNT_ID, TRANSACTION_ID)); + + assertPaymentEnvelope(stub); + } + + @Test + void logPaymentIgnoresUnexpectedRuntimeFailureAndPreservesAuditEnvelope() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())).thenThrow(new IllegalStateException("private detail")); + LoggingAdminClient client = newClient(stub); + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LoggingAdminClient.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + assertDoesNotThrow(() -> client.logPayment(TENANT_ID, ACCOUNT_ID, TRANSACTION_ID)); + + assertEquals(1, appender.list.size()); + ILoggingEvent warning = appender.list.get(0); + String message = warning.getFormattedMessage(); + assertTrue(message.contains("cause=IllegalStateException")); + assertTrue(message.contains("tenantId=" + TENANT_ID)); + assertTrue(message.contains("accountId=" + ACCOUNT_ID)); + assertTrue(message.contains("transactionId=" + TRANSACTION_ID)); + assertFalse(message.contains("private detail")); + assertFalse(message.contains(PAYMENT_PAYLOAD)); + assertNull(warning.getThrowableProxy()); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + + assertPaymentEnvelope(stub); + } + + @Test + void logPaymentIgnoresMismatchedReceiptAndPreservesAuditEnvelope() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())) + .thenReturn(CreateLogEventResponse.newBuilder().setAuditEventId("other-event").build()); + LoggingAdminClient client = newClient(stub); + + assertDoesNotThrow(() -> client.logPayment(TENANT_ID, ACCOUNT_ID, TRANSACTION_ID)); + + assertPaymentEnvelope(stub); + } + + @Test + void deliverStillThrowsWhenTheReceiverReturnsMismatchedReceiptEvidence() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())) + .thenReturn(CreateLogEventResponse.newBuilder().setAuditEventId("other-event").build()); + LoggingAdminClient client = newClient(stub); + + assertThrows(IllegalStateException.class, () -> client.deliver(validEnvelope())); + } + + @Test + void receiverErrorKeepsAuditPendingAndOmitsFreeFormErrorDetails() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())) + .thenReturn( + CreateLogEventResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_EVENT") + .setMessage("sensitive receiver detail")) + .build()); + LoggingAdminClient client = newClient(stub); + AccountAuditEnvelope envelope = validEnvelope(); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> client.deliver(envelope)); + + assertEquals("Account audit receiver returned error code INVALID_EVENT", failure.getMessage()); + assertFalse(failure.getMessage().contains("sensitive receiver detail")); + + AccountAuditOutboxRepository outbox = mock(AccountAuditOutboxRepository.class); + when(outbox.pending(org.mockito.ArgumentMatchers.eq(50), any(Instant.class))) + .thenReturn(java.util.List.of(envelope)); + new AccountAuditDeliveryJob(outbox, client).deliverPending(); + + verify(outbox).recordAttempt(envelope.auditEventId()); + verify(outbox, never()) + .markDelivered(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @Test + void deliverSanitizesMalformedReceiverErrorCode() throws Exception { + var stub = mockStub(); + when(stub.createLogEvent(any())) + .thenReturn( + CreateLogEventResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_EVENT\nprivate") + .setMessage("sensitive receiver detail")) + .build()); + LoggingAdminClient client = newClient(stub); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> client.deliver(validEnvelope())); + + assertEquals("Account audit receiver returned error code UNKNOWN", failure.getMessage()); + assertFalse(failure.getMessage().contains("sensitive receiver detail")); + assertFalse(failure.getMessage().contains("private")); + } + + @Test + void deliverRejectsNullOrNoncanonicalScopeBeforeTransport() throws Exception { + var stub = mockStub(); + LoggingAdminClient client = newClient(stub); + + assertThrows( + IllegalArgumentException.class, () -> client.deliver(envelopeWithScope(null, null))); + assertThrows( + IllegalArgumentException.class, () -> client.deliver(envelopeWithScope("other", null))); + assertThrows( + IllegalArgumentException.class, () -> client.deliver(envelopeWithScope("tenant", null))); + assertThrows( + IllegalArgumentException.class, () -> client.deliver(envelopeWithScope("platform", 7L))); + + verify(stub, never()).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, never()).createLogEvent(any()); + } + + private static AccountAuditEnvelope validEnvelope() { + String payload = "{\"event\":\"test\"}"; + return new AccountAuditEnvelope( + UUID.fromString("8a5f6238-f0d9-4992-80cb-e7f447e0f913"), + "tenant", + TENANT_ID, + "account-service", + "TEST_EVENT", + Instant.parse("2026-01-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static AccountAuditEnvelope envelopeWithScope(String scope, Long tenantId) { + AccountAuditEnvelope envelope = validEnvelope(); + return new AccountAuditEnvelope( + envelope.auditEventId(), + scope, + tenantId, + envelope.producerService(), + envelope.eventType(), + envelope.occurredAt(), + envelope.schemaVersion(), + envelope.payloadDigestVersion(), + envelope.payloadDigest(), + envelope.payload()); + } + + private static void assertPaymentEnvelope( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) { + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + verify(stub).createLogEvent(requestCaptor.capture()); + CreateLogEventRequest request = requestCaptor.getValue(); + + assertEquals(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT, request.getScope()); + assertEquals(Long.toString(TENANT_ID), request.getTenantId()); + assertEquals(4, UUID.fromString(request.getAuditEventId()).version()); + assertEquals("account-service", request.getProducerService()); + assertEquals("PAYMENT_TXN", request.getEventType()); + assertEquals(1, request.getSchemaVersion()); + assertEquals(1, request.getPayloadDigestVersion()); + assertEquals(PAYMENT_PAYLOAD, request.getPayload().toStringUtf8()); + assertEquals(AccountAuditDigest.ofPayload(PAYMENT_PAYLOAD), request.getPayloadDigest()); + } + + private static LoggingAdminClient newClient( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) throws Exception { + LoggingAdminClient client = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub mockStub() { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = + mock(LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 2c6f3ec899..20010b7bb1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -66,8 +66,7 @@ void clear() { @Test void createAccountReturnsDto() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); AccountDto response = new AccountDto(1L, "demo", "demo@example.com", "player", true); when(accountService.createAccount(request)).thenReturn(response); @@ -83,8 +82,7 @@ void createAccountReturnsDto() throws Exception { @Test void createAccountConflictUsesCanonicalEnvelope() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountService.createAccount(request)) .thenThrow(new AccountAlreadyExistsException(new RuntimeException("duplicate"))); @@ -99,27 +97,9 @@ void createAccountConflictUsesCanonicalEnvelope() throws Exception { .andExpect(jsonPath("$.error.message").value("Account already exists")); } - @Test - void createAccountRejectsZeroTenantIdBeforeDispatch() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(0L, "demo", "demo@example.com", "password"); - - mockMvc - .perform( - post("/accounts") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("tenantId must be positive")); - - verifyNoInteractions(accountService); - } - @Test void createAccountRetainsMinimumPasswordLength() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "12345"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "12345"); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 4b9d9e131c..316a813e0e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -3,6 +3,9 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -13,6 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Map; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -26,6 +30,7 @@ import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; import org.junit.jupiter.api.Test; @@ -36,6 +41,7 @@ import org.springframework.http.MediaType; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.yaml.snakeyaml.Yaml; import tools.jackson.databind.ObjectMapper; @WebMvcTest(AuthController.class) @@ -47,6 +53,38 @@ class AuthControllerTest { @MockitoBean private AccountService accountService; + @Test + void publicOpenApiOmitsUnavailableBootstrapJoin() throws Exception { + try (var input = getClass().getResourceAsStream("/openapi.yaml")) { + Map document = new Yaml().load(input); + Map paths = (Map) document.get("paths"); + Map components = (Map) document.get("components"); + Map schemas = (Map) components.get("schemas"); + + assertFalse(paths.containsKey("/auth/bootstrap/join")); + assertTrue(((Map) paths.get("/auth/player-bootstrap")).containsKey("post")); + assertTrue(((Map) paths.get("/auth/connect-token")).containsKey("post")); + assertFalse(schemas.containsKey("JoinPublicProductionRequest")); + assertFalse(schemas.containsKey("JoinPublicProductionResult")); + } + } + + @Test + void publicOpenApiDocumentsRetryableCharacterDiscoveryOutage() throws Exception { + try (var input = getClass().getResourceAsStream("/openapi.yaml")) { + Map document = new Yaml().load(input); + Map paths = (Map) document.get("paths"); + Map characterPath = + (Map) + paths.get("/auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters"); + Map operation = (Map) characterPath.get("get"); + Map responses = (Map) operation.get("responses"); + Map outage = (Map) responses.get("503"); + + assertEquals("#/components/responses/RetryableAuthenticationUnavailable", outage.get("$ref")); + } + } + @Test void loginReturnsTokenAndAccountId() throws Exception { LoginRequest request = new LoginRequest("demo", "password"); @@ -170,10 +208,14 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { new BootstrapRealmDto( "demo", "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", "Live Realm", 1L, 42L, 17L, + 23L, + "8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88", + "PLAYABLE_STATE_SCOPE_SHARED", false, "SHARED", "ALLOW_NEW", @@ -188,6 +230,13 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) + .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) + .andExpect(jsonPath("$.data[0].catalogRevision").value(23)) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88")) + .andExpect(jsonPath("$.data[0].playableStateScope").value("PLAYABLE_STATE_SCOPE_SHARED")) + .andExpect(jsonPath("$.data[0].stateScope").value("SHARED")) .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } @@ -219,6 +268,21 @@ void listBootstrapCharactersRejectsMissingConnectScopeIdBeforeDispatch() throws verifyNoInteractions(accountService); } + @Test + void listBootstrapCharactersReportsRetryableEntitlementOutage() throws Exception { + when(accountService.listBootstrapCharacters("boot123", "demo", "production", "scope-1")) + .thenThrow(new AuthenticationException("ENTITLEMENT_UNAVAILABLE", "Authority unavailable")); + + mockMvc + .perform( + get("/auth/bootstrap/worlds/demo/realms/production/characters") + .param("connectScopeId", "scope-1") + .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect(jsonPath("$.error.code").value("ENTITLEMENT_UNAVAILABLE")); + } + @Test void requestPasswordResetReturnsSuccess() throws Exception { PasswordResetRequest req = new PasswordResetRequest("demo@example.com"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index acd3e499da..fda8d4325e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -56,7 +56,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { @Test void accountCreationRemainsPublicInProdProfile() throws Exception { CreateAccountRequest request = - new CreateAccountRequest(1L, "demo", "demo@example.com", "swordfish"); + new CreateAccountRequest("demo", "demo@example.com", "swordfish"); when(accountService.createAccount(request)) .thenReturn(new AccountDto(1L, "demo", "demo@example.com", "player", true)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index e555477523..b76fe71ace 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -59,7 +59,8 @@ void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.empty()); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); @@ -80,11 +81,61 @@ void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { () -> assertEquals(1L, seededSubscription.getTenantId())); } + @Test + void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exception { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); + explicitJoin.setMembershipVersion(4L); + explicitJoin.setMembershipAuthorityGeneration(8L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + ArgumentCaptor accountCaptor = ArgumentCaptor.forClass(Account.class); + verify(accountRepository).save(accountCaptor.capture()); + Account saved = accountCaptor.getValue(); + assertAll( + () -> assertEquals("demo", saved.getUsername()), + () -> assertEquals("demo@example.com", saved.getEmail()), + () -> assertEquals("player", saved.getRole()), + () -> assertTrue(saved.isEmailVerified()), + () -> assertNotNull(saved.getPasswordHash()), + () -> assertFalse(saved.getPasswordHash().isBlank())); + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + org.junit.jupiter.api.Assertions.assertAll( + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "ACTIVE", explicitJoin.getLifecycleState()), + () -> + org.junit.jupiter.api.Assertions.assertTrue(explicitJoin.isGameplayAdmissionAllowed()), + () -> + org.junit.jupiter.api.Assertions.assertEquals(4L, explicitJoin.getMembershipVersion()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + 8L, explicitJoin.getMembershipAuthorityGeneration()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "EXPLICIT_JOIN", explicitJoin.getAuthorityProvenance())); + verify(profileRepository, never()).save(any(Profile.class)); + verify(subscriptionRepository).save(any(Subscription.class)); + } + @Test void runIsIdempotentWhenInvokedTwice() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); + AccountTenantMembership seededMembership = + membership(account, 1L, "ACTIVE", "SEEDED_DEMO", true); Subscription seededSubscription = new Subscription(); seededSubscription.setAccount(account); seededSubscription.setPlanId("local-smoke"); @@ -94,8 +145,8 @@ void runIsIdempotentWhenInvokedTwice() { when(accountRepository.findByEmail("demo@example.com")) .thenReturn(Optional.empty(), Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)) - .thenReturn(false, true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.empty(), Optional.of(seededMembership)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty(), Optional.of(new Profile())); when(subscriptionRepository.findByTenantId(1L)) @@ -104,6 +155,8 @@ void runIsIdempotentWhenInvokedTwice() { seeder.run(new DefaultApplicationArguments(new String[] {})); seeder.run(new DefaultApplicationArguments(new String[] {})); + verify(accountTenantMembershipRepository, times(1)).save(any(AccountTenantMembership.class)); + verify(profileRepository, times(1)).save(any(Profile.class)); verify(subscriptionRepository, times(1)).save(any(Subscription.class)); } @@ -114,6 +167,9 @@ void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { account.setEmail("demo@example.com"); Account billingOwner = new Account(); billingOwner.setId(2L); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); + explicitJoin.setMembershipVersion(4L); + explicitJoin.setMembershipAuthorityGeneration(8L); Subscription existingSubscription = new Subscription(); existingSubscription.setAccount(billingOwner); existingSubscription.setPlanId("billing-owned-plan"); @@ -123,29 +179,20 @@ void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(existingSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); - ArgumentCaptor accountCaptor = ArgumentCaptor.forClass(Account.class); - verify(accountRepository).save(accountCaptor.capture()); - Account saved = accountCaptor.getValue(); assertAll( - () -> assertEquals("demo", saved.getUsername()), - () -> assertEquals("demo@example.com", saved.getEmail()), - () -> assertEquals("player", saved.getRole()), - () -> assertTrue(saved.isEmailVerified()), - () -> assertNotNull(saved.getPasswordHash()), - () -> assertFalse(saved.getPasswordHash().isBlank()), () -> assertSame(billingOwner, existingSubscription.getAccount()), () -> assertEquals("canceled", existingSubscription.getStatus()), () -> assertEquals("billing-owned-plan", existingSubscription.getPlanId()), () -> assertEquals(LocalDateTime.of(2025, 1, 2, 3, 4), existingSubscription.getEndedAt())); verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); - verify(profileRepository, never()).save(any(Profile.class)); verify(subscriptionRepository, never()).save(any(Subscription.class)); } @@ -154,6 +201,7 @@ void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); Subscription active = new Subscription(); active.setStatus("active"); active.setTenantId(1L); @@ -163,7 +211,8 @@ void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(active, canceled)); @@ -174,6 +223,111 @@ void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); assertTrue(exception.getMessage().contains("ambiguous subscription authority")); + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); verify(subscriptionRepository, never()).save(any(Subscription.class)); } + + @Test + void runReconcilesOnlyTheExactQuarantinedDemoMembership() throws Exception { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + AccountTenantMembership quarantined = + membership(account, 1L, "LEGACY_UNVERIFIED", "LEGACY_UNVERIFIED", false); + quarantined.setId(42L); + quarantined.setMembershipVersion(1L); + quarantined.setMembershipAuthorityGeneration(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(quarantined)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(accountTenantMembershipRepository).save(quarantined); + org.junit.jupiter.api.Assertions.assertAll( + () -> org.junit.jupiter.api.Assertions.assertEquals(42L, quarantined.getId()), + () -> org.junit.jupiter.api.Assertions.assertEquals(1L, quarantined.getTenantId()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "ACTIVE", quarantined.getLifecycleState()), + () -> org.junit.jupiter.api.Assertions.assertTrue(quarantined.isGameplayAdmissionAllowed()), + () -> org.junit.jupiter.api.Assertions.assertEquals(2L, quarantined.getMembershipVersion()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + 2L, quarantined.getMembershipAuthorityGeneration()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "SEEDED_DEMO", quarantined.getAuthorityProvenance())); + } + + @Test + void runDoesNotPromoteLegacyMembershipOutsideTheDemoIdentity() throws Exception { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + Account otherAccount = new Account(); + otherAccount.setId(2L); + AccountTenantMembership unrelatedLegacyMembership = + membership(otherAccount, 7L, "LEGACY_UNVERIFIED", "LEGACY_UNVERIFIED", false); + unrelatedLegacyMembership.setId(93L); + unrelatedLegacyMembership.setMembershipVersion(1L); + unrelatedLegacyMembership.setMembershipAuthorityGeneration(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(unrelatedLegacyMembership)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + org.junit.jupiter.api.Assertions.assertAll( + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "LEGACY_UNVERIFIED", unrelatedLegacyMembership.getLifecycleState()), + () -> + org.junit.jupiter.api.Assertions.assertFalse( + unrelatedLegacyMembership.isGameplayAdmissionAllowed()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "LEGACY_UNVERIFIED", unrelatedLegacyMembership.getAuthorityProvenance())); + } + + @Test + void runFailsClosedBeforeRewritingMismatchedAccountReturnedForDemoEmail() throws Exception { + Account mismatchedAccount = new Account(); + mismatchedAccount.setId(1L); + mismatchedAccount.setEmail("real-player@example.com"); + when(accountRepository.findByEmail("demo@example.com")) + .thenReturn(Optional.of(mismatchedAccount)); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + + verify(accountRepository, never()).save(any(Account.class)); + org.mockito.Mockito.verifyNoInteractions(accountTenantMembershipRepository, profileRepository); + } + + private static AccountTenantMembership membership( + Account account, + long tenantId, + String lifecycleState, + String authorityProvenance, + boolean gameplayAdmissionAllowed) { + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(tenantId); + membership.setLifecycleState(lifecycleState); + membership.setAuthorityProvenance(authorityProvenance); + membership.setGameplayAdmissionAllowed(gameplayAdmissionAllowed); + return membership; + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java new file mode 100644 index 0000000000..0a9a029857 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountJoinDigestTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + + @Test + void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { + VerifiedJoinScope scope = scope("scope-token-α", "production"); + + assertEquals( + "sha256:15efd695569eca4a26589922c7ad128c3a2318203d1a2181666cc3ed6650f5b8", + AccountJoinDigest.scope(scope)); + assertEquals( + "sha256:764b03cbe948293517acb4ce201dbd24fc4d2a0a2306e853f2ab0a6c3775a768", + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", false, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 6L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope("scope-token-α", "preview"), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(withGameInstance(scope, 45L), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.scope(scope), + AccountJoinDigest.scope( + withRealm(scope, UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01")))); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.request(scope, "bootstrap-jti-α", null, null)); + + assertEquals( + "sha256:13445ed45c66f0e149250f4101c95452a74f15e56dbf3b9b271852ff2d058776", + AccountJoinDigest.intent("join-request-α", scope, "bootstrap-jti-α")); + } + + @Test + void canonicalSerializationRejectsAmbiguousValues() { + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope=token", "production"))); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope-token", "production\nJOIN"))); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.request(scope("scope-token", "production"), "bad=binding", true, 1L)); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.request(scope("scope-token", "production"), "caller", true, null)); + } + + private static VerifiedJoinScope withGameInstance(VerifiedJoinScope scope, long gameInstanceId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + gameInstanceId, + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static VerifiedJoinScope withRealm(VerifiedJoinScope scope, UUID realmId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + realmId, + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) { + return new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + REALM_ID, + "demo", + realmSlug, + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + "2026-09-24T10:02:00Z", + "unused-by-preimage"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java new file mode 100644 index 0000000000..1064d19560 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.tables.AccountAuditOutbox.ACCOUNT_AUDIT_OUTBOX; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.DSLContext; +import org.jooq.RecordContext; +import org.jooq.RecordListener; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultRecordListenerProvider; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class AccountAuditOutboxRepositoryTest { + private static final UUID EVENT_ID = UUID.fromString("8a5f6238-f0d9-4992-80cb-e7f447e0f913"); + private static final String RECEIPT_ID = "receipt-1"; + private static final String LOG_EVENT_ID = "log-1"; + + @Test + void exactCommittedOrMinimizedTerminalReceiptAfterLostCompareAndSetIsANoOp() { + for (String status : new String[] {"COMMITTED", "MINIMIZED"}) { + boolean minimized = "MINIMIZED".equals(status); + assertThatCode( + () -> + repositoryWithReadback(status, RECEIPT_ID, LOG_EVENT_ID, true) + .markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) + .doesNotThrowAnyException(); + } + } + + @Test + void contradictoryTerminalReceiptOrStatusAfterLostCompareAndSetFails() { + assertRejected("COMMITTED", "other-receipt", LOG_EVENT_ID, false); + assertRejected("COMMITTED", RECEIPT_ID, "other-log", false); + assertRejected("MINIMIZED", RECEIPT_ID, LOG_EVENT_ID, false); + } + + @Test + void missingOutboxRowAfterLostCompareAndSetFails() { + AccountAuditOutboxRepository repository = + repositoryWithReadback("COMMITTED", RECEIPT_ID, LOG_EVENT_ID, false); + + assertThatThrownBy(() -> repository.markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + } + + @Test + void pendingQuerySelectsOnlyDueRowsAndOrdersByRetryTimeBeforeCreationTime() { + AtomicReference executedSql = new AtomicReference<>(); + MockDataProvider provider = + context -> { + executedSql.set(context.sql().toLowerCase(Locale.ROOT)); + Result rows = + DSL.using(SQLDialect.POSTGRES).newResult(ACCOUNT_AUDIT_OUTBOX); + return new MockResult[] {new MockResult(0, rows)}; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + + new AccountAuditOutboxRepository(dsl).pending(7, Instant.parse("2026-10-01T00:00:00Z")); + + String sql = executedSql.get(); + int where = sql.indexOf("where"); + int orderBy = sql.indexOf("order by"); + int retryOrder = sql.indexOf("next_attempt_at", orderBy); + int createdOrder = sql.indexOf("created_at", retryOrder); + int eventOrder = sql.indexOf("audit_event_id", createdOrder); + assertThat(sql.substring(where, orderBy)) + .contains("delivery_status", "next_attempt_at", "<=", "="); + assertThat(retryOrder).isGreaterThan(orderBy); + assertThat(createdOrder).isGreaterThan(retryOrder); + assertThat(eventOrder).isGreaterThan(createdOrder); + assertThat(sql).contains("fetch next ? rows only"); + } + + @Test + void appendStoresRetryTimeAsTheSameUtcLocalDateTimeAsOccurredAt() { + AtomicReference executedSql = new AtomicReference<>(); + AtomicReference storedOccurredAt = new AtomicReference<>(); + AtomicReference storedNextAttemptAt = new AtomicReference<>(); + MockDataProvider provider = + context -> { + String sql = context.sql().toLowerCase(Locale.ROOT); + if (sql.stripLeading().startsWith("insert") && sql.contains("account_audit_outbox")) { + executedSql.set(sql); + } + Result rows = + DSL.using(SQLDialect.POSTGRES).newResult(ACCOUNT_AUDIT_OUTBOX); + return new MockResult[] {new MockResult(1, rows)}; + }; + RecordListener recordListener = + new RecordListener() { + @Override + public void storeStart(RecordContext context) { + if (context.record() instanceof AccountAuditOutboxRecord record) { + storedOccurredAt.set(record.getOccurredAt()); + storedNextAttemptAt.set(record.getNextAttemptAt()); + } + } + }; + DSLContext dsl = + DSL.using( + new DefaultConfiguration() + .set(new MockConnection(provider)) + .set(SQLDialect.POSTGRES) + .set(new DefaultRecordListenerProvider(recordListener))); + + AccountAuditEnvelope envelope = + new AccountAuditOutboxRepository(dsl) + .append(EVENT_ID, "platform", null, "ACCOUNT_REGISTERED", "{}"); + + assertThat(executedSql.get()).contains("occurred_at", "next_attempt_at"); + LocalDateTime expectedUtc = LocalDateTime.ofInstant(envelope.occurredAt(), ZoneOffset.UTC); + assertThat(storedOccurredAt.get()).isEqualTo(expectedUtc); + assertThat(storedNextAttemptAt.get()).isEqualTo(expectedUtc); + } + + @Test + void recordAttemptPersistsIncrementAndCappedExponentialScheduleOnlyWhilePending() { + AtomicReference executedSql = new AtomicReference<>(); + MockDataProvider provider = + context -> { + executedSql.set(context.sql().toLowerCase(Locale.ROOT)); + return new MockResult[] {new MockResult(1)}; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + + new AccountAuditOutboxRepository(dsl).recordAttempt(EVENT_ID); + + String sql = executedSql.get(); + assertThat(sql) + .contains( + "attempt_count", + "last_attempt_at", + "next_attempt_at", + "make_interval", + "least(300", + "where", + "delivery_status"); + } + + private static void assertRejected( + String storedStatus, String storedReceiptId, String storedLogEventId, boolean minimized) { + AccountAuditOutboxRepository repository = + repositoryWithReadback(storedStatus, storedReceiptId, storedLogEventId, true); + assertThatThrownBy( + () -> repository.markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + } + + private static AccountAuditOutboxRepository repositoryWithReadback( + String status, String receiptId, String logEventId, boolean rowExists) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + String sql = context.sql().trim().toLowerCase(Locale.ROOT); + if (sql.startsWith("update")) { + return new MockResult[] {new MockResult(0)}; + } + if (sql.startsWith("select")) { + Result rows = resultDsl.newResult(ACCOUNT_AUDIT_OUTBOX); + if (rowExists) { + AccountAuditOutboxRecord row = resultDsl.newRecord(ACCOUNT_AUDIT_OUTBOX); + row.setAuditEventId(EVENT_ID); + row.setDeliveryStatus(status); + row.setReceiverReceiptId(receiptId); + row.setReceiverLogEventId(logEventId); + rows.add(row); + } + return new MockResult[] {new MockResult(rowExists ? 1 : 0, rows)}; + } + throw new SQLException("Unexpected Account audit outbox query"); + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + return new AccountAuditOutboxRepository(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java new file mode 100644 index 0000000000..59323c498e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class AccountAuditDeliveryJobTest { + private final AccountAuditOutboxRepository outbox = + Mockito.mock(AccountAuditOutboxRepository.class); + private final LoggingAdminClient client = Mockito.mock(LoggingAdminClient.class); + private final AccountAuditDeliveryJob job = new AccountAuditDeliveryJob(outbox, client); + + @Test + void marksOnlyAnExactReceiverReceiptDelivered() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-1", "log-1", false)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + + @Test + void minimizedReceiverReceiptMarksSameIdentityTerminal() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", true)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-2", "log-2", true); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + + @Test + void unavailableReceiverKeepsSameEnvelopePending() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); + when(client.deliver(envelope)).thenThrow(new IllegalStateException("unavailable")); + + job.deliverPending(); + + verify(outbox).recordAttempt(envelope.auditEventId()); + verify(outbox, never()).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + } + + @Test + void recordAttemptFailureDoesNotPreventLaterEnvelopesFromDelivery() { + AccountAuditEnvelope failed = platformRegistration(); + AccountAuditEnvelope later = + platformRegistration(UUID.fromString("4cb5f750-6d75-4eaa-b0b4-2a9a285e2c32")); + when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(failed, later)); + when(client.deliver(failed)).thenThrow(new IllegalStateException("receiver unavailable")); + when(client.deliver(later)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", false)); + Mockito.doThrow(new IllegalStateException("outbox unavailable")) + .when(outbox) + .recordAttempt(failed.auditEventId()); + + job.deliverPending(); + + verify(outbox, never()) + .markDelivered(eq(failed.auditEventId()), anyString(), anyString(), anyBoolean()); + verify(client).deliver(later); + verify(outbox).markDelivered(later.auditEventId(), "receipt-2", "log-2", false); + } + + @Test + void digestBindsExactUtf8PayloadBytes() { + assertEquals( + "sha256:eee0f882a1fae6d1435a03d9e9508a3972f0c1f10495b4e3d5e388cebced63ef", + AccountAuditDigest.ofPayload("{\"accountId\":1}")); + assertNotEquals( + AccountAuditDigest.ofPayload("{\"accountId\":1}"), + AccountAuditDigest.ofPayload("{\"accountId\": 1}")); + } + + private static AccountAuditEnvelope platformRegistration() { + return platformRegistration(UUID.fromString("e9659715-e257-4f88-847e-700653e101d1")); + } + + private static AccountAuditEnvelope platformRegistration(UUID auditEventId) { + String payload = "{\"accountId\":1}"; + return new AccountAuditEnvelope( + auditEventId, + "platform", + null, + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-09-24T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java new file mode 100644 index 0000000000..66227937ed --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class ExpiredConnectScopeCleanupJobTest { + @Test + void cleanupRepeatsFullBatchesWithOneCutoffAndStopsAfterPartialBatch() { + AccountConnectScopeRepository repository = mock(AccountConnectScopeRepository.class); + when(repository.deleteExpiredUnreferenced(any(Instant.class), eq(2))).thenReturn(2, 2, 1); + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob job = newJob(repository, meters, 2); + + job.cleanupExpiredConnectScopes(); + + ArgumentCaptor cutoffs = ArgumentCaptor.forClass(Instant.class); + verify(repository, times(3)).deleteExpiredUnreferenced(cutoffs.capture(), eq(2)); + assertThat(cutoffs.getAllValues()) + .containsExactly(cutoffs.getValue(), cutoffs.getValue(), cutoffs.getValue()); + verifyNoMoreInteractions(repository); + assertThat(deletedCount(meters)).isEqualTo(5); + assertThat(failureCount(meters)).isZero(); + assertThat(capSaturationCount(meters)).isZero(); + } + + @Test + void cleanupStopsAfterAnEmptyBatch() { + AccountConnectScopeRepository repository = mock(AccountConnectScopeRepository.class); + when(repository.deleteExpiredUnreferenced(any(Instant.class), eq(2))).thenReturn(0); + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob job = newJob(repository, meters, 2); + + job.cleanupExpiredConnectScopes(); + + verify(repository).deleteExpiredUnreferenced(any(Instant.class), eq(2)); + verifyNoMoreInteractions(repository); + assertThat(deletedCount(meters)).isZero(); + assertThat(failureCount(meters)).isZero(); + assertThat(capSaturationCount(meters)).isZero(); + } + + @Test + void cleanupCapsEachRunAtFiveFullBatches() { + AccountConnectScopeRepository repository = mock(AccountConnectScopeRepository.class); + when(repository.deleteExpiredUnreferenced(any(Instant.class), eq(2))).thenReturn(2); + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob job = newJob(repository, meters, 2); + + job.cleanupExpiredConnectScopes(); + + verify(repository, times(5)).deleteExpiredUnreferenced(any(Instant.class), eq(2)); + verifyNoMoreInteractions(repository); + assertThat(deletedCount(meters)).isEqualTo(10); + assertThat(failureCount(meters)).isZero(); + assertThat(capSaturationCount(meters)).isEqualTo(1); + } + + @Test + void cleanupKeepsEarlierCountsAndRecordsFailureWhenLaterBatchThrows() { + AccountConnectScopeRepository repository = mock(AccountConnectScopeRepository.class); + when(repository.deleteExpiredUnreferenced(any(Instant.class), eq(2))) + .thenReturn(2, 2, 2, 2) + .thenThrow(new IllegalStateException("private repository detail")); + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob job = newJob(repository, meters, 2); + + job.cleanupExpiredConnectScopes(); + + verify(repository, times(5)).deleteExpiredUnreferenced(any(Instant.class), eq(2)); + verifyNoMoreInteractions(repository); + assertThat(deletedCount(meters)).isEqualTo(8); + assertThat(failureCount(meters)).isEqualTo(1); + assertThat(capSaturationCount(meters)).isZero(); + } + + private static ExpiredConnectScopeCleanupJob newJob( + AccountConnectScopeRepository repository, SimpleMeterRegistry meters, int batchSize) { + return new ExpiredConnectScopeCleanupJob(repository, meters, batchSize, 60_000); + } + + private static double deletedCount(SimpleMeterRegistry meters) { + return meters.get("account.connect_scopes.cleanup.deleted").counter().count(); + } + + private static double failureCount(SimpleMeterRegistry meters) { + return meters.get("account.connect_scopes.cleanup.failure").counter().count(); + } + + private static double capSaturationCount(SimpleMeterRegistry meters) { + return meters.get("account.connect_scopes.cleanup.cap_saturation").counter().count(); + } +} 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 62213d54ff..0db02b400a 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 @@ -5,9 +5,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -28,6 +30,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.PingRequest; @@ -38,17 +44,85 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class AccountGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + WORKLOAD_NAMESPACE, + "game-session-service"); + + private static PlayerExecutionContext validPlayerContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId("10") + .setTenantId("20") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setSessionId("session-1") + .setRequestId("request-1") + .build(); + } + + private static IssueDirectTextConnectScopeRequest validScopeRequest() { + return IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setTenantId("20") + .setRealmId(REALM_ID) + .setWorldSlug("world") + .setRealmSlug("public") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setCatalogRevision(5) + .setPointerVersion(8) + .build(); + } + + private static JoinPublicProductionMembershipRequest validJoinRequest() { + return JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setConnectScopeId("scope-1") + .setRequestId("request-1") + .build(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT; + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + @AfterEach void tearDown() { SessionContext.clear(); @@ -80,6 +154,325 @@ public void onCompleted() {} assertEquals("pong", ref.get().getMessage()); } + @Test + void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.issueDirectTextConnectScope( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(DirectTextJoinTarget.class))) + .thenReturn(new DirectTextJoinScope("scope-1", "2026-09-24T12:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); + + assertTrue(observer.completed()); + assertEquals("scope-1", observer.response().getConnectScopeId()); + assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); + Mockito.verify(accountService) + .issueDirectTextConnectScope( + new DirectTextCallerContext( + 10L, + 20L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "realm:30", + 40L, + "session-1", + "request-1"), + new DirectTextJoinTarget( + 20L, + UUID.fromString(REALM_ID), + "world", + "public", + PLAYABLE_STATE_NAMESPACE_ID, + "realm:30", + 40L, + 5L, + 8L)); + } + + @Test + void joinPublicProductionMembershipPreservesStoredFailureOutcome() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.joinPublicProductionFromGameSession( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(JoinPublicProductionRequest.class))) + .thenReturn( + new JoinPublicProductionResult( + false, "ENTITLEMENT_UNAVAILABLE", 10L, 20L, 0L, 0L, 0L, true)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); + assertEquals("10", observer.response().getAccountId()); + assertEquals("20", observer.response().getTenantId()); + assertEquals("0", observer.response().getMembershipId()); + assertTrue(observer.response().getReplayed()); + assertFalse(observer.response().hasError()); + Mockito.verify(accountService) + .joinPublicProductionFromGameSession( + new DirectTextCallerContext( + 10L, + 20L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "realm:30", + 40L, + "session-1", + "request-1"), + new JoinPublicProductionRequest("scope-1", "request-1")); + } + + @Test + void issueDirectTextConnectScopeMapsUnexpectedFailureToRetryableUnavailable() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.issueDirectTextConnectScope( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(DirectTextJoinTarget.class))) + .thenThrow(new IllegalStateException("private backend detail")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); + + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + } + + @Test + void joinPublicProductionMembershipMapsUnexpectedFailureToRetryableUnavailable() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.joinPublicProductionFromGameSession( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(JoinPublicProductionRequest.class))) + .thenThrow(new IllegalStateException("private backend detail")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + } + + @Test + void protectedDirectTextMethodsRejectAbsentWrongSharedAndCrossNamespacePeers() { + List rejectedPeers = + java.util.Arrays.asList( + null, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + "test", + "world-management-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", "test", "account-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver issueObserver = + new RecordingObserver<>(); + RecordingObserver joinObserver = + new RecordingObserver<>(); + + withPeer(peer, () -> service.issueDirectTextConnectScope(validScopeRequest(), issueObserver)); + withPeer( + peer, () -> service.joinPublicProductionMembership(validJoinRequest(), joinObserver)); + + assertEquals("PERMISSION_DENIED", issueObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", joinObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + + IssueDirectTextConnectScopeRequest mismatchedTarget = + validScopeRequest().toBuilder().setRealmId(OTHER_REALM_ID).build(); + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setAccountId("NaN").build(); + JoinPublicProductionMembershipRequest mismatchedJoin = + validJoinRequest().toBuilder().setRequestId("request-2").build(); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver malformedObserver = + new RecordingObserver<>(); + RecordingObserver requestIdObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(mismatchedTarget, targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(malformedContext).build(), + malformedObserver)); + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(mismatchedJoin, requestIdObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", malformedObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", requestIdObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void joinRejectsRequestIdLongerThanThePublicContractBeforeCallingAccountService() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + String requestId = "j".repeat(JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH + 1); + PlayerExecutionContext playerContext = + validPlayerContext().toBuilder().setRequestId(requestId).build(); + JoinPublicProductionMembershipRequest request = + validJoinRequest().toBuilder() + .setPlayerContext(playerContext) + .setRequestId(requestId) + .build(); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer(GAME_SESSION_PEER, () -> service.joinPublicProductionMembership(request, observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeServiceCall(String requestId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder() + .setPlayerContext(validPlayerContext().toBuilder().setRequestId(requestId)) + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource(strings = {"30", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver contextObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setRealmId(realmId).build(), targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder() + .setPlayerContext(validPlayerContext().toBuilder().setRealmId(realmId).build()) + .build(), + contextObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", contextObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource( + strings = { + "shared-live", + "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", + "c6ed6a44c7e74f1881fc078a74e67c07" + }) + void directTextMethodsRejectNoncanonicalPlayableStateNamespaceIdsAtIngress(String namespaceId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setPlayableStateNamespaceId(namespaceId).build(); + RecordingObserver scopeObserver = + new RecordingObserver<>(); + RecordingObserver joinObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setPlayerContext(malformedContext).build(), + scopeObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(malformedContext).build(), + joinObserver)); + + assertEquals("INVALID_ARGUMENT", scopeObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", joinObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -227,7 +620,6 @@ void createAccountValidationErrorReturnsErrorDetail() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -260,7 +652,6 @@ void createAccountConflictReturnsApplicationError() { service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("demo@example.com") .setPassword("pass") @@ -275,7 +666,7 @@ void createAccountConflictReturnsApplicationError() { } @Test - void createAccountReturnsAccountIdAndTenant() { + void createAccountReturnsAccountIdForGlobalRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.createAccount(Mockito.any())) @@ -285,7 +676,6 @@ void createAccountReturnsAccountIdAndTenant() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -310,40 +700,8 @@ public void onCompleted() {} org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.accountservice.dto.CreateAccountRequest.class); Mockito.verify(accountService).createAccount(captor.capture()); - assertEquals(7L, captor.getValue().tenantId()); - } - - @Test - void createAccountRejectsZeroTenantIdBeforeCreate() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.createAccount( - CreateAccountRequest.newBuilder() - .setTenantId("0") - .setUsername("demo") - .setEmail("e@example.com") - .setPassword("pass") - .build(), - new StreamObserver() { - @Override - public void onNext(CreateAccountResponse 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(accountService); + assertEquals("demo", captor.getValue().username()); + assertEquals("e@example.com", captor.getValue().email()); } @Test @@ -520,7 +878,7 @@ void getTenantMembershipForRuntimeReturnsResponse() { Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, true, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -557,7 +915,7 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); 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 9e9271c01d..2b3aa8aa5d 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 @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; @@ -12,16 +13,15 @@ import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; import java.util.Map; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; 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.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; @@ -29,10 +29,16 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; @@ -44,7 +50,10 @@ import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -59,7 +68,6 @@ import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.SessionService; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; @@ -69,15 +77,28 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.SimpleTransactionStatus; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = + "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; + @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; + @Mock private AccountConnectScopeRepository accountConnectScopeRepository; + @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -88,14 +109,13 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); - @Mock private LoggingAdminClient loggingAdminClient; @Mock private GameSessionClient gameSessionClient; @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; - @Mock private SagaRunner sagaRunner; @Mock private PaymentTransactionRepository paymentTransactionRepository; @Mock private SubscriptionRepository subscriptionRepository; @Mock private ExternalAccountRepository externalAccountRepository; + @Mock private PlatformTransactionManager transactionManager; @Mock private EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -106,8 +126,11 @@ class AccountServiceImplTest { private AccountServiceImpl service; @BeforeEach - void setup() throws net.firedevops.firemud.common.saga.SagaException { + void setup() { MockitoAnnotations.openMocks(this); + when(transactionManager.getTransaction( + org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); Subscription explicitActiveEntitlement = new Subscription(); explicitActiveEntitlement.setId(1L); explicitActiveEntitlement.setTenantId(7L); @@ -143,6 +166,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -159,6 +185,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -177,6 +206,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -193,28 +225,24 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, sessionService, - sagaRunner); - org.mockito.Mockito.doAnswer( - inv -> { - ((net.firedevops.firemud.common.saga.Saga) inv.getArgument(0)).run(); - return null; - }) - .when(sagaRunner) - .run(org.mockito.ArgumentMatchers.any()); + transactionManager); } @Test - void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.SagaException { + void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@example.com ", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); + new CreateAccountRequest("demo", " DEMO@example.com ", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + return saved; + }); AccountDto dto = service.createAccount(request); @@ -224,13 +252,21 @@ void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.Sag org.mockito.ArgumentCaptor.forClass(Account.class); org.mockito.Mockito.verify(accountRepository).save(accountCaptor.capture()); assertEquals("demo@example.com", accountCaptor.getValue().getEmail()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("platform"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), + org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + assertEquals(null, accountCaptor.getValue().getRole()); + verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@EXAMPLE.COM ", "password"); + new CreateAccountRequest("demo", " DEMO@EXAMPLE.COM ", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.jooq.exception.IntegrityConstraintViolationException("duplicate")); @@ -242,15 +278,1313 @@ void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { @Test void createAccountMapsSpringDataIntegrityConflict() { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.springframework.dao.DataIntegrityViolationException("duplicate")); - AccountAlreadyExistsException exception = - assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + AccountAlreadyExistsException exception = + assertThrows(AccountAlreadyExistsException.class, () -> service.createAccount(request)); + + assertEquals("Account already exists", exception.getMessage()); + } + + @Test + void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String requestId = "j".repeat(128); + assertEquals(128, requestId.length()); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, requestId); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var committedOperation = retainedOperation.get(); + org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); + JoinPublicProductionResult retried = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + var normalReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); + normalReplayOrder + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + normalReplayOrder.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); + normalReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + + org.mockito.Mockito.doThrow( + new DataAccessResourceFailureException("terminal operation lock read failed")) + .when(accountJoinOperationRepository) + .findForUpdate(requestId); + org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); + JoinPublicProductionResult readbackReplay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + var readbackReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); + readbackReplayOrder + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + readbackReplayOrder.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + readbackReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + + ConnectTokenResult onboardingToken = + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join")); + + assertTrue(first.success()); + assertEquals("JOINED", first.outcomeCode()); + assertEquals(701L, first.membershipId()); + assertEquals(1L, first.membershipVersion()); + assertTrue(retried.success()); + assertTrue(retried.replayed()); + assertTrue(readbackReplay.success()); + assertTrue(readbackReplay.replayed()); + assertEquals(committedOperation, retainedOperation.get()); + assertNotNull(onboardingToken.connectToken()); + assertEquals(REALM_ID, retainedScope.get().realmId().toString()); + assertEquals( + first, + new JoinPublicProductionResult( + retried.success(), + retried.outcomeCode(), + retried.accountId(), + retried.tenantId(), + retried.membershipId(), + retried.membershipVersion(), + retried.membershipAuthorityGeneration(), + false)); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq(1L), + org.mockito.ArgumentMatchers.eq(true)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .finish( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.eq(701L), + org.mockito.ArgumentMatchers.eq(1L), + org.mockito.ArgumentMatchers.eq(1L)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains(requestId)); + assertEquals("COMMITTED", retainedOperation.get().status()); + + AuthenticationException changedDigest = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest("different-scope", requestId))); + assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); + } + + @Test + void joinPublicProductionRejectsRequestIdLongerThan128BeforeIntentLookupOrMutation() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + String requestId = "j".repeat(129); + DirectTextCallerContext baseCaller = directTextCaller(); + DirectTextCallerContext caller = + new DirectTextCallerContext( + baseCaller.accountId(), + baseCaller.tenantId(), + baseCaller.realmId(), + baseCaller.playableStateNamespaceId(), + baseCaller.playableStateScope(), + baseCaller.gameInstanceId(), + baseCaller.sessionId(), + requestId); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, new JoinPublicProductionRequest("retained-scope", requestId))); + + assertEquals("INVALID_ARGUMENT", exception.getCode()); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); + } + + @ParameterizedTest + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS" + }) + void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + account.setLifecycleState(lifecycleState); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-ineligible-1"))); + + assertEquals(expectedCode, exception.getCode()); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); + } + + @Test + void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); + + JoinPublicProductionResult denied = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(denied.success()); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); + assertFalse(retry.success()); + assertTrue(retry.replayed()); + assertEquals(denied.outcomeCode(), retry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + var storedDeniedOperation = retainedOperation.get(); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityReplay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityReplay.success()); + assertFalse(unavailableAuthorityReplay.replayed()); + assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); + assertEquals(storedDeniedOperation, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription originalPolicy = new Subscription(); + originalPolicy.setId(22L); + originalPolicy.setTenantId(7L); + originalPolicy.setStatus("active"); + originalPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(originalPolicy), java.util.List.of(changedPolicy)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(originalPolicy)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-terminal-policy-change-1"); + + JoinPublicProductionResult joined = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var committedOperation = retainedOperation.get(); + AccountTenantMembership membership = joinedMembership.get(); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(joined.success()); + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(membership, joinedMembership.get()); + assertEquals("ACTIVE", membership.getLifecycleState()); + assertEquals(1L, membership.getMembershipVersion()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityRetry.success()); + assertFalse(unavailableAuthorityRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals(membership, joinedMembership.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-terminal-policy-change-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription recovered = new Subscription(); + recovered.setId(22L); + recovered.setTenantId(7L); + recovered.setStatus("active"); + recovered.setEntitlementVersion(1L); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn( + ambiguous + ? java.util.List.of(new Subscription(), new Subscription()) + : java.util.List.of(), + java.util.List.of(recovered)); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(recovered)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(first.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().requestDigestVersion()); + assertEquals(null, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().entitlementVersion()); + + JoinPublicProductionResult retriedAfterRecovery = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(retriedAfterRecovery.success()); + assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertNotNull(retainedOperation.get().requestDigest()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-unavailable-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(changedPolicy)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(initialPolicy)); + org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-race-1")); + + assertFalse(result.success()); + assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1, retainedOperation.get().requestDigestVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); + var order = org.mockito.Mockito.inOrder(gameSessionClient, subscriptionRepository); + order.verify(gameSessionClient).listGameplayRealms("demo"); + order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + order.verify(subscriptionRepository).findByTenantId(7L); + order.verify(gameSessionClient).listGameplayRealms("demo"); + order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + order.verify(subscriptionRepository).findByTenantIdForUpdate(7L); + org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); + } + + @Test + void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); + + JoinPublicProductionResult pending = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + String boundDigest = retainedOperation.get().requestDigest(); + String intentDigest = retainedOperation.get().intentDigest(); + + assertFalse(pending.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + + JoinPublicProductionResult changedPolicyRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedPolicyRetry.success()); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); + } + + @Test + void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + var exactRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); + var exactPointer = gameSessionClient.getAdmissionPointer(7L, "demo", "production"); + var changedRealm = exactRealm.toBuilder().setPointerVersion(18L).build(); + var changedPointer = exactPointer.toBuilder().setPointerVersion(18L).build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedPointer); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unbound-failure-1"); + + JoinPublicProductionResult originalFailure = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var storedFailure = retainedOperation.get(); + + assertFalse(originalFailure.success()); + assertEquals("CONNECT_SCOPE_MISMATCH", originalFailure.outcomeCode()); + assertEquals("FAILED", storedFailure.status()); + assertEquals(originalFailure.outcomeCode(), storedFailure.outcome()); + assertNull(storedFailure.requestDigest()); + + JoinPublicProductionResult changedTargetDenial = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedTargetDenial.success()); + assertFalse(changedTargetDenial.replayed()); + assertEquals("CONNECT_SCOPE_MISMATCH", changedTargetDenial.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(exactRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")).thenReturn(exactPointer); + JoinPublicProductionResult replay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(replay.success()); + assertTrue(replay.replayed()); + assertEquals(originalFailure.outcomeCode(), replay.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + + VerifiedJoinScope originalScope = retainedScope.get(); + VerifiedJoinScope alteredScopeWithoutDigest = + new VerifiedJoinScope( + originalScope.connectScopeId(), + originalScope.accountId(), + originalScope.tenantId(), + originalScope.realmId(), + originalScope.worldSlug(), + originalScope.realmSlug(), + originalScope.playableStateNamespaceId(), + originalScope.playableStateScope(), + originalScope.gameInstanceId(), + originalScope.catalogRevision(), + originalScope.pointerVersion() + 1, + originalScope.evaluatedAt(), + originalScope.connectScopeExpiresAt(), + ""); + retainedScope.set( + new VerifiedJoinScope( + alteredScopeWithoutDigest.connectScopeId(), + alteredScopeWithoutDigest.accountId(), + alteredScopeWithoutDigest.tenantId(), + alteredScopeWithoutDigest.realmId(), + alteredScopeWithoutDigest.worldSlug(), + alteredScopeWithoutDigest.realmSlug(), + alteredScopeWithoutDigest.playableStateNamespaceId(), + alteredScopeWithoutDigest.playableStateScope(), + alteredScopeWithoutDigest.gameInstanceId(), + alteredScopeWithoutDigest.catalogRevision(), + alteredScopeWithoutDigest.pointerVersion(), + alteredScopeWithoutDigest.evaluatedAt(), + alteredScopeWithoutDigest.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( + alteredScopeWithoutDigest))); + + AuthenticationException changedScope = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("IDEMPOTENCY_CONFLICT", changedScope.getCode()); + assertEquals(storedFailure, retainedOperation.get()); + + retainedScope.set(originalScope); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthority = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(unavailableAuthority.success()); + assertFalse(unavailableAuthority.replayed()); + assertEquals("AUTH_UNAVAILABLE", unavailableAuthority.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)) + .thenThrow(new IllegalStateException("entitlement storage unavailable")); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) + .commit(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + .rollback(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + @Test + void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); + + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + expiredScope = + new VerifiedJoinScope( + expiredScope.connectScopeId(), + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), + expiredScope.evaluatedAt(), + expiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "UNAVAILABLE", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + "ENTITLEMENT_UNAVAILABLE", + "UNAVAILABLE")); + + JoinPublicProductionResult expiredRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var expiredTerminalOperation = retainedOperation.get(); + JoinPublicProductionResult terminalReadback = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(expiredRetry.success()); + assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); + assertFalse(terminalReadback.success()); + assertFalse(terminalReadback.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); + assertEquals(expiredTerminalOperation, retainedOperation.get()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .finish( + org.mockito.ArgumentMatchers.eq(request.requestId()), + org.mockito.ArgumentMatchers.eq("FAILED"), + org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-committed-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); + VerifiedJoinScope unsignedExpiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + unsignedExpiredScope.connectScopeId(), + unsignedExpiredScope.accountId(), + unsignedExpiredScope.tenantId(), + unsignedExpiredScope.realmId(), + unsignedExpiredScope.worldSlug(), + unsignedExpiredScope.realmSlug(), + unsignedExpiredScope.playableStateNamespaceId(), + unsignedExpiredScope.playableStateScope(), + unsignedExpiredScope.gameInstanceId(), + unsignedExpiredScope.catalogRevision(), + unsignedExpiredScope.pointerVersion(), + unsignedExpiredScope.evaluatedAt(), + unsignedExpiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( + unsignedExpiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + var committedOperation = + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "AVAILABLE", + true, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + expiredScope, callerBinding, true, 1L), + "COMMITTED", + "JOINED", + 701L, + 1L, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + null, + "AVAILABLE"); + retainedOperation.set(committedOperation); + + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(701L, retainedOperation.get().membershipId()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"PENDING", "COMMITTED", "FAILED"}) + void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + String requestId = "join-global-collision-" + originalStatus.toLowerCase(); + String originalOutcome = + switch (originalStatus) { + case "COMMITTED" -> "JOINED"; + case "FAILED" -> "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + default -> null; + }; + Long originalMembershipId = "COMMITTED".equals(originalStatus) ? 812L : null; + AccountJoinOperationRepository.JoinOperation originalOperation = + new AccountJoinOperationRepository.JoinOperation( + 12L, + scope.tenantId(), + scope.realmId(), + "different-caller", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + scope.snapshotDigest(), + "COMMITTED".equals(originalStatus) || "FAILED".equals(originalStatus) + ? "AVAILABLE" + : "NOT_EVALUATED", + "PENDING".equals(originalStatus) ? null : true, + "PENDING".equals(originalStatus) ? null : 7L, + "PENDING".equals(originalStatus) ? null : 1, + "PENDING".equals(originalStatus) ? null : "original-request-digest", + originalStatus, + originalOutcome, + originalMembershipId, + originalMembershipId == null ? null : 9L, + originalMembershipId == null ? null : 5L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + requestId, scope, "different-caller"), + null, + "AVAILABLE"); + retainedOperation.set(originalOperation); + + AuthenticationException conflict = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, requestId))); + + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); + assertEquals("JOIN request ID was reused with different input", conflict.getMessage()); + assertFalse(conflict.getMessage().contains("JOINED")); + assertFalse(conflict.getMessage().contains("PUBLIC_PRODUCTION_ADMISSION_DENIED")); + assertFalse(conflict.getMessage().contains("812")); + assertEquals(originalOperation, retainedOperation.get()); + assertEquals(originalStatus, retainedOperation.get().status()); + assertEquals(originalOutcome, retainedOperation.get().outcome()); + assertEquals(originalMembershipId, retainedOperation.get().membershipId()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .find(org.mockito.ArgumentMatchers.eq(requestId)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void reclaimedScopeRaceReturnsConnectScopeInvalid() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + org.mockito.Mockito.clearInvocations( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + when(accountConnectScopeRepository.find(connectScopeId)) + .thenReturn(Optional.of(scope), Optional.empty()); + org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("scope reclaimed")) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-reclaimed-scope"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AccountTenantMembership quarantined = membership(account, 7L); + quarantined.setLifecycleState("LEGACY_UNVERIFIED"); + quarantined.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(quarantined)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); - assertEquals("Account already exists", exception.getMessage()); + assertFalse(result.success()); + assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); + assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); + assertFalse(quarantined.isGameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + private void retainJoinEvidence( + AtomicReference retainedScope, + AtomicReference retainedOperation) { + org.mockito.Mockito.doAnswer( + invocation -> { + retainedScope.set(invocation.getArgument(0)); + return null; + }) + .when(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); + when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + String requestId = invocation.getArgument(0); + VerifiedJoinScope scope = invocation.getArgument(1); + String callerBinding = invocation.getArgument(2); + String intentDigest = invocation.getArgument(3); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + "NOT_EVALUATED", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + intentDigest, + null, + "NOT_EVALUATED")); + return true; + }) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + "AVAILABLE", + invocation.getArgument(3), + invocation.getArgument(2), + 1, + invocation.getArgument(1), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE")); + return null; + }) + .when(accountJoinOperationRepository) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + String availability = invocation.getArgument(1); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.requestDigest() == null + ? availability + : pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + invocation.getArgument(2), + availability)); + return null; + }) + .when(accountJoinOperationRepository) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + pending.lastAttemptAuthorityAvailability())); + return null; + }) + .when(accountJoinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); } @Test @@ -501,25 +1835,6 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); } - @Test - void createAccountContinuesWhenAuditLoggingFails() - throws net.firedevops.firemud.common.saga.SagaException { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); - org.mockito.Mockito.doThrow(new StatusRuntimeException(Status.UNAVAILABLE)) - .when(loggingAdminClient) - .logAccountCreation(7L, 1L); - - AccountDto dto = service.createAccount(request); - - assertEquals(1L, dto.id()); - assertEquals("demo", dto.username()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); - } - @Test void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); @@ -535,7 +1850,7 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); org.mockito.Mockito.verify(sessionService) @@ -581,7 +1896,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -738,6 +2053,9 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -754,12 +2072,11 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, sessionService, - sagaRunner); + transactionManager); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); @@ -776,13 +2093,17 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(gameSessionClient.listGameplayRealms("demo")) .thenReturn( - java.util.List.of( + java.util.Arrays.asList( + null, net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() .setWorldSlug("demo") .setRealmSlug("broken") .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -802,6 +2123,29 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } + @Test + void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenThrow( + new IllegalStateException( + "Gameplay realm discovery failed: invalid public realm cardinality")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + @Test void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); @@ -818,6 +2162,9 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -837,6 +2184,181 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } + @Test + void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + var firstPublicRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); + var secondPublicRealm = + firstPublicRealm.toBuilder() + .setRealmSlug("production-alt") + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .setGameInstanceId("45") + .build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(firstPublicRealm, secondPublicRealm)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals("production", realms.getFirst().realmSlug()); + } + + @Test + void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransactions() + throws NoSuchMethodException { + Transactional listRealms = + AccountServiceImpl.class + .getMethod("listBootstrapRealms", String.class, String.class) + .getAnnotation(Transactional.class); + Transactional issueDirectTextScope = + AccountServiceImpl.class + .getMethod( + "issueDirectTextConnectScope", + DirectTextCallerContext.class, + DirectTextJoinTarget.class) + .getAnnotation(Transactional.class); + + assertNotNull(listRealms); + assertNotNull(issueDirectTextScope); + assertEquals(Propagation.NOT_SUPPORTED, listRealms.propagation()); + assertEquals(Propagation.NOT_SUPPORTED, issueDirectTextScope.propagation()); + } + + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "production")) + .thenReturn(true); + + var initiallyPublic = gameSessionClient.listGameplayRealms("demo").getFirst(); + var currentlyPrivate = initiallyPublic.toBuilder().setPublicProductionRealm(false).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyPublic), java.util.List.of(currentlyPrivate)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, false, "SHARED", "ALLOW_NEW")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + var initiallyDiscovered = gameSessionClient.listGameplayRealms("demo").getFirst(); + var changedRealmId = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + var currentRealm = + initiallyDiscovered.toBuilder().setRealmId(changedRealmId).setPointerVersion(18L).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyDiscovered), java.util.List.of(currentRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer(7L, "demo", "production", "44", 18L, true, true, "SHARED", "ALLOW_NEW") + .toBuilder() + .setRealmId(changedRealmId) + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(realmId) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + @Test void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); @@ -1001,6 +2523,59 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", realmId), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString()), + Map.entry("jti", "invalid-realm-id"))); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); @@ -1237,7 +2812,9 @@ void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { assertEquals(7L, dto.tenantId()); assertTrue(dto.membershipExists()); assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(711L, dto.membershipVersion()); + assertEquals(1L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(1L, dto.membershipAuthorityGeneration()); assertNotNull(dto.evaluatedAt()); } @@ -1277,44 +2854,119 @@ void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions() { var dto = service.getTenantEntitlementsForRuntime(7L, "req-2"); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.gameplayAvailable()); - assertTrue(dto.allowPublicJoin()); - assertEquals(31L, dto.entitlementVersion()); - assertEquals(31L, dto.tenantBillingSequence()); - assertNotNull(dto.evaluatedAt()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.gameplayAvailable()); + assertTrue(dto.allowPublicJoin()); + assertEquals(1L, dto.entitlementVersion()); + assertEquals(1L, dto.tenantBillingSequence()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + + @Test + void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + Subscription canceled = new Subscription(); + canceled.setId(32L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } @Test - void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { + void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( + String requestId) { + DirectTextCallerContext caller = + new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + "session-1", + requestId); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(caller, directTextTarget())); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions(accountRepository, subscriptionRepository, accountConnectScopeRepository); } @Test - void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { - Subscription active = new Subscription(); - active.setId(31L); - active.setTenantId(7L); - active.setStatus("active"); + void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); Subscription canceled = new Subscription(); - canceled.setId(32L); + canceled.setId(31L); canceled.setTenantId(7L); canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + DirectTextJoinScope result = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + assertNotNull(result.connectScopeId()); + assertNotNull(result.connectScopeExpiresAt()); + org.mockito.Mockito.verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); } @Test @@ -1464,6 +3116,9 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1479,9 +3134,10 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-4"))); - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", ex.getMessage()); } @@ -1514,6 +3170,9 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1569,6 +3228,9 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { .setDisplayName("Live Realm") .setTenantId("") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1628,6 +3290,9 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1732,6 +3397,49 @@ void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); } + @ParameterizedTest + @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) + void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( + String subscriptionStatus, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(subscriptionStatus); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-inactive-public"))); + + assertEquals(expectedCode, exception.getCode()); + if ("JOIN_REQUIRED".equals(expectedCode)) { + assertEquals( + "Join the selected world before requesting a connect token", exception.getMessage()); + } else { + assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); + } + } + @Test void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically() { Account account = new Account(); @@ -1819,6 +3527,9 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(publicProductionRealm) @@ -1835,6 +3546,9 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(publicProductionRealm) @@ -1906,6 +3620,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1921,13 +3638,14 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", firstFailure.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", firstFailure.getCode()); when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-fail-1")) .thenReturn( Optional.of( new SessionService.ConnectTokenReplay( - false, null, "CONNECT_SCOPE_MISMATCH", firstFailure.getMessage()))); + false, null, "ADMISSION_POINTER_UNAVAILABLE", firstFailure.getMessage()))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -1937,6 +3655,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1953,10 +3674,10 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", replayedFailure.getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", replayedFailure.getCode()); assertEquals(firstFailure.getMessage(), replayedFailure.getMessage()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", replayedFailure.getMessage()); } @@ -2084,6 +3805,48 @@ void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() verifyNoInteractions(entityManagementClient); } + @ParameterizedTest + @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) + void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( + String subscriptionStatus, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(subscriptionStatus); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals(expectedCode, exception.getCode()); + if ("JOIN_REQUIRED".equals(expectedCode)) { + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } else { + assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); + } + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); @@ -2112,6 +3875,8 @@ void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnav bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); } @@ -2135,6 +3900,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) @@ -2152,6 +3920,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setRealmDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) @@ -2205,6 +3976,9 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2255,6 +4029,9 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2291,10 +4068,68 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); assertEquals(1, realms.size()); + assertEquals(REALM_ID, realms.getFirst().realmId()); + assertEquals( + REALM_ID, + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload() + .get("realmId")); assertEquals("SHARED", realms.getFirst().stateScope()); + assertEquals(23L, realms.getFirst().catalogRevision()); + assertEquals(PLAYABLE_STATE_NAMESPACE_ID, realms.getFirst().playableStateNamespaceId()); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } + @ParameterizedTest + @ValueSource( + strings = { + "shared-live", + "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", + "c6ed6a44c7e74f1881fc078a74e67c07" + }) + void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachableRealm( + String namespaceId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(namespaceId) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); @@ -2311,6 +4146,9 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2323,6 +4161,9 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { .setDisplayName("Private Preview Realm") .setTenantId("7") .setGameInstanceId("45") + .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(false) @@ -2334,6 +4175,25 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( 11L, 7L, "demo", "preview")) .thenReturn(true); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("preview") + .setRealmDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -2376,6 +4236,9 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { .setDisplayName("Sandbox Realm") .setTenantId("7") .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -2427,6 +4290,9 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( .setDisplayName("Sandbox Realm") .setTenantId("8") .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -2448,6 +4314,14 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( java.util.List.of("demo"), worldsWithCanceledTenant.stream().map(world -> world.worldSlug()).toList()); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); + AuthenticationException unavailableSandbox = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); + Subscription activeSandbox = new Subscription(); activeSandbox.setId(3L); activeSandbox.setTenantId(8L); @@ -2461,9 +4335,9 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(8L); } @@ -2487,6 +4361,59 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @Test + void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("8") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantId(7L); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantId(8L); + } + @Test void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { Account account = new Account(); @@ -2503,6 +4430,9 @@ void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { .setDisplayName("Private Preview Realm") .setTenantId("7") .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(false) @@ -2544,6 +4474,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2557,6 +4490,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2595,6 +4531,9 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2634,6 +4573,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2650,6 +4592,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2695,6 +4640,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2702,6 +4649,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("bad") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2738,6 +4688,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2745,6 +4697,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2789,6 +4744,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2805,6 +4763,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2821,6 +4782,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2854,7 +4818,8 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat assertEquals("char-sandbox-1", characters.getFirst().characterId()); assertEquals("BuilderMara", characters.getFirst().characterName()); assertEquals("ISOLATED", characters.getFirst().stateScope()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "sandbox", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "sandbox", "production"); } @Test @@ -2877,6 +4842,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Seven") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2889,12 +4857,23 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Eight") .setTenantId("8") .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); + when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) + .thenReturn( + admissionPointer( + 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); when(entityManagementClient.listCharactersByAccount( 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(java.util.List.of()); @@ -2913,9 +4892,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { bootstrap.bootstrapToken(), "demo", "production", connectScopeId); assertTrue(characters.isEmpty()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) - .getAdmissionPointer(8L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); } @Test @@ -2945,6 +4924,44 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { verifyNoInteractions(entityManagementClient); } + @Test + void listBootstrapCharactersRejectsChangedCanonicalRealmId() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = + gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedAdmissionPointer); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); @@ -2969,12 +4986,19 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(false) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -3010,6 +5034,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3026,6 +5053,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3067,6 +5097,9 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3074,6 +5107,18 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, + "demo", + "preview", + "55", + 19L, + visible, + publicProductionRealm, + "SHARED", + "ALLOW_NEW")); when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( 11L, 7L, "demo", "preview")) .thenReturn(true); @@ -3114,6 +5159,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3130,6 +5178,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3647,6 +5698,38 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private static Account directTextAccount() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + return account; + } + + private static DirectTextCallerContext directTextCaller() { + return new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + "session-1", + "direct-text-request-1"); + } + + private static DirectTextJoinTarget directTextTarget() { + return new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); + } + private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); @@ -3657,12 +5740,57 @@ private static String hash(String password) { } } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( + long tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy) { + return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(worldSlug) + .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") + .setRealmSlug(realmSlug) + .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(gameInstanceId) + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(playableStateNamespaceIdForTenant(tenantId)) + .setCatalogRevision(23L) + .setPointerVersion(pointerVersion) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope(stateScope) + .setCharacterCreationPolicy(characterCreationPolicy) + .build(); + } + + private static String playableStateNamespaceIdForTenant(long tenantId) { + return switch ((int) tenantId) { + case 7 -> PLAYABLE_STATE_NAMESPACE_ID; + case 8 -> PLAYABLE_STATE_NAMESPACE_ID_TENANT_8; + default -> + UUID.nameUUIDFromBytes( + ("playable-state-namespace-" + tenantId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .toString(); + }; + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); membership.setAccount(account); membership.setTenantId(tenantId); membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("SEEDED_DEMO"); return membership; } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java new file mode 100644 index 0000000000..c37359c20b --- /dev/null +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.test; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class AccountAuditProtoContractTest { + @Test + void createRequestKeepsTenantIdentityAndReservesRemovedLegacyFields() { + Descriptor descriptor = CreateLogEventRequest.getDescriptor(); + + assertField(descriptor, "tenant_id", 1, FieldDescriptor.Type.STRING); + assertField(descriptor, "scope", 5, FieldDescriptor.Type.ENUM); + assertField(descriptor, "audit_event_id", 6, FieldDescriptor.Type.STRING); + assertField(descriptor, "producer_service", 7, FieldDescriptor.Type.STRING); + assertField(descriptor, "event_type", 8, FieldDescriptor.Type.STRING); + assertField(descriptor, "occurred_at", 9, FieldDescriptor.Type.MESSAGE); + assertField(descriptor, "schema_version", 10, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload", 11, FieldDescriptor.Type.BYTES); + assertField(descriptor, "payload_digest_version", 12, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload_digest", 13, FieldDescriptor.Type.STRING); + assertThat(descriptor.findFieldByNumber(2)).isNull(); + assertThat(descriptor.findFieldByNumber(3)).isNull(); + assertThat(descriptor.findFieldByNumber(4)).isNull(); + assertThat(descriptor.toProto().getReservedRangeCount()).isEqualTo(1); + assertThat(descriptor.toProto().getReservedRange(0).getStart()).isEqualTo(2); + assertThat(descriptor.toProto().getReservedRange(0).getEnd()).isEqualTo(5); + assertThat(descriptor.toProto().getReservedNameList()) + .containsExactlyInAnyOrder("account_id", "type", "message"); + } + + @Test + void createResponseKeepsLegacyIdentityAndErrorNumbers() { + Descriptor descriptor = CreateLogEventResponse.getDescriptor(); + + assertField(descriptor, "log_event_id", 1, FieldDescriptor.Type.STRING); + assertErrorField(descriptor, "error", 2); + assertField(descriptor, "scope", 3, FieldDescriptor.Type.ENUM); + assertField(descriptor, "tenant_id", 4, FieldDescriptor.Type.STRING); + assertField(descriptor, "audit_event_id", 5, FieldDescriptor.Type.STRING); + assertField(descriptor, "receipt_id", 6, FieldDescriptor.Type.STRING); + assertField(descriptor, "schema_version", 7, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload_digest_version", 8, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload_digest", 9, FieldDescriptor.Type.STRING); + assertField(descriptor, "status", 10, FieldDescriptor.Type.ENUM); + assertField(descriptor, "outcome", 11, FieldDescriptor.Type.ENUM); + assertThat(descriptor.findFieldByName("scope").getEnumType()) + .isEqualTo(AccountAuditScope.getDescriptor()); + assertThat(descriptor.findFieldByName("status").getEnumType()) + .isEqualTo(AccountAuditReceiptStatus.getDescriptor()); + assertThat(descriptor.findFieldByName("outcome").getEnumType()) + .isEqualTo(AccountAuditReceiptOutcome.getDescriptor()); + } + + @Test + void receiptReadResponseAddsErrorDetailAtTheNextFreeNumber() { + Descriptor descriptor = ReadLogEventReceiptResponse.getDescriptor(); + + assertField(descriptor, "scope", 1, FieldDescriptor.Type.ENUM); + assertField(descriptor, "tenant_id", 2, FieldDescriptor.Type.STRING); + assertField(descriptor, "audit_event_id", 3, FieldDescriptor.Type.STRING); + assertField(descriptor, "receipt_id", 4, FieldDescriptor.Type.STRING); + assertField(descriptor, "log_event_id", 5, FieldDescriptor.Type.STRING); + assertField(descriptor, "schema_version", 6, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload_digest_version", 7, FieldDescriptor.Type.INT32); + assertField(descriptor, "payload_digest", 8, FieldDescriptor.Type.STRING); + assertField(descriptor, "status", 9, FieldDescriptor.Type.ENUM); + assertField(descriptor, "outcome", 10, FieldDescriptor.Type.ENUM); + assertErrorField(descriptor, "error", 11); + } + + private static void assertField( + Descriptor descriptor, String name, int number, FieldDescriptor.Type type) { + FieldDescriptor field = descriptor.findFieldByName(name); + assertThat(field).isNotNull(); + assertThat(field.getNumber()).isEqualTo(number); + assertThat(field.getType()).isEqualTo(type); + } + + private static void assertErrorField(Descriptor descriptor, String name, int number) { + assertField(descriptor, name, number, FieldDescriptor.Type.MESSAGE); + assertThat(descriptor.findFieldByName(name).getMessageType()) + .isEqualTo(ErrorDetail.getDescriptor()); + } +} diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 30a088e01d..3c1a72bac0 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -2,11 +2,23 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.util.List; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; class AccountRuntimeStubServerCompatibilityTest { + private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; + private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = Set.of( "CreateAccount", @@ -37,5 +49,221 @@ void accountServiceMethodSetIsFullyCategorized() { AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), NON_RUNTIME_METHODS.stream()) .collect(java.util.stream.Collectors.toSet())); + + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); + } + + @Test + void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { + Descriptor descriptor = + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse.getDescriptor(); + + assertField(descriptor, "membership_version", 6, FieldDescriptor.Type.UINT64); + assertField(descriptor, "membership_authority_generation", 7, FieldDescriptor.Type.UINT64); + } + + @Test + void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRealmAccess() + throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + + server.denyGameplayAdmission(); + var existingButNonAdmitting = + stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + assertThat(existingButNonAdmitting.getMembershipExists()).isTrue(); + assertThat(existingButNonAdmitting.getGameplayAdmissionAllowed()).isFalse(); + assertThat(existingButNonAdmitting.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(existingButNonAdmitting.getMembershipAuthorityGeneration()).isEqualTo(1L); + + server.setMembershipExists(false); + var missing = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + assertThat(missing.getMembershipExists()).isFalse(); + assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); + assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(missing.getMembershipAuthorityGeneration()).isZero(); + + server.setRealmAccessGranted(false); + PlayerExecutionContext caller = + PlayerExecutionContext.newBuilder() + .setAccountId("7") + .setTenantId("11") + .setRealmId(REALM_ID) + .setGameInstanceId("33") + .setSessionId("session-1") + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setPlayableStateScope("SHARED") + .setRequestId("join-request-1") + .build(); + var connectScope = + stub.issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(caller) + .setTenantId("11") + .setWorldSlug("demo") + .setRealmSlug("live") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setPlayableStateScope("SHARED") + .setGameInstanceId("33") + .setCatalogRevision(1L) + .setPointerVersion(1L) + .build()); + assertThat(connectScope.getError().getCode()).isEmpty(); + + var join = + stub.joinPublicProductionMembership( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(caller) + .setConnectScopeId(connectScope.getConnectScopeId()) + .setRequestId("join-request-1") + .build()); + assertThat(join.getSuccess()).isTrue(); + + var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + assertThat(afterJoin.getMembershipExists()).isTrue(); + assertThat(afterJoin.getGameplayAdmissionAllowed()).isTrue(); + assertThat(afterJoin.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(afterJoin.getMembershipAuthorityGeneration()).isEqualTo(1L); + + var realmGrant = + stub.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("11") + .setWorldSlug("demo") + .setRealmSlug("live") + .build()); + assertThat(realmGrant.getGranted()).isFalse(); + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + IssueDirectTextConnectScopeRequest validRequest = validConnectScopeRequest(); + List invalidRequests = + List.of( + validRequest.toBuilder().setRealmId("22").build(), + validRequest.toBuilder() + .setRealmId("22") + .setPlayerContext(validRequest.getPlayerContext().toBuilder().setRealmId("22")) + .build(), + validRequest.toBuilder().setPlayableStateNamespaceId("namespace-1").build(), + validRequest.toBuilder() + .setPlayableStateNamespaceId("namespace-1") + .setPlayerContext( + validRequest.getPlayerContext().toBuilder() + .setPlayableStateNamespaceId("namespace-1")) + .build(), + validRequest.toBuilder() + .setPlayerContext( + validRequest.getPlayerContext().toBuilder().setRequestId(" ")) + .build(), + validRequest.toBuilder().setCatalogRevision(0L).build(), + validRequest.toBuilder().setPointerVersion(-1L).build()); + + for (IssueDirectTextConnectScopeRequest request : invalidRequests) { + var response = stub.issueDirectTextConnectScope(request); + assertThat(response.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(response.getConnectScopeId()).isEmpty(); + } + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + IssueDirectTextConnectScopeRequest scopeRequest = validConnectScopeRequest(); + String connectScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); + JoinPublicProductionMembershipRequest validJoin = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(connectScopeId) + .setRequestId("join-request-1") + .build(); + + var blankSession = + stub.joinPublicProductionMembership( + validJoin.toBuilder() + .setPlayerContext(validJoin.getPlayerContext().toBuilder().setSessionId(" ")) + .build()); + assertThat(blankSession.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(blankSession.getSuccess()).isFalse(); + + assertThat(stub.joinPublicProductionMembership(validJoin).getSuccess()).isTrue(); + server.resetRuntimeState(); + + var afterReset = stub.joinPublicProductionMembership(validJoin); + assertThat(afterReset.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(afterReset.getSuccess()).isFalse(); + } finally { + channel.shutdownNow(); + } + } + } + + private static IssueDirectTextConnectScopeRequest validConnectScopeRequest() { + PlayerExecutionContext caller = + PlayerExecutionContext.newBuilder() + .setAccountId("7") + .setTenantId("11") + .setRealmId(REALM_ID) + .setGameInstanceId("33") + .setSessionId("session-1") + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setPlayableStateScope("SHARED") + .setRequestId("join-request-1") + .build(); + return IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(caller) + .setTenantId("11") + .setWorldSlug("demo") + .setRealmSlug("live") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setPlayableStateScope("SHARED") + .setGameInstanceId("33") + .setCatalogRevision(1L) + .setPointerVersion(1L) + .build(); + } + + private static void assertField( + Descriptor descriptor, String name, int number, FieldDescriptor.Type type) { + FieldDescriptor field = descriptor.findFieldByName(name); + assertThat(field).isNotNull(); + assertThat(field.getNumber()).isEqualTo(number); + assertThat(field.getType()).isEqualTo(type); + } + + private static GetTenantMembershipForRuntimeRequest membershipRequest( + String accountId, String tenantId) { + return GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setRequestId("membership-request") + .build(); } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 06a325ea23..4bb8d1f7a5 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -4,9 +4,11 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; @@ -22,12 +24,18 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.account.AccountProfileJson; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase @@ -39,7 +47,9 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe "Authenticate", "GetTenantMembershipForRuntime", "GetRealmAccessGrantForRuntime", - "GetTenantEntitlementsForRuntime"); + "GetTenantEntitlementsForRuntime", + "IssueDirectTextConnectScope", + "JoinPublicProductionMembership"); private final Server server; private final List authenticateRequests = new CopyOnWriteArrayList<>(); @@ -49,8 +59,10 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); private final AtomicLong defaultAccountId = new AtomicLong(1L); + private final AtomicLong nextConnectScopeId = new AtomicLong(1L); private final Map accountIdsByEmail = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); + private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { this.server = NettyServerBuilder.forPort(port).addService(this).build().start(); @@ -125,6 +137,7 @@ public void resetRuntimeState() { allowPublicJoin.set(true); realmAccessGranted.set(true); profilesByAccountId.clear(); + connectScopesById.clear(); } @Override @@ -160,6 +173,8 @@ public void getTenantMembershipForRuntime( .setMembershipExists(exists) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .setMembershipVersion(exists ? 1L : 0L) + .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") + .setMembershipAuthorityGeneration(exists ? 1L : 0L) .setEvaluatedAt(EVALUATED_AT) .build()); responseObserver.onCompleted(); @@ -198,6 +213,128 @@ public void getTenantEntitlementsForRuntime( responseObserver.onCompleted(); } + @Override + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + if (caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || caller.getRealmId().isBlank() + || caller.getRequestId().isBlank() + || caller.getGameInstanceId().isBlank() + || caller.getPlayableStateNamespaceId().isBlank() + || caller.getPlayableStateScope().isBlank() + || request.getTenantId().isBlank() + || request.getRealmId().isBlank() + || request.getGameInstanceId().isBlank() + || request.getWorldSlug().isBlank() + || request.getRealmSlug().isBlank() + || request.getPlayableStateNamespaceId().isBlank() + || request.getPlayableStateScope().isBlank() + || request.getCatalogRevision() <= 0 + || request.getPointerVersion() <= 0 + || !isCanonicalUuid(caller.getRealmId()) + || !isCanonicalUuid(request.getRealmId()) + || !isCanonicalUuid(caller.getPlayableStateNamespaceId()) + || !isCanonicalUuid(request.getPlayableStateNamespaceId()) + || !caller.getTenantId().equals(request.getTenantId()) + || !caller.getRealmId().equals(request.getRealmId()) + || !caller.getGameInstanceId().equals(request.getGameInstanceId()) + || !caller.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.getPlayableStateScope().equals(request.getPlayableStateScope())) { + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text connect scope request is incomplete")) + .build()); + } else { + String scopeId = "stub-connect-scope-" + nextConnectScopeId.getAndIncrement(); + Instant expiresAt = Instant.now().plusSeconds(300); + connectScopesById.put( + scopeId, + new StubConnectScope( + caller.getAccountId(), + request.getTenantId(), + request.getRealmId(), + request.getGameInstanceId(), + request.getPlayableStateNamespaceId(), + request.getPlayableStateScope(), + expiresAt)); + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setConnectScopeExpiresAt(expiresAt.toString()) + .build()); + } + responseObserver.onCompleted(); + } + + private static boolean isCanonicalUuid(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } + + @Override + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); + if (request.getConnectScopeId().isBlank() + || request.getRequestId().isBlank() + || !request.getRequestId().equals(caller.getRequestId()) + || caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || caller.getSessionId().isBlank() + || scope == null + || !scope.expiresAt().isAfter(Instant.now()) + || !scope.accountId().equals(caller.getAccountId()) + || !scope.tenantId().equals(caller.getTenantId()) + || !scope.realmId().equals(caller.getRealmId()) + || !scope.gameInstanceId().equals(caller.getGameInstanceId()) + || !scope.playableStateNamespaceId().equals(caller.getPlayableStateNamespaceId()) + || !scope.playableStateScope().equals(caller.getPlayableStateScope())) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text JOIN request is incomplete")) + .build()); + } else if (!allowPublicJoin.get()) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build()); + } else { + membershipExists.set(true); + gameplayAdmissionAllowed.set(true); + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId( + "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .build()); + } + responseObserver.onCompleted(); + } + @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { @@ -262,4 +399,13 @@ private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { visibilityPolicy == null ? DEFAULT_VISIBILITY_POLICY : visibilityPolicy); } } + + private record StubConnectScope( + String accountId, + String tenantId, + String realmId, + String gameInstanceId, + String playableStateNamespaceId, + String playableStateScope, + Instant expiresAt) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index 516147c63f..eaa5b07d51 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -30,6 +30,9 @@ public final class GameplayStageCommandConstants { public static final String AUTH_UNAVAILABLE_CODE = AuthenticationErrorCodes.UNAVAILABLE; public static final String AUTH_UNAVAILABLE_MESSAGE = "Gameplay authority is temporarily unavailable. Retry PLAY shortly."; + public static final String ADMISSION_POINTER_UNAVAILABLE_CODE = "ADMISSION_POINTER_UNAVAILABLE"; + public static final String ADMISSION_POINTER_UNAVAILABLE_MESSAGE = + "Gameplay admission pointer is temporarily unavailable. Retry PLAY shortly."; public static final String ENTITLEMENT_UNAVAILABLE_CODE = "ENTITLEMENT_UNAVAILABLE"; public static final String ENTITLEMENT_UNAVAILABLE_MESSAGE = "Gameplay entitlement is temporarily unavailable. Retry PLAY shortly."; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 90c6076f91..c182c81d4b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -215,6 +215,10 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); + if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedRealm.tenantId())) { + return admissionPointerUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); + } try (GameplayLoggingContext worldContext = GameplayLoggingContext.open( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), null, null)) { @@ -836,6 +840,19 @@ private PlayCommandHandlingResult authorityUnavailableFailure( null); } + private PlayCommandHandlingResult admissionPointerUnavailableFailure( + String tenantTag, String gameInstanceTag) { + return failure( + GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_CODE, + GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_MESSAGE, + "error.play.admission-pointer-unavailable", + Map.of(), + tenantTag, + gameInstanceTag, + null, + null); + } + private PlayCommandHandlingResult entitlementUnavailableFailure( String tenantTag, String gameInstanceTag, long requestedCharacterId) { return failure( diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index f076ab4f29..cc917e432a 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -22,6 +22,7 @@ error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. error.play.join-required=Membership is required before PLAY; joining this world is not available yet. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. +error.play.admission-pointer-unavailable=Gameplay admission pointer is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. error.look.room-not-found=Room not found. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 3d8d8309fc..7df38878ab 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -22,6 +22,7 @@ error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. +error.play.admission-pointer-unavailable=Le pointeur d’admission au jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=Les droits de jeu sont temporairement indisponibles. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. error.look.room-not-found=Salle introuvable. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 4c00ec76cb..bc6c04ede6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -260,6 +261,148 @@ void playPromotesSessionIntoGameplay() { Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); } + @Test + void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult ambiguousDefaultResult = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(ambiguousDefaultResult.commandResult().accepted()).isFalse(); + assertThat(ambiguousDefaultResult.commandResult().errorCode()) + .isEqualTo("PLAY_SELECTION_REQUIRED"); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + + @Test + void playFailsClosedWhenTenantHasNoPublicProductionRealm() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_CODE); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_MESSAGE); + ErrorOutput errorOutput = (ErrorOutput) result.outputs().getFirst().payload(); + assertThat(errorOutput.messageKey()).isEqualTo("error.play.admission-pointer-unavailable"); + + TextPlayerOutputRenderer englishRenderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + assertThat(englishRenderer.render(result.outputs().getFirst())) + .isEqualTo( + "ERROR ADMISSION_POINTER_UNAVAILABLE Gameplay admission pointer is temporarily unavailable. Retry PLAY shortly."); + + TextPlayerOutputRenderer frenchRenderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "fr", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + assertThat(frenchRenderer.render(result.outputs().getFirst())) + .isEqualTo( + "ERROR ADMISSION_POINTER_UNAVAILABLE Le pointeur d’admission au jeu est temporairement indisponible. Réessayez PLAY sous peu."); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + + @Test + void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm() { + gameplayCatalogProperties.setWorlds(new ArrayList<>(gameplayCatalogProperties.getWorlds())); + gameplayCatalogProperties + .getWorlds() + .add( + world( + "maintenance", + "Maintenance World", + List.of(realm("maintenance", "Maintenance Realm", 23L, 99L, true, false)))); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + @Test + void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); + gameplayCatalogProperties.setWorlds(new ArrayList<>(gameplayCatalogProperties.getWorlds())); + gameplayCatalogProperties + .getWorlds() + .add( + world( + "other-public", + "Other Public World", + List.of(realm("production", "Live Realm", 23L, 99L, true, false)))); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = @@ -914,6 +1057,64 @@ void unknownWorldReturnsSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); } + @Test + void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 11L, + 1L, + true, + true, + false, + "UNKNOWN_LEGACY_SCOPE", + "ALLOW_NEW", + 0L, + null, + null))); + GameplayWorldCatalog authorityBackedCatalog = new GameplayWorldCatalog(authorityService); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + authorityBackedCatalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { GameplayAdmissionPointerAuthorityService pointerAuthority = @@ -1759,7 +1960,7 @@ private static GameplayCatalogProperties.World world( GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); world.setSlug(slug); world.setDisplayName(displayName); - world.setRealms(realms); + world.setRealms(new ArrayList<>(realms)); return world; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index a72f9bd3a6..ccfde37969 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -145,11 +145,11 @@ void setUp() { sessionContextService.save(bootstrapShell(1L, 1L)); sessionContextService.save(bootstrapShell(2L, 1L)); gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + List.of(world("demo", 22L, 1L, false, true), world("sandbox", 22L, 2L, true, false))); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L, true))); when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L, false))); when(instanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { @@ -525,7 +525,7 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { assertTrue(firstLook.commandResult().accepted()); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L))); + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L, true))); TextCommandInterpretationResult lookAfterCutover = interpreter.interpret("1", LOOK_PAYLOAD, false); @@ -573,7 +573,11 @@ void staleIdentityMappingFallsBackToFreshSession() { } private static GameplayCatalogProperties.World world( - String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { + String slug, + long tenantId, + long gameInstanceId, + boolean requiresCharacterSelection, + boolean publicProductionRealm) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); world.setSlug(slug); world.setDisplayName(slug); @@ -583,14 +587,19 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); - realm.setPublicProductionRealm("demo".equals(slug)); + realm.setPublicProductionRealm(publicProductionRealm); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; } private static GameplayAdmissionPointerSnapshot pointer( - String worldSlug, String realmSlug, long tenantId, long gameInstanceId, long pointerVersion) { + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean publicProductionRealm) { return new GameplayAdmissionPointerSnapshot( worldSlug, worldSlug, @@ -600,7 +609,7 @@ private static GameplayAdmissionPointerSnapshot pointer( gameInstanceId, pointerVersion, true, - "demo".equals(worldSlug) && "production".equals(realmSlug), + publicProductionRealm, false, "SHARED", "ALLOW_NEW", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 1758e01f5b..1504b7ed76 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -332,9 +332,9 @@ void setUp() { when(commandService.enqueue(anyString(), anyString(), anyBoolean())) .thenReturn(CommandEnqueueResult.success()); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L, true))); when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L, false))); when(gameInstanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { @@ -354,7 +354,7 @@ void setUp() { gameplayPresenceLifecycleService); GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + List.of(world("demo", 22L, 1L, true, false), world("sandbox", 22L, 2L, false, true))); GameplayWorldCatalog worldCatalog = TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); LoginCommandHandler loginHandler = @@ -1038,7 +1038,11 @@ private String renderedResponse( } private static GameplayCatalogProperties.World world( - String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { + String slug, + long tenantId, + long gameInstanceId, + boolean publicProductionRealm, + boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); world.setSlug(slug); world.setDisplayName( @@ -1053,14 +1057,27 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); - realm.setPublicProductionRealm("demo".equals(slug)); + realm.setPublicProductionRealm(publicProductionRealm); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; } private static GameplayAdmissionPointerSnapshot pointer( - String worldSlug, String realmSlug, long tenantId, long gameInstanceId, long pointerVersion) { + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean publicProductionRealm) { + java.util.UUID realmId = + switch (worldSlug) { + case "demo" -> java.util.UUID.fromString("f67fd9ec-c8e0-48d0-b238-d0c0a57fb8d9"); + case "sandbox" -> java.util.UUID.fromString("e4d17ea7-c544-4ec1-a6d7-c756b1dc2c0b"); + default -> + java.util.UUID.nameUUIDFromBytes( + (worldSlug + ":" + realmSlug).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + }; return new GameplayAdmissionPointerSnapshot( worldSlug, worldSlug, @@ -1070,12 +1087,12 @@ private static GameplayAdmissionPointerSnapshot pointer( gameInstanceId, pointerVersion, true, - "demo".equals(worldSlug) && "production".equals(realmSlug), + publicProductionRealm, false, "SHARED", "ALLOW_NEW", 1L, - stableUuid("realm:" + tenantId + ":" + worldSlug + ":" + realmSlug), + realmId, stableUuid("shared-namespace:" + tenantId)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 190e5f07db..a046ccc09a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -39,11 +39,19 @@ void setUp() { @Test void browseViewReturnsStructuredWorldList() { + GameplayCatalogProperties.World demoWorld = world("demo", 22L, 1L, false); + demoWorld.setDisplayName("Demo World"); + GameplayCatalogProperties.World sandboxWorld = world("sandbox", 23L, 2L, true); + sandboxWorld.setDisplayName("Builder Sandbox"); + gameplayCatalogProperties.setWorlds(List.of(demoWorld, sandboxWorld)); + WorldsViewOutput response = handler.browseView(); - assertThat(response.worlds()).hasSize(1); + assertThat(response.worlds()).hasSize(2); assertThat(response.worlds().get(0).slug()).isEqualTo("demo"); assertThat(response.worlds().get(0).displayName()).isEqualTo("Demo World"); + assertThat(response.worlds().get(1).slug()).isEqualTo("sandbox"); + assertThat(response.worlds().get(1).displayName()).isEqualTo("Builder Sandbox"); } @Test @@ -81,13 +89,7 @@ void browseRealmsToleratesNullRealmEnums() { @Test void browseCharactersReturnsStructuredCharacterList() { gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .getFirst() - .setPublicProductionRealm(false); + List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -96,8 +98,11 @@ void browseCharactersReturnsStructuredCharacterList() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") .setName("Emberline") .setLevel(12) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); @@ -116,6 +121,8 @@ void browseCharactersReturnsStructuredCharacterList() { assertThat(output.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); assertThat(output.characters()).hasSize(1); assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -142,8 +149,11 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8001") + .setTenantId("22") + .setAccountId("123") .setName("Forkline") .setLevel(5) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .build()) .build()); @@ -161,6 +171,9 @@ void browseCharactersUsesIsolatedStateRealmRoster() { assertThat(output.characters()) .extracting(CharacterBrowseViewOutput.CharacterEntry::characterName) .containsExactly("Forkline"); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index f8dfef9b80..e37e07fc6d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -101,8 +101,11 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") .setName("Emberline") .setLevel(12) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); SessionContext context = @@ -122,6 +125,8 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .singleElement() .extracting(output -> output.payload()) .isInstanceOf(CharacterBrowseViewOutput.class); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 2eb238c017..88707e8363 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -514,7 +514,9 @@ private static RoleMaterials of(CertificateMaterialService.RoleMaterial... mater HostedIdentityContract.TELNET_ROLE, HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, - HostedIdentityContract.GRPC_ROLE -> { + HostedIdentityContract.GRPC_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> { if (materialsByRole.putIfAbsent(role, material) != null) { throw new IllegalArgumentException("duplicate identity material role: " + role); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 928418f154..a6f731da0c 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.loggingadmin.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -26,6 +27,9 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Moderation actions are unavailable until the shared mutation gate is implemented"; private static final String FEATURE_FLAG_TOGGLE_UNAVAILABLE_MESSAGE = "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; + private static final String ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE = + "Account audit receipt receiver is unavailable until the immutable receipt contract is " + + "implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); @@ -175,18 +179,12 @@ public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { try { AdminRoleGuard.requireAdminRole(); - var dto = - logEventService.createLogEvent( - new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.parseOptionalPositiveLong( - request.getAccountId(), "accountId"), - request.getType(), - request.getMessage())); - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder().setLogEventId(String.valueOf(dto.id())).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + GrpcAppErrors.error( + meterRegistry, + logger, + "CreateLogEvent", + "UNAVAILABLE", + ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE); } catch (AdminAuthorizationException ex) { CreateLogEventResponse response = CreateLogEventResponse.newBuilder() @@ -200,15 +198,7 @@ public void createLogEvent( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "CreateLogEvent", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + return; } catch (Exception ex) { CreateLogEventResponse response = CreateLogEventResponse.newBuilder() @@ -216,7 +206,12 @@ public void createLogEvent( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + return; } + responseObserver.onError( + Status.UNAVAILABLE + .withDescription(ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE) + .asRuntimeException()); } @Override diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 8a3df2b5fd..5bd6364051 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -3,20 +3,20 @@ 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.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.grpc.Status; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; @@ -73,34 +73,73 @@ public void onCompleted() {} } @Test - void createLogEventUsesLogEventServiceWithoutCallingModeration() { + void createLogEventReturnsUnavailableWithoutDispatchingUntilReceiptReceiverExists() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); LogEventService logEventService = Mockito.mock(LogEventService.class); ModerationService moderationService = Mockito.mock(ModerationService.class); - when(logEventService.createLogEvent(any())) - .thenReturn( - new LogEventDto( - 77L, - 1L, - 42L, - "ACCOUNT_CREATED", - "account created", - Instant.parse("2026-01-01T00:00:00Z"))); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); LoggingAdminGrpcService service = new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - moderationService, - new SimpleMeterRegistry()); + Mockito.mock(LogQueryService.class), logEventService, moderationService, meterRegistry); + + AtomicReference error = new AtomicReference<>(); + java.util.concurrent.atomic.AtomicBoolean receivedResponse = + new java.util.concurrent.atomic.AtomicBoolean(); + java.util.concurrent.atomic.AtomicBoolean completed = + new java.util.concurrent.atomic.AtomicBoolean(); + service.createLogEvent( + CreateLogEventRequest.newBuilder().setTenantId("1").build(), + new StreamObserver<>() { + @Override + public void onNext(CreateLogEventResponse value) { + receivedResponse.set(true); + } + + @Override + public void onError(Throwable t) { + error.set(t); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + + assertNotNull(error.get()); + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + String description = Status.fromThrowable(error.get()).getDescription(); + assertEquals( + "Account audit receipt receiver is unavailable until the immutable receipt contract is " + + "implemented", + description); + assertTrue(description.length() <= 128); + assertFalse(receivedResponse.get()); + assertFalse(completed.get()); + assertEquals(1.0, meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE").count()); + verifyNoInteractions(logEventService, moderationService); + } + + @Test + void createLogEventMapsUnexpectedFailureToSanitizedInternalAndCompletes() { + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + LogEventService logEventService = Mockito.mock(LogEventService.class); + ModerationService moderationService = Mockito.mock(ModerationService.class); + MeterRegistry meterRegistry = Mockito.mock(MeterRegistry.class); + Counter internalErrorCounter = Mockito.mock(Counter.class); + when(meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE")) + .thenThrow(new IllegalStateException("sensitive meter-registry diagnostic")); + when(meterRegistry.counter("grpc.app_error", "code", "INTERNAL")) + .thenReturn(internalErrorCounter); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), logEventService, moderationService, meterRegistry); AtomicReference ref = new AtomicReference<>(); + java.util.concurrent.atomic.AtomicBoolean completed = + new java.util.concurrent.atomic.AtomicBoolean(); service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("42") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), + CreateLogEventRequest.newBuilder().setTenantId("1").build(), new StreamObserver<>() { @Override public void onNext(CreateLogEventResponse value) { @@ -111,13 +150,17 @@ public void onNext(CreateLogEventResponse value) { public void onError(Throwable t) {} @Override - public void onCompleted() {} + public void onCompleted() { + completed.set(true); + } }); assertNotNull(ref.get()); - assertEquals("77", ref.get().getLogEventId()); - verify(logEventService).createLogEvent(any()); - verify(moderationService, never()).applyAction(any()); + assertEquals("INTERNAL", ref.get().getError().getCode()); + assertEquals("Internal error", ref.get().getError().getMessage()); + assertFalse(ref.get().getError().getMessage().contains("sensitive")); + assertTrue(completed.get()); + verifyNoInteractions(logEventService, moderationService); } @Test @@ -259,8 +302,8 @@ public void onCompleted() {} } @Test - void createLogEventRejectsZeroAccountIdBeforeDispatch() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void createLogEventRejectsUnauthorizedCallerBeforeUnavailableResponse() { + SessionContext.setContext("1", List.of("player"), Map.of()); LogEventService logEventService = Mockito.mock(LogEventService.class); LoggingAdminGrpcService service = new LoggingAdminGrpcService( @@ -271,12 +314,7 @@ void createLogEventRejectsZeroAccountIdBeforeDispatch() { AtomicReference ref = new AtomicReference<>(); service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("0") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), + CreateLogEventRequest.newBuilder().setTenantId("1").build(), new StreamObserver<>() { @Override public void onNext(CreateLogEventResponse value) { @@ -291,8 +329,8 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + assertEquals("Admin role required", ref.get().getError().getMessage()); verifyNoInteractions(logEventService); } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java index 7e7d7b7ecd..548f5c56d8 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java @@ -1,8 +1,11 @@ package net.firedevops.firemud.springcloudgateway.filter; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import org.springframework.core.Ordered; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.server.PathContainer; import org.springframework.stereotype.Component; @@ -24,11 +27,13 @@ public class PublicInternalRouteBlockFilter implements WebFilter, Ordered { private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); private static final PathPattern UNAVAILABLE_EXTERNAL_ACCOUNT_ROUTE = PATH_PATTERN_PARSER.parse("/api/account/accounts/{accountId}/external"); + private static final PathPattern UNAVAILABLE_PUBLIC_JOIN_ROUTE = + PATH_PATTERN_PARSER.parse("/api/account/auth/bootstrap/join"); @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { PathContainer pathWithinApplication = exchange.getRequest().getPath().pathWithinApplication(); - if (!targetsBlockedPath(pathWithinApplication)) { + if (!targetsBlockedPath(exchange.getRequest().getMethod(), pathWithinApplication)) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); @@ -40,9 +45,60 @@ public int getOrder() { return -2; } - private boolean targetsBlockedPath(PathContainer pathWithinApplication) { + private boolean targetsBlockedPath(HttpMethod method, PathContainer pathWithinApplication) { return targetsBlockedInternalPath(pathWithinApplication) - || targetsUnavailableExternalAccountPath(pathWithinApplication); + || targetsUnavailableExternalAccountPath(pathWithinApplication) + || targetsUnavailablePublicJoinRoute(method, pathWithinApplication.value()); + } + + private boolean targetsUnavailablePublicJoinRoute(HttpMethod method, String path) { + if (!HttpMethod.POST.equals(method)) { + return false; + } + String canonicalPath = canonicalizePublicRoutePath(path); + return UNAVAILABLE_PUBLIC_JOIN_ROUTE.matches(PathContainer.parsePath(canonicalPath)); + } + + private String canonicalizePublicRoutePath(String path) { + String decodedPath = decodePath(path); + StringBuilder canonicalPath = new StringBuilder(decodedPath.length()); + String[] rawSegments = decodedPath.replace('\\', '/').split("/", -1); + for (String rawSegment : rawSegments) { + String segment = rawSegment; + int matrixParameterStart = segment.indexOf(';'); + if (matrixParameterStart >= 0) { + segment = segment.substring(0, matrixParameterStart); + } + if (segment.isEmpty() || ".".equals(segment)) { + continue; + } + if ("..".equals(segment)) { + int previousSeparator = canonicalPath.lastIndexOf("/"); + if (previousSeparator >= 0) { + canonicalPath.setLength(previousSeparator); + } + continue; + } + canonicalPath.append('/').append(segment); + } + return canonicalPath.length() == 0 ? "/" : canonicalPath.toString(); + } + + private String decodePath(String path) { + String decodedPath = path; + for (int pass = 0; pass < 8; pass++) { + try { + String nextPath = + URLDecoder.decode(decodedPath.replace("+", "%2B"), StandardCharsets.UTF_8); + if (nextPath.equals(decodedPath)) { + return decodedPath; + } + decodedPath = nextPath; + } catch (IllegalArgumentException exception) { + return decodedPath; + } + } + return decodedPath; } private boolean targetsBlockedInternalPath(PathContainer path) { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 40274fc623..b72f5f4787 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -338,6 +338,37 @@ void allowsNormalPublicApiRoute() { assertThat(exchange.getResponse().getStatusCode()).isNull(); } + @Test + void blocksPublicBootstrapJoinRoute() { + assertBlockedPost("/api/account/auth/bootstrap/join"); + } + + @Test + void blocksPublicBootstrapJoinRouteAfterPathCanonicalization() { + assertBlockedPost("/api/account//auth/bootstrap/join/"); + assertBlockedPost("/api/account/auth/bootstrap/join;probe=true"); + assertBlockedPost("/api/account/auth/bootstrap/../bootstrap/join"); + assertBlockedPost("/api%252Faccount/auth/bootstrap/join"); + assertBlockedPost("/api/account/auth/bootstrap/%256Aoin"); + } + + @Test + void blocksBootstrapJoinWhenMalformedSuffixFollowsSuccessfullyDecodedSegment() { + assertBlockedPost("/api/account/auth/bootstrap/%6Aoin;x=%25ZZ"); + } + + @Test + void handlesMalformedPercentEncodingRemainingAfterMaximumDecodePasses() { + assertAllowed(HttpMethod.POST, "/api/account/auth/bootstrap/%2525252525252525"); + } + + @Test + void allowsOtherAccountAuthRoutesAndNonPostJoinPath() { + assertAllowed(HttpMethod.POST, "/api/account/auth/player-bootstrap"); + assertAllowed(HttpMethod.POST, "/api/account/auth/connect-token"); + assertAllowed(HttpMethod.GET, "/api/account/auth/bootstrap/join"); + } + @Test void allowsSiblingPathsOfBlockedServiceLocalRoots() { assertAllowedPath("/api/account/internalized/runtime"); @@ -363,6 +394,17 @@ private WebFilterChain chain(AtomicBoolean chainCalled) { }; } + private void assertBlockedPost(String path) { + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).as(path).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isEqualTo(HttpStatus.NOT_FOUND); + } + private void assertBlockedPath(String path) { MockServerWebExchange exchange = MockServerWebExchange.from( @@ -371,8 +413,19 @@ private void assertBlockedPath(String path) { filter.filter(exchange, chain(chainCalled)).block(); - assertThat(chainCalled).isFalse(); - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(chainCalled).as(path).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isEqualTo(HttpStatus.NOT_FOUND); + } + + private void assertAllowed(HttpMethod method, String path) { + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.method(method, path).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).as(path).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isNull(); } private void assertAllowedPath(String path) { @@ -383,7 +436,7 @@ private void assertAllowedPath(String path) { filter.filter(exchange, chain(chainCalled)).block(); - assertThat(chainCalled).isTrue(); - assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(chainCalled).as(path).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isNull(); } }