diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 0ed9f04aec..9a9d5340fd 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1498,6 +1498,7 @@ jobs: id: runtime-smoke if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held SMOKE_MINIO_SERVER_IMAGE_ID: >- ${{ steps.minio-source.outputs.server_image_id }} SMOKE_MINIO_CLIENT_IMAGE_ID: >- diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e6d02914ee..5ccd4d0e7a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -600,7 +600,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "8b49b5e26ac37a1b6c1d098ee0d8c9716d850eb0ea7e43491b6c6b6f191fca1a"; + const canonicalRuntimeWorkflowSha256 = "08dcfb278c69913ed3732d15c88ceb7eef047a04f729e625891afa4038e4a9d4"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = `${owner}/${repo}`; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 721a7a8f27..2df0e5baee 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -72,7 +72,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `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; its Account component exposes the persisted UUID, while profile fields retain their current identifiers. This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/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 returns the persisted Account UUID in `AccountDto.id` / `CreateAccountResponse.account_id` and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. 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 login/auth/bootstrap results and tenant/profile/member DTOs still use numeric account and tenant identities; only registration and the Account components of the existing Account-local exports now use Account UUID. 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; its Account component exposes the persisted UUID, while profile fields retain their current identifiers. This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/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 returns the persisted Account UUID in `AccountDto.id` / `CreateAccountResponse.account_id` and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current login/auth/bootstrap results and tenant/profile/member DTOs still use numeric account and tenant identities; only registration and the Account components of the existing Account-local exports now use Account UUID. 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 @@ -239,7 +239,7 @@ The current Account source also prepares `AcquireStartSessionWorldParticipation` | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/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:** after bootstrap and connect-scope authentication, the endpoint returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation while the canonical producer is unavailable. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | | `POST` | `/auth/bootstrap/join` | **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 | @@ -251,7 +251,7 @@ Current verification routing/auth status: `POST /auth/verify-email` inherits bea Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. -The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. **Current implementation drift:** `ConnectTokenResponse` currently includes `jti` in the body, despite this target metadata-only contract. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. An exact retry with the same `(accountId, connectScopeId, requestId)` and digest replays the stored result; after the response envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. No gRPC `IssueConnectToken` transport exists. +The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. **Current endpoint behavior:** after validating bootstrap identity and connect-scope binding, Account returns `AUTH_UNAVAILABLE` before cached-success replay or fresh membership, entitlement, and runtime authority reads, token minting, or replay/session mutation. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; no gRPC `IssueConnectToken` transport exists. For the bootstrap-character and connect-token REST routes, authenticated gameplay-admission denials (`CONNECT_TOKEN_REJECTED`, `NON_PUBLIC_ENROLLMENT_REQUIRED`, `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `JOIN_REQUIRED`, and `TENANT_BILLING_BLOCKED`) map to HTTP 403; invalid bootstrap credentials remain 401 and unavailable authority remains 503. @@ -283,7 +283,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, 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. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` validates bootstrap identity and scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, or cached-result reads and token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | 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/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 657bd6435c..0302c286fa 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -54,7 +54,7 @@ The current public registration path creates only a global Account row and a pla Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current 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 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. Character discovery requires membership after applicable target and entitlement checks; on an eligible public-production target missing or `INACTIVE` membership returns non-actionable `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, while other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current `POST /auth/connect-token` validates bootstrap identity and the retained connect scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-result, or token-issuance work; it does not currently return an issuance `JOIN_REQUIRED` or `CONNECT_TOKEN_REJECTED` result. 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. @@ -83,7 +83,7 @@ The unregistered canonical gameplay LOGIN primary-credential adapter reuses Acco - 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). - Internal service-to-service **gRPC** calls use mutual TLS; Gateway-to-backend HTTP/WebSocket hops remain explicit, controlled in-cluster non-mTLS exceptions governed by the shared [Security Architecture](../../system-architecture-security.md#cross-service-trust). -- 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. +- 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 clients use the short-lived `player-bootstrap` profile for HTTPS bootstrap. The target WebSocket flow uses a separate one-use connect token, but current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before exposing one. 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 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). @@ -140,9 +140,9 @@ For `security_locked`, the canonical account export route set uses only the dist - `session:auth:account::` – current legacy Account account-session projection; Account owns its revocation and repair while it converges to the target token record. - `session:auth:tenant::` – current legacy Account tenant-session projection; it is a separate tenant-scoped projection and must not be removed independently of the account projection during a tenant reset. - `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, and `session:auth:generation:membership::` – Account-owned generation projections for issuer, account, tenant, and membership authority; Account durable generations remain authoritative. - - `session:connect-token:tenant::account::scope::request:` – the **current legacy** exact-input result-map family. Its bounded map contains the raw issued token or deterministic cached failure; it remains a distinct legacy representation and is never read by the target path. + - `session:connect-token:tenant::account::scope::request:` – a retained legacy exact-input result-map family. Current `AccountServiceImpl.issueConnectToken` stops before reading or writing it, so it is not a current issuance or replay path. - `session:connect-token:v1:tenant::account::scope::request:` – the **target** exact-input issuance-result projection. Here `scopeHash` is the fixed-length lowercase hexadecimal SHA-256 of the canonical UTF-8 `connectScopeId`, and `requestHash` is the fixed-length lowercase hexadecimal SHA-256 of the canonical UTF-8 `requestId`; these components use the same encoding as the explicit legacy `sha256(...)` components and are not the versioned request digest. Its value must carry the explicit discriminator `schemaVersion: "connect-token-issuance-result-v1"` and the Account-encrypted exact response envelope. The target reader reads only this versioned family and requires that discriminator; target writers never read, write, or promote the unversioned legacy map. Account first claims the durable `connect_token_issuance_operation` with first-writer-wins SQL/CAS before minting; only the winner mints, matching losers read the winning operation/result. Redis installation is set-if-absent followed by read-winner, never overwrite. Missing or malformed target projections are repaired only from the exact durable operation/envelope, or fail closed; no JWT/request-field reconstruction or remint is allowed. Changed input remains `IDEMPOTENCY_CONFLICT`. - - These records live on Coordination Redis so auth sessions share the same AOF and reset semantics as gameplay sessions. The [canonical Redis reset-policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) owns the detailed reset procedure; these Account-local consequences are distinct: region- and tenant-scoped resets preserve the token and both legacy auth projections, while a cluster reset may discard them only through Account-owned cutover and durable repair; missing token records deny protected use rather than being reconstructed from a JWT. Generation projections are re-projected and verified from Account durable authority for affected scopes, and unavailable or contradictory repair keeps the scope fenced. The exact-input connect-token issuance-result family is preserved by region/tenant resets; a cluster reset may discard it only after Account durable/fenced recovery or expiry of the request identity. **Current implementation gap:** `AccountServiceImpl.issueConnectToken` reads the legacy map through `SessionServiceImpl.getConnectTokenReplay`; on a miss it falls through `issueConnectTokenFresh`, then `SessionServiceImpl.storeConnectTokenReplay` unconditionally overwrites that map. Legacy Redis loss or rewind is therefore unsafe and unrecoverable by the current runtime; affected handshakes must remain fenced and operators must escalate rather than treating this path as current fail-closed conformance. The target contract remains exact-result recovery: Account must exact-match the durable `connect_token_issuance_operation` and encrypted response envelope/readback before trusting or re-projecting a result; a missing or mismatched operation, envelope, or readback is untrusted and remains fenced, never reconstructed as a JWT or silently reminted. + - These records live on Coordination Redis so auth sessions share the same AOF and reset semantics as gameplay sessions. The [canonical Redis reset-policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) owns the detailed reset procedure; these Account-local consequences are distinct: region- and tenant-scoped resets preserve the token and both legacy auth projections, while a cluster reset may discard them only through Account-owned cutover and durable repair; missing token records deny protected use rather than being reconstructed from a JWT. Generation projections are re-projected and verified from Account durable authority for affected scopes, and unavailable or contradictory repair keeps the scope fenced. The exact-input connect-token issuance-result family is preserved by region/tenant resets; a cluster reset may discard it only after Account durable/fenced recovery or expiry of the request identity. **Current behavior:** `AccountServiceImpl.issueConnectToken` validates the bootstrap identity and connect scope, then returns `AUTH_UNAVAILABLE` before cached-result reads, token minting, or session/replay mutation. The legacy map and its helpers are not reached by the current endpoint, and no successful connect-token response or replay is claimed. The target contract remains exact-result recovery: Account must exact-match the durable `connect_token_issuance_operation` and encrypted response envelope/readback before trusting or re-projecting a result; a missing or mismatched operation, envelope, or readback is untrusted and remains fenced, never reconstructed as a JWT or silently reminted. - **Cache/Rate-Limit Redis** - The Account Service does not maintain its own Cache/Rate-Limit Redis prefixes today; any future caches for account or profile lookups must use Cache/Rate-Limit Redis and the key naming/TTL/versioning rules in [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md), not Coordination Redis. - Account does not currently claim a Cache/Rate-Limit Redis bucket or cache as an authorization, financial, durable-quota, or security-lock authority. Any future abuse signal remains a bounded heuristic unless an authoritative owner contract is added. @@ -177,7 +177,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. 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 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. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current connect-token issuance validates bootstrap identity and scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, target-authority, or cached-result processing. 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. @@ -233,8 +233,8 @@ Runtime caller contract: - For a selected target confirmed as public production, fresh Account entitlement (`allowPublicJoin`) and fresh selected-target catalog/pointer/public-production evidence are separate required gates. `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when that selected public-production joining policy denies entry. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; and failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. `JOIN_REQUIRED` is returned only when both gates pass but the fresh membership snapshot is missing or `INACTIVE`. - Target issuance also requires the shared replay-readiness record to be `OPEN` and binds its exact `replayAdmissionFence` into the signed token. Missing, unreadable, quarantined, or changing readiness fails closed before the token is exposed. - Minimum request fields: `connectScopeId`, `requestId`. - - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Current implementation drift:** `ConnectTokenResponse` currently exposes `jti` in the HTTP response body, and the current `ConnectTokenResult`/`AccountServiceImpl` issuance path does not carry or return `playtestLifecycleId` or `playtestStateGeneration`; the live body is therefore not conformant to the target metadata-only/no-internal-jti target or the required non-public-target identity metadata. - - 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. + - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Dormant DTO/source-shape drift:** `ConnectTokenResponse` declares `jti`, and `ConnectTokenResult`/`AccountServiceImpl` do not carry `playtestLifecycleId` or `playtestStateGeneration` required for target non-public response metadata. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before constructing this response, so these fields are not a live HTTP response or token disclosure. + - Target success delivery uses only `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is not returned in the response body or a response-header fallback. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before creating a token or cookie, so no current first-party WebSocket admission is established. Under the target flow, browser/mobile clients and first-party non-browser clients with a protected cookie jar remain cookie-only. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. - 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. @@ -242,7 +242,7 @@ Runtime caller contract: - 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. + - **Target contract; current Account behavior is fail-closed.** The target requires caller-bound membership for every selected target. For a 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. **Current runtime:** `AccountServiceImpl.issueConnectToken` validates the bootstrap identity and connect scope, then returns `AUTH_UNAVAILABLE` before membership checks, replay reads or writes, token minting, or session mutation. A private or playtest target additionally requires the current Account-owned realm-access grant under the target contract; a grant never substitutes for membership or public onboarding. The canonical contracts remain in [Authentication](../../system-architecture-authentication.md) and [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). - 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. @@ -308,7 +308,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit - Account's owner-local JOIN v2 model adds a closed canonical scope, stable intent digest, and policy-bound request digest to the existing persistence foundation. It does not change the current JoinPublicProductionMembership RPC or confer target authority by digest alone. Account login/public JOIN wiring, Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current 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. +- 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 validates bootstrap identity and connect-scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-success, or token-minting work. Character discovery checks local membership existence/admission after fresh entitlement and target checks. On an eligible public-production target, missing or `INACTIVE` membership returns `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. 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 and direct text-client end-to-end proof remain incomplete. The membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` maps either membership 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). diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 17d122402d..e597bd1f91 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. + - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). diff --git a/design/architecture/microservices/spring-cloud-gateway/README.md b/design/architecture/microservices/spring-cloud-gateway/README.md index 3f30eba183..d5ba567b4f 100644 --- a/design/architecture/microservices/spring-cloud-gateway/README.md +++ b/design/architecture/microservices/spring-cloud-gateway/README.md @@ -32,8 +32,9 @@ An OpenAPI specification for these REST endpoints lives in `services/spring-clou - `readiness` is route-admission safety. For the currently implemented gameplay slice, the gateway is ready only when: - baseline route configuration is loaded; and - the `/ws/game/**` gameplay path can pass the same admission filters, upgrade, and forward to Game Session successfully enough for new gameplay sockets to be admitted. -- Public Gateway readiness remains scoped to public/gameplay route safety. The dedicated TCP Proxy TLS listener has route-specific admission and is proved separately by reaching readiness through that listener; its `tcpProxyTlsListenerReadiness` indicator reports the listener state without making the public readiness group depend on it. Invalid listener, environment, trust-profile, expiry, or TLS-material configuration still fails startup before either listener can serve traffic. -- The gameplay-route canary is bounded and operation-shaped. It validates the actual `/ws/game/**` upgrade path with an explicit short timeout rather than relying on unrelated ping-style checks or long retry budgets. In player-facing environments, connect-token replay protection is part of admission safety; if the replay-protection store is unavailable and the route would fail closed with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, the gameplay route is not ready. +- **Target:** Public Gateway readiness is scoped to public/gameplay route safety. The dedicated TCP Proxy TLS listener has its own route-admission boundary; its `tcpProxyTlsListenerReadiness` indicator is not part of the public readiness group. [ADR 0157](../../decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md) calls for a route-specific gate or distinct Kubernetes Service when one bounded route has stricter admission requirements, so unrelated safe traffic remains admitted. +- **Current deployment qualification:** `gameplayRouteReadiness` is included in the shared `/actuator/health/readiness` group and remains `OUT_OF_SERVICE` while first-party admission prerequisites are unqualified. The repository's Kubernetes base and hosted Helm example use that endpoint as the Gateway pod readiness probe. The public Gateway and internal TCP Proxy mTLS Services select the same pods, so this is an explicit combined-workload hold: both Services withdraw those pods while first-party gameplay admission is held, including the trusted TCP Proxy bridge Service. The separate `tcpProxyTlsListenerReadiness` component reports listener state but does not provide an independent pod or Service readiness boundary; `/actuator/health/readiness` through the TLS listener uses the same health group. Independent route-level readiness and admission remain a pre-rollout gap. Invalid listener, environment, trust-profile, expiry, or TLS-material configuration still fails startup before either listener can serve traffic. +- The target gameplay-route canary is bounded and operation-shaped. It validates the actual `/ws/game/**` upgrade path with an explicit short timeout rather than relying on unrelated ping-style checks or long retry budgets. In player-facing environments, connect-token replay protection is part of admission safety; if the replay-protection store is unavailable and the route would fail closed with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, the gameplay route is not ready. **Current first-party status:** a presented public cookie receives `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, and the gameplay-route readiness indicator reports `OUT_OF_SERVICE` while canonical Account production, shared replay fencing, and dedicated Gateway signing keys remain unqualified. The trusted TCP Proxy handshake retains its distinct listener trust checks, but the current combined pod readiness hold does not claim separate Service admission for that path. - Retry filters are resilience mechanisms, not readiness compensation. A gateway that still needs startup retries to survive ordinary new gameplay admission is not ready. - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency name `gameplayRoute`. @@ -47,7 +48,7 @@ This document describes the behaviour of Spring Cloud Gateway in its target arch | Dynamic route management | REST and gRPC route mutation APIs are dev/test-only overrides on top of the released route catalog. Player-facing environments reject dynamic mutation configuration at startup; production operators have diagnostics only, and route changes use the separately accepted declarative deployment workflow. Any future production runtime route-control plane requires a new architecture decision and must remain consistent with the [canonical authorization route matrix](../../system-architecture-authz-route-matrix.md). | Not converged: mutation components are currently unconditional and lack the required profile isolation, startup rejection, protected-route validation, and destination/predicate/filter allowlists. | | Rate limiting and Redis wiring | Gateway rate limiting uses Spring Cloud Gateway `RequestRateLimiter` backed by the Cache/Rate-Limit Redis role, with gameplay abuse policy split across Gateway, TCP Proxy, and Game Session. | Implemented. | | TCP Proxy bridge admission | Traffic from the TCP Proxy Service always targets `/ws/game/**`; player-facing bridge authority requires the exclusive environment-bound mTLS identity contract in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). | Gateway runtime now provides a separately bound TLS listener, requires CA-validated client certificates for certificate-bound profiles, enforces exact URI SAN, expiring DNS migration, expiring leaf fingerprint, or development-only TLS/CIDR selection exclusively, and promotes bridge headers only after the selected trust check. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with its dedicated Service, separate Gateway-server/TCP-Proxy-client Secret mounts and environment, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned identity issuance/projection, live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. TLS material is loaded at listener startup; live renewal reload is not implemented. | -| WebSocket close and handshake observability | Target-only typed Game Session → Gateway lifecycle intent feeds Gateway’s sole external WebSocket close-translation owner: `logout`, `session_replaced`, `service_restart`, `idle_timeout`, `policy_violation`, `internal_error`, and `backend_unavailable` are bounded top-level classes; bridge closes also carry `bridge_shutdown_class=planned_drain\|valid_upstream_close\|unattributed_failure` and optional diagnostic subreason. | Partially implemented at the current bridge and first-party handshake boundary. The typed lifecycle-intent contract is not implemented or versioned; unknown or absent intent must fail closed as `internal_error` at the public WebSocket boundary. `session_replaced`/`service_restart` convergence, neutral valid-upstream attribution, ADR 0013's elapsed-time cutoff, bounded input stall/rebind path, and terminal-versus-rebindable upstream classification remain gaps. See [Gateway Architecture](../../system-architecture-gateway.md#canonical-close-translation-matrix). | +| WebSocket close and handshake observability | Target-only typed Game Session → Gateway lifecycle intent feeds Gateway’s sole external WebSocket close-translation owner: `logout`, `session_replaced`, `service_restart`, `idle_timeout`, `policy_violation`, `internal_error`, and `backend_unavailable` are bounded top-level classes; bridge closes also carry `bridge_shutdown_class=planned_drain\|valid_upstream_close\|unattributed_failure` and optional diagnostic subreason. | The trusted TCP Proxy bridge is implemented locally, and the public first-party filter is fail-closed; it does not validate a connect token or admit a cookie handshake. The typed lifecycle-intent contract is not implemented or versioned; unknown or absent intent must fail closed as `internal_error` at the public WebSocket boundary. `session_replaced`/`service_restart` convergence, neutral valid-upstream attribution, ADR 0013's elapsed-time cutoff, bounded input stall/rebind path, and terminal-versus-rebindable upstream classification remain gaps. See [Gateway Architecture](../../system-architecture-gateway.md#canonical-close-translation-matrix). | ## Documentation Map diff --git a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md index be9c9b0eac..18fd6c25bd 100644 --- a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md +++ b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md @@ -13,7 +13,7 @@ - Traffic from the TCP Proxy Service always targets `/ws/game/**` via `GATEWAY_WS_URL`. - In player-facing environments, the TCP Proxy -> Gateway WebSocket hop is mTLS-authenticated under the mutually exclusive environment-bound trust profiles in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md); the local endpoint and certificate variables remain in [TCP Proxy configuration](../tcp-proxy-service/configuration.md#websocket-mtls-to-spring-cloud-gateway). - Spring Cloud Gateway strips or overwrites spoofable tenant, game-instance, and routing headers from public ingress. It forwards `X-Tenant-Id` / `X-Game-Instance-Id` only when derived from trusted inputs, and accepts `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` from TCP Proxy only as an all-or-none bundle on the authenticated bridge; a partial or malformed bundle is rejected before the validated advisory context reaches Game Session. -- Gateway emits the positive `X-Firemud-Connection-Mode` discriminator on successful gameplay admission: `first_party_web` for the supported protected-cookie connect-token path and `trusted_tcp_proxy` for authenticated TCP Proxy bridges. A future target-only public non-browser header variant requires its own route classification and proof. The canonical marker and downstream trust rules are owned by [Gateway architecture](../../system-architecture-gateway.md#gateway-output-rules-downstream-trusted); Game Session must not infer path type from header absence. +- On successful target first-party admission, Gateway emits `X-Firemud-Connection-Mode: first_party_web`; authenticated TCP Proxy bridges use `trusted_tcp_proxy`. Current public first-party cookie handshakes are denied with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, so only the trusted TCP Proxy path currently emits a positive gameplay mode. A future target-only public non-browser header variant requires its own route classification and proof. The canonical marker and downstream trust rules are owned by [Gateway architecture](../../system-architecture-gateway.md#gateway-output-rules-downstream-trusted); Game Session must not infer path type from header absence. ## WebSocket Close and Handshake Classification @@ -36,7 +36,7 @@ Unless explicitly described as current behavior, the sections below define the t - Java `CanonicalGatewayRoutesConfiguration` is the current route authority, with environment overrides; the target route catalog and deny-by-default exposure rules still require convergence proof. It currently has no `/assets/**` route or asset-store route ID; published asset delivery remains target-only pending a separate approved public origin/provisioner, and private MinIO is not public delivery. - **Current Game Design route consequence:** the current coarse `/api/design/**` route forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. That controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate, so official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. -- The current edge implements bounded connect-token handshake classes and replay handling, but this does not prove the complete target replay durability, rotation, or reconnect contract. +- **Current first-party status:** the public filter returns `CONNECT_TOKEN_MISSING` when the cookie is absent and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when it is presented; it performs no connect-token validation or replay-marker operation. The gameplay-route readiness indicator reports `OUT_OF_SERVICE` until canonical Account production, shared replay fencing, and dedicated Gateway signing keys are qualified. This is fail-closed receiving behavior, not a successful first-party handshake or complete target replay implementation. - **Current drift:** the protected admin `JwtAuthFilter` parses shared-HMAC JWTs through `JwtUtil`. This is current implementation behavior only, is not a player-facing asymmetric-validation capability, and must not be confused with the target receiving-service boundary. - **Target boundary:** On protected admin routes, Gateway requires an `Authorization` header at ingress and forwards it without parsing or validating ordinary JWT contents; consuming services own asymmetric JWKS validation under [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). - The current public `/api/session/**` inventory is limited to `GET /api/session/ping`; internal `/sessions*` mutations remain non-public. diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 4135413074..96ea81ea4f 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -71,7 +71,7 @@ An explicit certificate-instance revocation, identity removal, or emergency trus ### Coordination Redis -- The target Gateway replay/deny/readiness client uses the Gateway-owned non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` pin, which must equal exactly `gateway-connect-token-replay-v1`; its key/domain representation and reset contract follow the canonical [Redis architecture](../../system-architecture-redis.md), [Redis usage and profiles](../../system-architecture-redis-usage-and-profiles.md), and [Redis reset and recovery](../../system-architecture-redis-reset-and-recovery.md) owner documents and are intentionally not restated here. Target startup and preflight reject any missing, unknown, or mismatched value. The current `GameplayHandshakeFilter` remains migration-only drift: it receives the generic `spring.data.redis` template routed through `FIREMUD_REDIS_CACHE_HOST`, writes only the untagged replay marker `gateway:connect-token:jti:`, and now accepts only the protected `Firemud-Connect-Token` cookie on public gameplay while rejecting the target-only header carrier. This is an implementation exception that must not be treated as an allowed Cache/Rate-Limit use: the filter can authorize a handshake while using this generic Cache-bound replay marker, and it does not currently write a browser-deny marker, readiness record, or replay fence. Current behavior rejects that header carrier as `CONNECT_TOKEN_REJECTED` until the `non_first_party_public` route/profile is registered and its issuance, replay, signed-context, response, and carrier proofs exist; it is not current `first_party_web` support or a fallback carrier. Player-facing admission must remain quarantined until the named Coordination client/ACL and owner-defined replay contract are cut over, the old replay state is inventoried/read back, and old markers are retained or explicitly cleaned only after their original acceptance windows. +- The target Gateway replay/deny/readiness client uses the Gateway-owned non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` pin, which must equal exactly `gateway-connect-token-replay-v1`; its key/domain representation and reset contract follow the canonical [Redis architecture](../../system-architecture-redis.md), [Redis usage and profiles](../../system-architecture-redis-usage-and-profiles.md), and [Redis reset and recovery](../../system-architecture-redis-reset-and-recovery.md) owner documents and are intentionally not restated here. Target startup and preflight reject any missing, unknown, or mismatched value. Current `GameplayHandshakeFilter` has no Redis client and neither reads nor writes replay markers: the dedicated public `X-Firemud-Connect-Token` header is rejected as unsupported, a missing cookie returns `CONNECT_TOKEN_MISSING`, and a presented `Firemud-Connect-Token` cookie returns `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`. The gameplay-route readiness indicator reports `OUT_OF_SERVICE` while canonical Account connect-context production, shared replay fencing, and dedicated Gateway signing keys remain unqualified. The legacy untagged replay-marker family is not a current authorization path and cannot authorize a cookie handshake. ### Cache/Rate-Limit Redis @@ -94,7 +94,7 @@ Any additional gateway-local caches must explicitly declare whether they are str ## Runtime and TLS Invariants - The HTTP server listens on `SERVER_PORT` (typically `8080`), and the gRPC server listens on port `6565` as configured in `application.yml`. -- **Target-state JWT and presence boundary:** Spring Cloud Gateway does not validate or parse ordinary JWTs for routed gameplay or admin traffic, does not require JWT signing material for those routes, and does not own gameplay login, session, or presence state. Downstream services, especially Game Session, remain responsible for those concerns. The explicit target gameplay-connect exception is `/ws/game/**`: `GameplayHandshakeFilter` validates the short-lived `gameplay-connect` JWT and signs the downstream connect context, so player-facing target deployments must provide the Gateway signing material and satisfy the dedicated signature, clock/lifetime, claim/scope, replay-readiness, and atomic consume requirements in [Gateway Architecture](../../system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) and [ADR 0029](../../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). **Current implementation:** `GameplayHandshakeFilter` provides the bounded signature/claim/expiry and one-time marker checks but uses the legacy untagged Cache-bound marker and lacks the target readiness/fence/quarantine proof; this exception does not broaden ordinary routed JWT handling or establish current player-facing readiness. +- **Target-state JWT and presence boundary:** Spring Cloud Gateway does not validate or parse ordinary JWTs for routed gameplay or admin traffic, does not require JWT signing material for those routes, and does not own gameplay login, session, or presence state. Downstream services, especially Game Session, remain responsible for those concerns. The target gameplay-connect exception is `/ws/game/**`: Gateway validates the short-lived connect credential and emits the owner-defined signed downstream context only after the canonical signature, claim, expiry, scope, replay-readiness, and atomic-consume checks. **Current first-party implementation:** `GameplayHandshakeFilter` does not parse a gameplay-connect credential, sign a context, or consult/consume replay state. It rejects a presented cookie with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, and gameplay-route readiness is `OUT_OF_SERVICE` pending canonical Account production, shared replay fencing, and dedicated Gateway signing-key qualification. The separate trusted TCP Proxy admission path remains available under its existing trust profile. - Admin and other meta/control services validate JWTs themselves. The gateway `JwtAuthFilter` only enforces the presence of an `Authorization` header on protected routes and forwards tokens unchanged. - External TLS is terminated by the load balancer. - Spring Cloud Gateway routes to backend services over in-cluster `http://` and `ws://` endpoints, while internal service-to-service traffic uses mTLS gRPC as described in the [Security Architecture](../../system-architecture-security.md). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 0f416a6add..51631b8830 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -23,16 +23,16 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Account's local canonical tenant/source-currentness and JOIN v2 persistence foundations do not change the direct-text REALMS-to-JOIN authority contract or prove that Game Session dispatches text JOIN; that #2898 capability remains incomplete, as does #2848 unknown-outcome recovery. - **Current gameplay authentication and transport boundary:** Current gameplay authentication supports `LOGIN ` / `LOGON ` to request a verified-email login code and `LOGIN ` / `LOGON ` for an immediate password-or-code attempt on raw Telnet and other non-WebSocket text clients. Bare raw-text `LOGIN`/`LOGON` prompt exchange is target-only and currently returns `PROMPT_LOGIN_UNSUPPORTED`. Control-plane clients use `/auth/login`. First-party gameplay uses `POST /auth/player-bootstrap` to establish the `player-bootstrap` identity, then uses `/auth/bootstrap/*` discovery/action routes and `/auth/connect-token` before the gameplay socket. Clients are stateless; current Account-owned legacy authentication session records persist `tokenHash` and session metadata under the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key, while gameplay bindings remain in Redis. These records never persist the raw delegation JWT; their runtime/data ownership is defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#session-and-token-model). Target issued-token registry issuance, storage, and consumer enforcement in Coordination Redis are unimplemented. The Game Session Service restores gameplay session state from Redis, while the Account Service validates the supplied login secret and issues the exact `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT profile required by the destination. Raw Telnet gameplay command streams never carry JWT authorization. Target browser and mobile-browser gameplay uses a `player-bootstrap` JWT for HTTPS bootstrap calls and a cookie-carried one-use connect token for the `/ws/game/**` handshake; target first-party native-mobile clients that use a cookie jar remain cookie-only. Public non-browser issuance and the dedicated handshake-header carrier are target-only and unavailable until a dedicated route is fully registered and its issuance, registry, profile, and carrier proof is complete; the target design uses protected secure storage plus `X-Firemud-Connect-Token`. First-party admin/creator UIs and backend services use their own permitted token profiles. Provider-specific HTTPS sign-in remains unavailable until the provider-specific verification, collision, recovery, and end-to-end proof required by [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md) is complete. -- **Current first-party endpoint and runtime boundary:** The current first-party browser/mobile runtime includes dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces, Gateway rejection for missing, expired, replayed, or scope-mismatched connect tokens, and Game Session validation of the signed connect context before bare `LOGIN`, but these remain partial implementation surfaces rather than proof of the complete target flow. Current `PLAY` resolves the admissible `gameInstanceId` from realm routing and binds the legacy `{tenantId, gameInstanceId, characterId}` identity; that per-instance binding is implementation drift. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. -- **Current realm-identity gap:** Current discovery, admission-pointer mutation/read models, gameplay-connect claims, and the Gateway signed context do not carry and prove durable `realmId` end to end; several runtime surfaces still key or resolve routes directly from `worldSlug`/`realmSlug`. The target resolves those selectors to `{tenantId, realmId}` before pointer lookup and carries `realmId` in the exact selected-target snapshot and signed context. +- **Current first-party endpoint and runtime boundary:** The existing Account connect-token surface and Gateway first-party cookie handshake fail closed while the canonical Account producer, shared replay-readiness fence, and dedicated Gateway key delivery remain unavailable. Game Session locally prepares complete signed-context verification, canonical current-target comparison, and exact retained-context recovery; bare first-party `LOGIN` and `PLAY` deny before legacy authentication or binding effects. These prepared consumers do not qualify issuance, gameplay admission, or a deployed end-to-end flow. Current capability and proof limits are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. +- **Current realm-identity gap:** Canonical owner route reads and the local signed-context receiver carry durable `realmId` with the exact selected-target snapshot. The Account/Gateway producer and full gameplay admission handoff remain unavailable, so this does not establish end-to-end realm authority; legacy numeric-only admission cannot substitute for that boundary. - **Current provider-specific sign-in boundary:** Optional provider-specific HTTPS sign-in is permitted only after complete provider proof; password and verified-email code remain the Account-owned baseline and fallback, and Telnet never carries provider credentials. See [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md). - **Current raw-text challenge semantics:** The current raw-text email-code challenge is two commands: `LOGIN ` (or `LOGON `) requests an Account-owned, server-side verified-email challenge bound to the normalized account/email and its configured expiry without authenticating the session, then `LOGIN ` (or `LOGON `) submits that code. The separate immediate-auth form is `LOGIN ` (or `LOGON `) with one secret. Account selects the `EMAIL_OTP` validator first when the supplied secret matches the live challenge; otherwise it verifies `PASSWORD` when that account mode is enabled. The client does not select the validator, and a code is not valid outside its server-side challenge and expiry. - **Target only/currently unavailable:** The independently enrolled TOTP-backed `privileged_control` elevation window for `platformAdmin` and cross-tenant `billingAdmin` is not implemented; current runtime must not claim those elevated paths are available. - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. -- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; 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`. +- Current connect-token issuance returns `AUTH_UNAVAILABLE` before membership or replay-cache reads while its canonical producer is unavailable. Supported text `PLAY` does not consult the connect-token replay cache and performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. Current text `PLAY` requires 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, this text consumer still uses only the four fields above and does not enforce the complete atomic-freshness contract. Connect-token issuance cannot currently return a cached success because its fail-closed guard precedes replay reads; the target replay/persistence and revalidation contract is 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 current text consumer 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 non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Text `PLAY` returns `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 on a supported text path 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. @@ -367,9 +367,11 @@ Authentication-local consequences are limited to bootstrap and admission sequenc #### Gateway-to-Game Session connect context (normative) -Gateway strips the external carrier and attaches one signed, short-lived non-JWT context. Gateway owns issuance, replay, its dedicated asymmetric signing-key namespace, verification-key publication and rotation, and carrier policy as defined by [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). Game Session owns receiving-service validation, including explicit audience/recipient binding, before applying gameplay admission. A JWS serialization does not turn this envelope into an Account-issued JWT profile or permit reuse of Account signing keys. +Gateway strips the external carrier and attaches one signed, short-lived non-JWT context. Gateway owns issuance, replay, its dedicated asymmetric signing-key namespace, verification-key publication and rotation, and carrier policy as defined by [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). Game Session owns receiving-service validation, including explicit audience/recipient binding, before applying gameplay admission. A JWS serialization does not turn this envelope into an Account-issued JWT profile or permit reuse of Account signing keys. The compact JWS has the exact protected header `{alg: RS256, kid, typ: application/firemud-connect-context.v1+jws}` and a closed payload schema; the versioned type binds the schema and does not require a separate payload issuer claim. Header and payload use RFC 8785 canonical JSON UTF-8 before signing. The verifier rejects noncanonical or padded compact encoding, duplicate or unknown fields, any other algorithm or type, and unknown Gateway key IDs. Gateway signing and verification keys remain a separate namespace from Account JWT keys. -Minimum context fields are `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `playtestLifecycleId` and positive `playtestStateGeneration` when the target is non-public (both absent for public production), `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the exact bounded selected-target `authorityTuple`, separate exact `membershipVersion`, `connectTokenJti`, `replayAdmissionFence`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`. The signed context's `issuedAt`-to-`expiresAt` lifetime is no longer than 30 seconds, subject only to the configured bounded clock-skew handling owned by Gateway. `connectRequestId` is the canonical signed-context name and carries the source `gameplay-connect` token's `requestId` (the connect-token issuance/request-operation identity); the context does not expose that source field under the generic name `requestId`. +The closed payload carries `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the exact bounded selected-target `authorityTuple`, the exact selected-tenant `membershipVersion`, `connectTokenJti`, positive `replayAdmissionFence`, `issuedAt`, `verifiedAt`, `expiresAt`, `gatewayRequestId`, `canonicalClientAddress`, and `transportClass: first_party_web`. For fresh `gameplay-connect` and this matching context, `pointerVersion`, `catalogRevision`, positive `replayAdmissionFence`, and the non-public `playtestStateGeneration` use the source owners' canonical positive decimal-string carriers; copied `authorityTuple` and `membershipVersion` retain their exact source shapes, values, and types. A non-public target additionally carries its exact `playtestLifecycleId` and positive `playtestStateGeneration`; public production omits and rejects both. `canonicalClientAddress` is derived by Gateway's trust/canonicalization path, and `transportClass` is the Gateway-observed `first_party_web` classification. Both are signed abuse metadata only: neither authenticates the peer, grants identity, or establishes replay readiness. The positive fence is compared with the Gateway-owned shared replay-readiness state; its presence in a signed context alone does not establish readiness or admission. `gatewayRequestId` is correlation-only and does not establish stable identity. The context carries no raw carrier or generic `requestId`. `connectRequestId` is the canonical name for the source `gameplay-connect` token's `requestId` (the connect-token issuance/request-operation identity). The `authorityTuple` and separate `membershipVersion` preserve the source contract's exact bounded field names, types, and selected-target key scope defined by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#jwt-claim-contract-normative). + +`issuedAt`, `verifiedAt`, and `expiresAt` are positive UTC epoch-millisecond integers no greater than `9,007,199,254,740,991`, the maximum safe integer in JSON. `verifiedAt` must not exceed `issuedAt`. `expiresAt` must follow `issuedAt`, must not exceed the 30-second envelope lifetime from `issuedAt`, and must not exceed the source token's `exp` converted to milliseconds using overflow-safe arithmetic. Gateway uses its existing bounded connect-token clock-skew semantics; it does not add post-consumption grace. The exact audience and recipient are `game-session` and `game-session-service`, set by Gateway rather than accepted from a client. - Game Session validates the asymmetric signature and `kid` against Gateway verification keys, validates the exact audience/recipient binding, enforces the bounded expiry, and rejects missing, invalid, wrong-recipient, or expired context with `CONNECT_CONTEXT_INVALID` before `PLAY`. - Game Session does not implement a second replay authority for `connectTokenJti`; it treats that value as access-controlled correlation and must not emit it as a metric label, ordinary log field, or trace attribute. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 9a664d1492..b1b622cb42 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -72,19 +72,19 @@ The optional [Validation Summary](../../.github/workflows/validation-summary.yml | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | -| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run applicable full-stack smoke proof, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without receiving registry-write credentials. | -| [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of full-stack smoke. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | +| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. The smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | +| [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub's event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. A stacked pull request may enter the same chain only while it is open, mergeable, based on another current branch in the same repository, and carries the maintainer-controlled `preview:priority` label. After a long-lived base branch's CI push run completes, trusted orchestration dispatches a new credential-free merge-image run and preview reconciliation for affected open PRs without changing their heads; scheduled reconciliation provides the equivalent exact-tuple detection for an eligible stacked parent advance. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own full-stack smoke succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. +The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub's event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. A stacked pull request may enter the same chain only while it is open, mergeable, based on another current branch in the same repository, and carries the maintainer-controlled `preview:priority` label. After a long-lived base branch's CI push run completes, trusted orchestration dispatches a new credential-free merge-image run and preview reconciliation for affected open PRs without changing their heads; scheduled reconciliation provides the equivalent exact-tuple detection for an eligible stacked parent advance. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. @@ -146,7 +146,7 @@ Other workflows support additional automation: - [`weekly-security-scan.yml`](../../.github/workflows/weekly-security-scan.yml) runs the weekly Trivy image scan. - [`ort-advisory.yml`](../../.github/workflows/ort-advisory.yml) runs the **Weekly ORT Advisory Scan**. - [`publish-base-image.yml`](../../.github/workflows/publish-base-image.yml) runs the **Weekly FireMUD Base Image Refresh** and is also the branch-guarded publication path for explicit base-image rebuilds on `develop` / `main`. -- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs applicable full-stack smoke without a registry-write token. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. +- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. --- diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index bce80338a6..f479fef6a1 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -14,9 +14,9 @@ Unless otherwise noted, this document describes target-state gateway behavior. C - **Current Game Design route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. The controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate; official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. - The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. -- The target replay domain is a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Gateway carries its non-secret domain pin in `FIREMUD_GATEWAY_REPLAY_DOMAIN`, which must equal exactly `gateway-connect-token-replay-v1` and is rendered as the fixed `{gateway-connect-token-replay-v1}` hash tag. Startup, target preflight, and migration/reset tooling must reject any other value and prove the same tag across Gateway instances and shared Coordination Redis readback. The current `GameplayHandshakeFilter` still writes only a legacy replay marker through the generic Cache-bound client; it has no browser-deny, readiness, or replay-fence writer. This is migration-only drift: before target admission, the named Coordination client/ACL must be cut over, the legacy state must be inventoried and read back under quarantine, the target contract must be verified, and legacy markers must be retained or explicitly cleaned only after their original acceptance windows expire. +- The target replay domain remains a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Its non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` pin and shared hash-tag contract remain unimplemented. The current `GameplayHandshakeFilter` denies a presented first-party cookie with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` before validation, context signing, replay consumption, or upstream admission; it no longer authorizes handshakes through a legacy Cache-bound replay marker. Dedicated signing-key delivery, shared readiness/fence/consume writers, browser-deny state, and qualified Account source production remain open. Removing the old writer does not establish legacy-state cleanup: retain prior markers through their original acceptance windows and use the owner-defined inventory/readback and recovery contract before target admission. - Dynamic REST and gRPC route-management APIs remain local/dev/test-only ephemeral capabilities. The current implementation does not yet enforce the target profile, endpoint isolation, validation, or startup boundary, so these APIs must not be treated as production-safe merely because they exist. -- Connect-token carrier parsing, required routing claims, expiry, and Redis replay checks are implemented for `/ws/game/**`, but current claims and the emitted signed context do not carry and prove durable `realmId`, the current carrier path still does not reject duplicate header values or duplicate token cookies, and successful cookie authentication strips the connect-token cookie carrier from the forwarded request. The protected-cookie `/ws/game/**` variant and bootstrap-backed bare `LOGIN` handoff are implemented but non-promotable in player-facing environments until the named Gateway readiness evidence is complete: exact selector-to-`{tenantId, realmId}` resolution and claim/context equality, carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. The target contract also requires explicit future-`iat` tolerance, `exp` tolerance, and the 30-second `iat`-to-`exp` hard maximum; the current shared `JwtUtil` parser uses JJWT defaults (no configured clock skew), and `GameplayHandshakeFilter` does not yet explicitly enforce those target `iat`/lifetime bounds. These readiness gaps do not mean that the existing signature, claim, expiry, carrier, or replay checks are absent. +- Public first-party `/ws/game/**` admission and gameplay-route readiness currently fail closed. The filter rejects the unsupported header carrier and missing cookie, then denies a presented cookie while canonical Account production, replay readiness/consumption, and dedicated Gateway keys are unavailable. The receiver source verifies and retains the complete dedicated signed envelope and canonical route snapshot, but bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or gameplay-binding effects. Earlier HMAC validation, cache-marker replay checks, and partial-context bare-login behavior are superseded; they do not establish current admission. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-first-party-receiving-preparation) records focused proof and remaining genuine authority, lease, finalization, and packaged-runtime gaps. The current shared pod readiness probe makes this an explicit combined-workload hold: both the public Gateway and internal TCP Proxy mTLS Services withdraw selected pods while first-party readiness is `OUT_OF_SERVICE`; independent route-level Service admission remains a pre-rollout gap. See [Gateway readiness](./microservices/spring-cloud-gateway/README.md#readiness-and-liveness) for the owner contract and current deployment qualification. The separate trusted TCP Proxy listener path retains its distinct handshake trust checks, but is not independently Service-ready in the current deployment. - The target bounded typed Game Session → Gateway lifecycle-intent contract is not implemented or versioned yet. Current Gateway behavior infers lifecycle intent from upstream close/error behavior; the target and its implementation/proof boundary are recorded in [ADR 0131](./decisions/adr-0131-lifecycle-distinct-gameplay-close-taxonomy.md#implementation-status). Gateway remains the sole authority for translating that intent into external WebSocket close semantics. ## Gateway Pattern @@ -142,7 +142,7 @@ After applying strip/authentication rules, the gateway sets or forwards the down - `X-Proxy-Connection-Id` – preserved unchanged only after TCP Proxy authentication as the sole gateway-authenticated, server-owned opaque raw-name correlation field so downstream services can correlate lifecycle signals with the TCP Proxy's `NotifyDisconnect {proxyConnectionId, disconnectSequence}`; the raw inbound header is stripped before this authenticated value is re-added. It is not authentication or session authority. - `X-Game-Instance-Id` / `X-Tenant-Id` – downstream game/tenant context generated from authenticated TCP Proxy metadata when the corresponding `X-Proxy-Game-Instance-Id` / `X-Proxy-Tenant-Id` inputs are present. Raw proxy names are stripped and never forwarded. - `X-World-Slug` / `X-Realm-Slug` / `X-Pointer-Version` – one all-or-none routing bundle derived from verified connect-token claims on non-proxy admission or accepted from the authenticated TCP Proxy bridge. A partial, malformed, or non-positive-version bundle is rejected. These values and the game/tenant fields remain advisory admission context; Game Session validates them against current session, entitlement, catalog, and admission-pointer authority. -- `X-Firemud-Connect-Context` – for non-proxy `/ws/game/**` handshakes that pass connect-token validation, gateway emits a short-lived signed context payload containing the complete verified connect scope: `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the bounded selected-target `authorityTuple` including its applicable caller-membership generation, exact `membershipVersion: {tenantId: version}` map containing only the selected tenant, `replayAdmissionFence`, `connectTokenJti`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`. Multi-Tenancy resolves the tenant-local `{tenantId, realmSlug}` selectors to the durable `realmId`; Account carries that exact resolved realm snapshot and admission evidence in the `gameplay-connect` token. Private/playtest targets additionally carry the exact `playtestLifecycleId` and positive `playtestStateGeneration`; public-production contexts omit both and reject either field if present. The lifecycle ID and generation must equal the verified source claim and selected-target context exactly, and remain distinct from the admission-pointer `pointerVersion`. The context `expiresAt` is no later than the source `gameplay-connect` JWT `exp` and no later than `issuedAt + 30 seconds`; Gateway never extends the source token lifetime or grants a post-consumption grace period. The `audience` and `recipient` values are registered context bindings, not client input. Gateway carries these Account-produced selectors, durable realm identity, and authority evidence unchanged without reinterpretation, independent realm resolution, or rescoping; its provenance and Game Session's joint continuation validation are defined by the [canonical JWT and token contract](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) and [ADR 0137](./decisions/adr-0137-isolated-playtest-state-modes-and-reset.md). Game Session must validate the complete context schema, signature, expiry bounds, exact audience/recipient and claim/context equality, then validate the durable realm identity, lifecycle ID, positive generation, namespace, and current caller grant together for private/playtest admission before using this context; public-production admission rejects those playtest fields. Replay protection for `connectTokenJti` remains Gateway-owned and is not re-implemented as a second authority in Game Session. `connectTokenJti` is internal replay/audit evidence and is never returned in client metadata or protocol output. +- `X-Firemud-Connect-Context` – for non-proxy `/ws/game/**` handshakes that pass connect-token validation, Gateway emits the signed short-lived envelope whose closed schema, exact protected header, canonical encoding, audience/recipient, source-claim mapping, signed canonical client address, and `first_party_web` abuse classification are defined by [Authentication and authorization](./system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). Gateway validates and carries the Account-produced selected-target snapshot without reinterpretation, independent realm resolution, or rescoping; private/playtest fields remain exact and are distinct from `pointerVersion`. `expiresAt` must not exceed the source token expiry or the 30-second envelope maximum. Gateway alone consumes `connectTokenJti` against the shared replay fence; Game Session does not create a second replay authority and must not expose `connectTokenJti` in client metadata, ordinary logs, metrics, or trace attributes. - `X-Firemud-Connection-Mode` – gateway-owned marker identifying the gameplay admission path. `first_party_web` identifies public non-proxy WebSockets admitted through the protected first-party cookie path; `trusted_tcp_proxy` identifies only the authenticated internal TCP Proxy mTLS bridge and is not a public WebSocket mode. A future `non_first_party_public` value is reserved but unavailable. The current `first_party_web` value covers browser/mobile-browser and native or other nonbrowser Account clients using a protected cookie jar; it identifies the verified connect-token path rather than a browser-only client class. It does not authorize a tokenless generic WebSocket path or imply current support for `X-Firemud-Connect-Token`. Game Session must treat this header as meaningful only when produced by the gateway after trust/canonicalization filters run, and must reject `/ws/game/**` admissions that present neither supported mode. - `X-Session-Id` is not part of the canonical header contract and must not be emitted or consumed for gameplay/session binding decisions. @@ -360,6 +360,7 @@ This section is the canonical source of truth for connect-token enforcement and - Issued only by the account/authentication control-plane after account authentication and tenant entitlement checks. - Issuance is performed via the control-plane connect-token API (for example `POST /auth/connect-token`); gateway must not mint connect tokens. - Account may issue only while the shared replay-readiness record is `OPEN`, and each token carries the exact `replayAdmissionFence` observed for that decision. Missing, unreadable, quarantined, or changing replay readiness fails issuance closed. + - Fresh `gameplay-connect` and the matching signed Gateway context carry `replayAdmissionFence` as a canonical positive decimal string in the signed-BIGINT range `1` through `9223372036854775807`. It is an owner-monotonic fence compared for exact equality with Gateway's authoritative readiness state; when the owner reaches the maximum, further advancement fails closed. The owner must not wrap, reuse, or implicitly reset the value. A syntactically valid fence in the source token or signed context does not prove that replay readiness is open or that the token was consumed. - Audience is exactly `gameplay-connect`, the token profile for the gateway gameplay route (`/ws/game/**`), and must not be accepted on unrelated routes. - Gateway validates signatures against the issuer's published verification key set with explicit `kid` selection and overlap handling during rotation. - **Transport location** @@ -431,9 +432,9 @@ This token is an edge admission/rate-limiting hint only. It does not replace `LO - **Verified context handoff (Gateway -> Game Session)** - After successful connect-token validation, Gateway must emit a signed, short-lived connect context (`X-Firemud-Connect-Context`) for the upgraded `/ws/game/**` connection. - Gateway strips every external connect-token carrier before forwarding. The raw header or cookie token never reaches Game Session or another upstream service. - - Context payload must carry the registered schema: `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the bounded selected-target `authorityTuple` including its applicable caller-membership generation, exact `membershipVersion: {tenantId: version}` map containing only the selected tenant, `replayAdmissionFence`, `connectTokenJti`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`; private/playtest contexts additionally carry the exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public-production contexts omit and reject both. `playtestStateGeneration` is separate from the admission-pointer `pointerVersion`. Multi-Tenancy resolves the tenant-local `{tenantId, realmSlug}` selectors to the durable `realmId`, and Account carries that exact resolved realm snapshot and admission evidence in the `gameplay-connect` token. Gateway is the producer and must set the registered audience and recipient itself; it carries the Account-issued selected-target snapshot's durable realm identity, selectors, namespace/scope claims, and authority evidence unchanged, with exact equality through the signed context, and does not own or derive an independent realm, namespace, or scope authority. Gateway accepts those realm, namespace/scope, and runtime-target fields only as the server-resolved target already bound to the exact `catalogRevision`/`pointerVersion` pair; it must not select a newer pointer, substitute carrier fields, or resolve a separate realm/namespace/scope. The lifecycle ID and generation must match the verified source claims and selected-target context exactly. The evidence provenance, lifecycle/grant predicate, and Game Session continuation check are defined by the [canonical JWT and token contract](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) and [ADR 0137](./decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); Game Session is the consumer and must validate those exact values before admission. + - The Gateway context must follow the exact schema and source mapping owned by [Authentication and authorization](./system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). It includes the complete selected-target snapshot, exact `audience` and `recipient`, Gateway-derived signed canonical client address, fixed `first_party_web` transport classification, and bounded timestamps; Gateway sets receiver bindings itself and carries the Account-issued selected-target evidence unchanged. It does not derive an independent realm, namespace, scope, lifecycle, or admission-pointer authority. - The producer/consumer contract proof must cover one representative signed context with every required field and exact `audience`/`recipient`, plus rejection of missing or wrong audience/recipient, altered claims, wrong field types, invalid signature/key, and expired context. Signature verification alone is not proof of the handoff contract. - - Game Session validates the complete signed-context schema before using any field for `LOGIN`, `PLAY`, or scope comparison. Required fields are present with their declared scalar, map, or object types; `authorityTuple` and the selected-tenant `membershipVersion` map are structurally exact; `audience=game-session`, `recipient=game-session-service`, the positive `first_party_web` mode, signature (`kid` aware), bounded `issuedAt`/`expiresAt`, and all context bindings are valid. Private/playtest contexts require a positive `playtestStateGeneration` and exact `playtestLifecycleId`/generation equality with the verified source claims and selected target, followed by current lifecycle, namespace, and caller-grant validation; public-production contexts reject either playtest field. A missing field, wrong-typed field, altered claim, or field not bound to the Gateway-verified source token/selected target is rejected before any scope fallback or `PLAY` use. Replay protection for `connectTokenJti` is performed only at Gateway handshake time. + - Game Session validates the complete signed-context schema before using any field for `LOGIN`, `PLAY`, or scope comparison, using the exact field types and omission rules owned by [Authentication and authorization](./system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). It verifies the fixed algorithm and `kid`, canonical encoding, exact `audience` and `recipient`, `first_party_web` classification, timestamp bounds and source binding, then compares the exact selected scope. A missing field, wrong-typed field, altered claim, or field not bound to the Gateway-verified source token/selected target is rejected before any scope fallback or `PLAY` use. Replay protection for `connectTokenJti` is performed only at Gateway handshake time. - Missing/invalid/expired context on non-proxy handshakes that required connect-token validation must be rejected with the existing gameplay protocol error `ERROR CONNECT_CONTEXT_INVALID reason=` before `PLAY` (no scope fallback to raw headers). The bounded reasons are `missing_field`, `wrong_field_type`, `altered_claim`, `unbound_claim`, `invalid_signature`, `unknown_kid`, `expired`, `audience_mismatch`, and `recipient_mismatch`; they are machine-readable subreasons, not a second browser or handshake taxonomy. - If the failure occurs before HTTP 101, Gateway exposes the existing handshake class and reason surface to capable non-browser HTTP callers and structured operator telemetry; source-token failures use `CONNECT_TOKEN_REJECTED` with `reason=invalid_token_content` when that is the classified cause. If the signed context is rejected after HTTP 101, Game Session uses the existing `ERROR ` protocol surface above and closes the socket. Browser clients use the conservative pre-upgrade recovery rule above and the established gameplay protocol for post-upgrade failures; they do not infer class or reason from inaccessible failed-upgrade headers. - Gateway must also emit `X-Firemud-Connection-Mode: first_party_web` for these first-party protected-cookie connect-token-validated handshakes, including native or other nonbrowser Account clients using a protected cookie jar. This current marker does not establish support for `X-Firemud-Connect-Token`; a future dedicated nonbrowser route may use the same marker only after its route and proof are complete. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 407551d029..556027a428 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -368,6 +368,8 @@ For `gameplay-connect`, the complete issuance contract is the Account `IssueConn | `globalRoles` | Optional list | Optional list | Absent | Optional list | Omission and explicit `[]` both mean no global roles; when present, the exact role list is required. `gameplay-connect` admission never authorizes from role claims | | `scopedRoles` | Required; `{}` when none | Empty map | Absent | Optional; generation maps align to delegated binding scope rather than this claim | Omission is rejected for `control-ui`; generation-map keys must be subsets of its tenant UUID keys and must exactly match the independent token-allowed target-tenant and caller-membership route predicates; no generation map may introduce an unclaimed tenant | +For the fresh `gameplay-connect` source and its Gateway connect-context projection, `pointerVersion`, `catalogRevision`, optional `playtestStateGeneration`, and `replayAdmissionFence` use canonical positive decimal-string JSON carriers within each owning source's declared positive-BIGINT range. The copied `authorityTuple` and separate `membershipVersion` retain the exact source values, field shapes, and JSON types; their generation, grant-version, cutoff-sequence, and membership-version counters use their owning contracts' canonical decimal-string forms. Gateway's `replayAdmissionFence` range and exhaustion behavior are owned by [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). This field-level mapping is specific to fresh `gameplay-connect`; it does not change other JWT profiles, the `iat`/`nbf`/`exp` NumericDate fields, or retained signed bytes. The mixed safe-number/wide-decimal-string rule in [ADR 0047](./decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) applies only to `reservationClaimFence` and is not a blanket JWT carrier rule. + `Required` means the claim must be present with a valid type. For an `Optional` list/map claim, omission is semantically equivalent to its declared empty value (`[]` or `{}`), never to authority; when present it must have the exact declared type and shape. For an `Optional` object claim, omission is allowed only when the object is inapplicable and is never equivalent to `{}` or `[]`. A present optional list/map claim with no entries must use that exact empty representation. Positive-value constraints apply only where a generation, cutoff sequence, fence, or other numeric claim is specified to be positive; string claims must be non-empty and satisfy their exact issuer, subject, profile, or audience contract, and time claims must be valid UTC epoch-second values. `Empty map` means the claim must be present as `{}`; `Empty list` means the claim must be present as `[]`; `Absent` means the claim must not be serialized for that profile. In any profile that marks it Optional, `globalRoles` follows the optional-list rule: absence and `[]` both mean that the token carries no global roles, and neither grants or implies a role. For `control-ui`, `scopedRoles` is required even when empty. Its `tenantAuthorityGeneration` keys are the non-empty scoped-role tenant keys whose allowed routes require target-tenant authority, while its independent `membershipAuthorityGeneration` and `membershipVersion` maps contain the caller-membership tenant keys needed by the allowed route classifications, including a `billing_safe_tenant` key without a target-tenant authority entry. Omission of `scopedRoles`, `authorityTuple`, either required generation map, or any applicable generation-map key is rejected. The `billing_safe_tenant` route may omit comparison with the target-tenant generation only under its closed route classification; it may not omit the canonical generation claim or the required membership key from that claim. An explicitly non-tenant profile may use every map/list claim that its profile declares with an empty value; `player-bootstrap` is one such profile, so its authority maps and `scopedRoles` are empty and its private-realm grant list is empty. A tenant-bound private player-delegation profile has no end-user role scope or `scopedRoles` key requirement, but it must carry both authority maps with exactly one shared, non-empty key derived from the exact delegated gameplay binding `{accountId, tenantId}`; the receiver rejects any extra, missing, empty, wildcard, bare realm, account, or differently keyed entry. Empty maps/lists never satisfy a tenant-bound delegation predicate. For non-`control-ui` validation, map presence and key-set rules are applied from the profile and route contract independently; validators must not infer equality between tenant-authority, membership-authority, and membership-version maps merely because the claims are present. The private-delegation shared-key rule is an explicit profile constraint, not a generic rule. diff --git a/design/architecture/system-architecture-security.md b/design/architecture/system-architecture-security.md index 5ad6a9a0aa..5e272599ca 100644 --- a/design/architecture/system-architecture-security.md +++ b/design/architecture/system-architecture-security.md @@ -104,7 +104,7 @@ Routine internal gameplay delegation uses concrete mTLS workload identity, metho Every gameplay workload certificate must resolve to one approved service identity. Consumers reject a generic internal-service claim, an unknown certificate identity, a caller not allowlisted for the exact RPC, missing context scope, or context that does not match the request and owning domain data. Mutation replay remains governed by command/effect/request idempotency. -Compromise response revokes or replaces the affected workload certificate, removes its method permissions, and audits calls made under that identity. Account JWT and Gateway connect-context keys retain their separate rotation contracts. Administrative and financial operations use their own control-plane and payment security boundaries rather than introducing gameplay-wide per-action signatures. +Compromise response revokes or replaces the affected workload certificate, removes its method permissions, and audits calls made under that identity. Account JWT and the dedicated Gateway connect-context signing keys retain separate namespaces and rotation contracts; the envelope contract is owned by [Authentication and authorization](./system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). Administrative and financial operations use their own control-plane and payment security boundaries rather than introducing gameplay-wide per-action signatures. --- diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 4747fb0855..689e7ca94e 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -167,11 +167,13 @@ Test data seeding strategies use the `dev-tools/seed/seed-test-data.sh` script t The canonical player-flow baseline is `LOGIN` -> `PLAY` -> `LOOK`. It is read-only with respect to ordinary playable state, although login, session, presence, and transport effects still follow their normal contracts. An advertised player-flow canary remains subject to [ADR 0161](./decisions/adr-0161-profile-aware-isolated-synthetic-player-flow-canaries.md), including its Account-owned restricted synthetic identity and transport isolation, even when its representative command is read-only. The optional item/container/equipment extension is mutating. The current standalone WebSocket and Telnet clients default to the baseline; mutation requires `SMOKE_MUTATION_EXTENSION=true`, `SMOKE_MUTATION_BOUNDARY=run-owned-compose`, and the explicit per-run binding enforced by [`run-owned-compose.sh`](../../dev-tools/smoke/run-owned-compose.sh). Project-name shape alone must never authorize destructive or mutating smoke access. +Runtime-image CI explicitly selects `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held` while public first-party admission is intentionally held. That mode waits for the run-owned stack with all required services running, supporting services healthy, and Gateway/TCP Proxy unhealthy; it verifies their real public readiness responses are `OUT_OF_SERVICE`, a real Telnet connection to its exact published run-owned port receives the exact `startup_unavailable` denial and closes, and a first-party Gateway WebSocket handshake reaches the public listener from inside the exact run-owned Gateway container over loopback. The Gateway handshake records the actual socket peer and accepts only the exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` response, which demonstrates that this loopback peer continued past the earlier TCP-trust filter as an untrusted peer without proxy identity. The local trust inputs are checked against the run's non-secret Compose settings; a trusted-peer short-circuit, missing classification, or unexpected source address fails closed. Gateway readiness, TCP management readiness, and Telnet remain bound to the exact published ports of the run-owned services; endpoint overrides fail closed. The container-loopback handshake does not prove host-published Gateway ingress. Missing, malformed, unexpected, accidentally ready, or silent responses fail the qualification. The existing direct Game Session WebSocket smoke still performs the positive `LOGIN` -> `PLAY` -> `LOOK` backend proof. Held mode does not prove successful public Gateway or Telnet admission and does not change public readiness. The wrappers retain `baseline` as their default; use the explicit mode only when the held-admission boundary is the intended proof. + [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md#runtime-and-smoke-changes) owns validation-entrypoint selection and evidence reporting for this boundary. The run-owned Compose contract is explicit and per invocation. In local mode, `FIREMUD_SMOKE_RUN_ID` is required and must match `^[a-z0-9][a-z0-9-]*$`, `COMPOSE_PROJECT_NAME` must equal `firemud-smoke-$FIREMUD_SMOKE_RUN_ID` exactly, and destructive or mutating access also requires a high-entropy `FIREMUD_SMOKE_OWNERSHIP_TOKEN`. The helper stores only that token's digest in an atomic user-private marker and holds a project lock. In GitHub Actions mode (`GITHUB_ACTIONS=true`), nonempty `GITHUB_RUN_ID`, `GITHUB_RUN_ATTEMPT`, and `GITHUB_JOB` are required; the invocation capability is derived from that exact run/attempt/job tuple and the project name must equal `smoke-full-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT` exactly. The helper fails closed when the binding or capability is missing, invalid, or mismatched. -Fresh-bootstrap and image-tag invocations may establish a new claim only when no project-labelled resources exist; an invocation retaining the exact matching capability may reuse its existing claim. Restart and mutation require the matching marker and project resources; unmarked, mismatched, malformed, symlinked, or colliding state fails closed and is never auto-reclaimed. Mutation additionally requires the canonical endpoint to map to exactly one running expected Compose service. Cleanup releases the marker only after all resources for the project are gone. This is an anti-accidental-mis-targeting and replay boundary, not authentication against a hostile Docker-daemon user. The fresh-bootstrap, restart-state, and image-tag wrappers execute both transports in baseline-only mode and reject mutation requests until independent transport identities and playable state exist. A persistent/shared environment may use the target restricted-synthetic identity, namespace, and fence verifier only after that verifier is implemented; it is not a current mutation path. A run-owned Compose project is the only currently supported mutation boundary. Its whole-stack teardown disposes that test deployment and is not authority to reset Coordination Redis; Coordination Redis reset remains governed by the canonical Redis operations owner and its quarantine/fence contract. +Fresh-bootstrap and image-tag invocations may establish a new claim only when no project-labelled resources exist; an invocation retaining the exact matching capability may reuse its existing claim. Restart and mutation require the matching marker and project resources; unmarked, mismatched, malformed, symlinked, or colliding state fails closed and is never auto-reclaimed. Mutation additionally requires the canonical endpoint to map to exactly one running expected Compose service. Cleanup releases the marker only after all resources for the project are gone. This is an anti-accidental-mis-targeting and replay boundary, not authentication against a hostile Docker-daemon user. The fresh-bootstrap, restart-state, and image-tag wrappers default to both transports in baseline-only mode and reject mutation requests until independent transport identities and playable state exist. Fresh-bootstrap and image-tag wrappers can explicitly select the held-admission qualification described above; that mode does not prove successful public admission. A persistent/shared environment may use the target restricted-synthetic identity, namespace, and fence verifier only after that verifier is implemented; it is not a current mutation path. A run-owned Compose project is the only currently supported mutation boundary. Its whole-stack teardown disposes that test deployment and is not authority to reset Coordination Redis; Coordination Redis reset remains governed by the canonical Redis operations owner and its quarantine/fence contract. The future persistent/shared mutation path is narrower than run-owned Compose and never authorizes a whole-stack reset. A future disposable preview mutation/reset boundary must be uniquely owned by the exact run and head under test; stable/shared Compose, shared `dev-demo-cluster`, hobby, staging, and production deployments cannot become disposable by an operator label or smoke-script convention. It requires an Account-owned restricted synthetic identity, a fresh server-authoritative `playableStateNamespaceId`, the server-derived `playableStateScope`, applicable positive state generation and admission/reset fence, and protected unique run identity, all acquired and exact-compared by the authoritative owners immediately before any mutation. A missing, unavailable, stale, or mismatched namespace/scope binding fails closed; callers must not invent, reuse, or infer these bindings from `gameInstanceId`, tenant, account ID, fixture name, or local timestamp. Where the run is a playtest lifecycle, the applicable `playtestLifecycleId` and `playtestStateGeneration` are part of the exact tuple. Only playable state owned by that namespace and scope may be mutated. Global account identity and credentials, authentication sessions and authority generations, connect-token replay state, global or derived indexes, and irreversible external effects remain outside the boundary or are redirected to explicit test sinks. Run-owned disposable mutation likewise excludes or redirects irreversible external effects, and synthetic status never bypasses authentication, authorization, abuse controls, moderation, security monitoring, or durable audit. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f614627016..aff6695e12 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -96,3 +96,28 @@ Entry format: - Observation: Verifying the checkout did not prevent a typo in the absolute patch target. The helper reported the mistake; Main compared the misplaced and intended files byte-for-byte, removed only the confirmed new duplicate, and preserved the sibling directories. No misplaced file was published. - Expected pattern: Compare every patch target with the pinned worktree path, then inspect the first written file at that absolute destination before continuing. This destination check remains manual. - Reconsideration trigger: enforce destination verification at the native patch boundary, or repeat measurement disproves the risk; completion of migration review alone does not resolve it. + +- `2026-10-15`: Preserve receiver status when relocating inherited tracker proof + - Context: the local #3224 parent reconciliation relocated inherited LOGIN proof into a dedicated section. Selecting the complete incoming tracker plus one receiver proof paragraph also displaced the receiver's first-party denial and historical-proof qualifications. The candidate had not been published. + - Observation: verifying nonoverlapping blobs and paragraphs unique against the merge base missed receiver status that also appeared in the base. Main later compared the complete receiver document, restored every original receiver paragraph byte-for-byte, and retained the incoming concise status and relocated proof. No production source changed. + - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. + - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. + +- `2026-10-16`: Report source validation separately from packaged smoke + - Context: PR #3224 had a successful Validation result and a separate runtime-image Smoke failure in run [38844094461](https://github.com/benhook1013/FireMUD/actions/runs/38844094461); the retained local job record showed Gateway and TCP Proxy public readiness intentionally out of service after the bounded Compose wait. + - Observation: successful source validation does not replace packaged-image runtime proof, and an expected held-readiness result does not justify weakening public readiness or extending timeouts. + - Expected pattern: report Validation and Smoke outcomes independently, select the held-admission qualification explicitly, and keep its positive backend claim separate from successful public admission. Follow the [player-flow smoke boundary](../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). + - Reconsideration trigger: reconsider the qualification after the held-admission runtime path has fresh packaged-image proof and the separate successful-admission obligation is complete. + +- `2026-10-16`: Bind publication destinations to the live PR branch + - Context: while receiving #3248, a manually typed plausible branch name created an unintended remote branch instead of updating the PR's actual `headRefName`. The correct PR branch remained unchanged until the mistake was detected. + - Observation: a successful push does not establish that the intended PR received the change. The worker used the live status response to publish to the correct branch, then deleted only its just-created accidental branch under an exact-commit lease. No PR or queue topology changed. + - Expected pattern: derive the push destination directly from the verified live PR identity, verify the destination and expected prior head before writing, then read back the PR head. A guarded controller publication operation could remove this manual mapping step. + - Reconsideration trigger: a canonical publication primitive enforces this identity binding; until then use the live `headRefName` without retyping it. + +- `2026-10-16`: Preserve terminal capture when a runtime command session disappears + - Context: a fresh #3224 held-admission attempt on `887586fb50769855e2bb74fa98192a92868933f3` started at 05:03:37 UTC, built images and started Compose, then its command session disappeared before qualification. The preserved console reports `Gradle wrapper exited; cancelling its owned run.` and authenticated teardown. + - Observation: the capture retained its initial identity and full console but no terminal exit code or end timestamp. The reason the owning process ended is unknown; the elapsed time alone does not establish a command timeout or the resource-admission budget as its cause. Targeted checks found no run-owned processes, containers, networks, volumes or ownership marker afterward. No Gateway/Telnet or backend positive proof completed. + - Expected pattern: keep the foreground command and its native session supervised through terminal completion, preserve the raw capture and report missing terminal evidence explicitly. An interrupted attempt and successful cleanup cannot count as runtime qualification. Supply command arguments as an explicit array when delegating; a sentence-ending period was separately mistaken for an argument and caused an avoidable pre-execution failure. + - Recovery: the next foreground canonical attempt on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` completed at 05:27:42 UTC with exit zero, full terminal capture, held-edge and backend proof, authenticated teardown and independently absent project resources. This does not establish why the earlier owner ended. + - Reconsideration trigger: a subsequent canonical attempt completes with terminal capture, or bounded process evidence identifies why the previous owner ended. 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 4c3bc0ddf3..51ff096564 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -156,20 +156,28 @@ Deployment must not advertise retained credential/security-write workflows as re These links add decision provenance only; they do not upgrade player-access or session capability status. +### Canonical first-party receiving preparation + +The local receiving preparation uses the dedicated Gateway RS256 non-JWT envelope defined by [Authentication and authorization](../../architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). [GatewayFirstPartyConnectContextEnvelope](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java) verifies the complete closed schema, canonical bytes, signature, receiver binding, bounded expiry, exact copied Account evidence, and decimal-string counters. Twelve focused controlled-key tests pass; this does not qualify an Account producer, Gateway replay consumption, or key delivery. + +[FirstPartyConnectContextService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java) joins that verified context to the current [canonical route owner read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java). Logical UUID authority stays separate from owner-supplied private storage handles. Retention keeps the original compact envelope and resolved owner snapshot, re-verifies expiry and current owner evidence on reads, and rejects old partial selector fragments, corruption, or unavailable authority. Main's latest focused evidence reports 12 controlled-key envelope tests, 199 Game Session unit cases after two narrow fixes, 184 Account unit cases after the fixture mock-history correction, 15 Gateway unit cases, and six physical Redis cases. The local socket-ownership correction requests transport close after send failure and performs disconnect cleanup only when the close callback atomically removes the exact registered transport. Forty-seven focused ownership unit cases and affected static/format gates pass. A fresh PostgreSQL-backed WebSocket class run passes 19 of 20 cases after default-off route-reader wiring is repaired; its remaining fixture-room assertion is corrected and that case passes in a separate focused run. The original startup and assertion failures and earlier all-skipped result remain retained; no genuine first-party admission authority is claimed. See [Session Behavior](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes). These partial results do not establish a complete consumer gate or packaged runtime. + +Account connect-token issuance retains its existing bootstrap and scope authentication checks, then denies before cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. + ## Capability Status | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. 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. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and 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.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | -| `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. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | +| `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. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. 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. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `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. 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. +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 requires membership permitting gameplay admission without an Entity read; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership or cached-success replay. 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. @@ -190,9 +198,9 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` 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). +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. The current `/auth/connect-token` validates bootstrap and connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/runtime reads, token minting, or replay/session mutation. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. 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). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. 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 remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -222,7 +230,7 @@ Game Session owns the canonical admitted-runtime normalization through `Gameplay First-party selector state used as connect or admission authority is also complete-or-absent. A pre-`PLAY` session shell may retain a normalized `{worldSlug, realmSlug, pointerVersion}` trio only as a non-authoritative lobby selection hint while `playableStateScope=UNSPECIFIED`; that hint cannot establish or preserve a runtime route, authorize `PLAY`, or become downstream gameplay metadata. A missing registry entry combined with any other partial persisted selector fails as `CONNECT_CONTEXT_INVALID` rather than degrading into ordinary realm selection, and malformed or incomplete bootstrap/connect authority is rejected before route preservation. Gateway trust-boundary failures and handshake scope failures remain distinct (`403`/trust rejection versus `CONNECT_SCOPE_MISMATCH`), while invalid first-party signed context is `CONNECT_CONTEXT_INVALID` or `CONNECT_TOKEN_REJECTED` according to the owning seam. -`PLAY` is the gameplay-binding step after authentication or verified first-party bootstrap identity. Its canonical admission semantics and outcome mappings are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md); current implementation and proof status are recorded under `AA-2.1`. First-party `PLAY` uses the same runtime authority as generic reconnect. +`PLAY` remains the gameplay-binding step after ordinary credential authentication and, in the target first-party path, after verified first-party identity. Public first-party identity is currently unavailable: Gateway cookie admission fails closed and Game Session bare first-party `LOGIN`/`PLAY` deny before downstream Account, Entity, or binding effects. Generic credential `PLAY` remains separately implemented. Canonical admission semantics and outcome mappings are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md); implementation and proof status are recorded under `AA-2.1`. The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admission before replacing an existing session. Replacement transfers/reserves the IP slot safely, leaves the existing session alive until the new session and reservation succeed, and on failed admission stops only the tentative session. The shared `GameInstanceService.startSession` default is non-destructive; replacement is explicit. Once replacement is admitted, failure to tear down the old session is warning/cleanup follow-up rather than grounds to revoke the newly accepted session. REST `/sessions` is explicitly noncanonical operator/bootstrap behavior. @@ -236,7 +244,7 @@ The lifecycle classes are deliberately distinct: - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. - Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. -Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. The current first-party connect-context path still reads and replays retained context after a post-logout `LOGIN` plus `PLAY`, which has not yet converged with the target rule that deliberate logout is not a recovery replay path. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. +Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. Earlier first-party screen-buffer tests exercised a post-logout replay path, but that behavior is historical: current public first-party `LOGIN`/`PLAY` is denied before admission and cannot establish current reconnect eligibility. Revisit the target rule that deliberate logout is not a recovery replay path when the protected first-party receiver is qualified. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. ### Reconnect and Continuity @@ -244,11 +252,11 @@ For generic Telnet and WebSocket, reconnect uses current identity and current Ac Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). -First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. The current screen-buffer projection restores retained context and fresh redraw, but resume-window enforcement, prompt proof, and post-logout suppression remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +Public first-party `/ws/game/**` is currently unavailable. Account validates bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation; Gateway rejects a presented cookie and reports route readiness unavailable while the canonical producer, shared replay readiness, and dedicated signing keys remain unqualified. In the current Kubernetes configuration this route hold is also the shared Gateway pod-readiness hold: both the public Gateway Service and internal TCP Proxy mTLS Service withdraw selected pods while the shared readiness endpoint is `OUT_OF_SERVICE`. The TCP Proxy listener keeps its distinct handshake trust boundary, but the current deployment does not provide it independent pod/Service readiness; that route-level separation remains a pre-rollout gap. The Gateway owner doc records this qualification and the ADR 0157 exception for explicit combined-workload holds in [Gateway Readiness and Liveness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness). Game Session retains complete signed-context and canonical-route/private-handle revalidation sources, but bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or binding effects and do not fall back from partial selectors. Earlier positive first-party handshake, screen-buffer, and reconnect results are historical. Canonical authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md), [Authentication and authorization](../../architecture/system-architecture-authentication.md), and [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). -Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. +Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused ordinary-transport proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. These transport continuity results do not establish first-party authenticated admission. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. -Shared coordination state now carries reconnect/connect-context tracking, disconnect deduplication, gameplay-identity screen-buffer access, and bounded takeover information, while the in-process socket remains local. Shipped proof is limited to the close-metadata fallbacks: missing or unattributed metadata on a public WebSocket emits close `1011`/`internal_error`, and missing or invalid top-level metadata on an established authenticated TCP Proxy bridge renders `DISCONNECT backend_unavailable ...`. Focused Gateway/bridge and Telnet-handler tests cover those classifications; they do not prove command/byte replay, the broader handler taxonomy, or the complete continuity contract. Those remaining gaps are tracked in [TCP Proxy Operations](../../architecture/microservices/tcp-proxy-service/operations.md#implementation-status); duplicate and missing disconnect hints remain separately metered. +Shared coordination state carries reconnect/connect-context tracking, disconnect deduplication, gameplay-identity screen-buffer access, and bounded takeover information, while the in-process socket remains local. These stores do not produce authenticated first-party ingress. Shipped close-metadata proof covers missing or unattributed metadata on a public WebSocket emitting close `1011`/`internal_error`, and missing or invalid top-level metadata on an established authenticated TCP Proxy bridge rendering `DISCONNECT backend_unavailable ...`; it does not establish a successful first-party handshake, command/byte replay, the broader handler taxonomy, or the complete continuity contract. Remaining gaps are tracked in [TCP Proxy Operations](../../architecture/microservices/tcp-proxy-service/operations.md#implementation-status); duplicate and missing disconnect hints remain separately metered. ### Fail-Closed Boundary Convergence @@ -257,26 +265,28 @@ The auth/session/routing guardrail family is complete at its current bounded sea - `JwtClaims`, `SessionClaims`, current-account access, current global-role-based gameplay classification drift, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; - bootstrap/connect-scope/runtime membership/grant/entitlement claim readers, account-subject coherence, replay readers/writers, and account REST/gRPC request readers in Account Service; - `GameplayAdmissionPointerSnapshots`, `ControlPlaneRequestParser`, `SessionIdParsing`, positive-ID readers, gameplay-character parsing, partial-shell classification, IP counter parsing, and command/control-plane routing normalization in Game Session; -- signed first-party handshake/connect-context checks and `TrustedTcpProxyIdentity` at Gateway, plus `TelnetRoutingBundle` and hidden bootstrap envelope handling at TCP Proxy; +- fail-closed first-party Gateway handshake/readiness and the source-prepared signed-context kernel, plus `TrustedTcpProxyIdentity`, `TelnetRoutingBundle`, and hidden bootstrap envelope handling at TCP Proxy; - the corresponding positive-ID, room-scope, actor-scope, replay-payload, current-account, routing-bundle, and REST error-envelope readers in World Management, Entity Management, Social Groups, Automation, Logging & Admin, Game Design, and Game Logic. The current numeric-reader guardrail is: numeric identifiers still used by an implemented seam must be present, well-formed, and positive; opaque room ids remain textual. This is not the durable cross-boundary target. [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) makes durable cross-boundary account, tenant, game-instance, character, and version identities scoped UUIDs, so replacing current numeric forms and proving scope-qualified comparison remains tracked migration work. Malformed or contradictory JWT/signed-token claims reject before identity comparison; partial routing bundles are absent or rejected, never completed by fallback; malformed persisted replay state is ignored/rejected or terminalizes only its affected durable work item; and request validation occurs before replay lookup when malformed shape could otherwise be masked by a stored effect. Malformed persisted Automation tenant identity terminalizes only that work item rather than aborting the batch. Unexpected parser/runtime bugs are not mislabeled as auth failures. This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The current classifier still maps a valid global `platformAdmin` claim to in-game `ADMIN`, contrary to the target rule that only explicit tenant-scoped gameplay grants may elevate presence or capabilities. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. -Replay boundaries validate both read and write sides. Account connect-token and public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. +Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` denies after bootstrap/scope validation before any replay read, token mint, or replay/session mutation. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) uses typed result unions for successfully produced expected domain outcomes and canonical non-OK status with bounded details when a domain result cannot be produced. Current Game Session/peer handlers still return many response-level `ErrorDetail` payloads, while transport failures cover infrastructure and some pre-domain cases; exact per-RPC migration and proof remain gaps. Shared REST exception handling continues to produce `ApiResponse` envelopes and field-specific `INVALID_ARGUMENT` responses instead of framework-default JSON. These seams log application warnings, meter `grpc.app_error` where applicable, and preserve span/error-code classification. ## Validation and Proof -The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; real Account-backed login and authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; first-party handshake/reconnect; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. +The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; real Account-backed generic login and authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. Earlier positive first-party handshake/reconnect proofs describe the superseded HMAC-cookie path and are historical. Current focused first-party tests cover denial and unavailable readiness; envelope, owner, retained-context, and consumer proofs remain bounded as recorded above and do not qualify production ingress. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. -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. +The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the 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. +The #3224 candidate adds an explicit held-admission image-smoke mode: it preserves the existing isolated backend `LOGIN` -> `PLAY` -> `LOOK` proof and checks that real Gateway and Telnet public paths fail closed while admission readiness is out of service. This is separate from successful public admission. The focused transport and image-environment contracts pass. Fresh source-built held-admission qualification on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` passes from 2026-10-16 05:20:30 to 05:27:42 UTC: the run-owned Gateway public listener receives the first-party loopback request outside configured TCP-proxy trust and returns exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`; Telnet returns `startup_unavailable` and closes; the direct backend completes `WORLDS`, `LOGIN`, `PLAY`, `LOOK` and `LOGOUT`. Canonical teardown completes and independent exact-project inspection finds no containers, networks or volumes. This proves the held mode and isolated backend flow; it does not prove Kubernetes Service endpoint withdrawal or independent TCP Proxy Service readiness. Host-published Gateway ingress and successful public admission also remain unproved. + +- **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) for the earlier documentation-only tracker update. The #3224 held-admission contracts and source-built runtime proof have the scoped attribution above; follow [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md#runtime-and-smoke-changes) for its deferred checks. ### Initial private gameplay LOGIN source proof @@ -316,15 +326,17 @@ The source-fence allocator intentionally locks one singleton row until the Accou Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). +At local source `0a685173e0982ba3c0006acb3e378d228daeadbb`, normally reconciled to published parent `7b2ce6340309198ed4fabd0e58629102ba717706`, the focused gate passed in 2m36s: 150 fresh unit cases and 35 physical Redis-context/PostgreSQL-journal cases, all with zero failures, errors or skips, plus Game Session Checkstyle, SpotBugs, formatting and documentation checks. The subsequent two composed-owner test additions on that local baseline passed all 28 physical Redis-context/PostgreSQL cases in the 57-second affected gate, with zero failures, errors or skips and affected static/format checks. The initial test-package compilation failures remain failed history; production constructor visibility was preserved. The unregistered [InitialGameplayLoginOwner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) reserves and independently reads back distinct server UUIDv4 request/context coordinates at fence 1 before create-only `PENDING`, then calls the [canonical Account client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java) with its bounded same-deadline retry guarded by current original credential custody. It records and reads back the verified nonsecret witness before exact-result installation and transfers the still-live private result to its caller; uncertain results and actual original pre-admission custody loss retain exact-original cleanup. This original-attempt lifecycle remains separate from already-admitted retained-edge rebind. The [owner proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java), [Redis integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java), and [journal integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java) exercise controlled composition and physical storage fixtures only. The composed physical cases check independently committed original coordinates before the first Redis mutation, actual PENDING creation and non-admitting installation, and same-invocation credential closure after a controlled Account response followed by exact-original Redis closure, frozen witness-bearing retirement, a PENDING disposal receipt and owned-result erasure. Account signing/disposal responses and external Redis qualification remain controlled inputs. The later 28-case evidence belongs to the local changed test postimage, not an authenticated production receiving chain. Caller registration, trusted Gateway/Proxy identity and protected custody, production Redis qualification, real Account mTLS/signing, qualified retained binding-history recovery, runtime activation, gameplay admission, and LOGIN wire success remain unproved; `AA-2.1` remains partial. See the canonical [session and identity model](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes), [plain-text LOGIN mapping](../../architecture/system-architecture-authentication.md#plain-text-login-logon-command-mapping), [original-attempt coordination](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination), [bounded non-edge recovery](../../architecture/system-architecture-reconnection.md#bounded-non-edge-restart-recovery), [initial-context aggregate](../../architecture/system-architecture-redis.md#initial-login-context-aggregate), and [Redis operation](../../architecture/system-architecture-redis-ops-access.md) owners. + ## Active Gaps - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. - Signup-time login-mode selection and authenticator-app TOTP enrollment/management are not implemented; the live credential contract remains password plus email OTP. Richer MFA policy for elevated users is also future work. - Tenant membership currently persists admission permission rather than the designed tenant-role set; Account JWT issuance does not emit tenant `scopedRoles`, and realm grants have no expiry or tenant-admin management surface. - The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. -- Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials, while public non-proxy `/ws/game/**` requires a verified connect-token context and bare `LOGIN`. -- Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. -- The first-party post-logout path still replays retained transcript context even though generic fresh login does not; that replay-projection mismatch must converge without treating durable transcript retention as reconnect eligibility. +- Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam accept parameterized credentials; public non-proxy `/ws/game/**` currently fails closed, and first-party bare `LOGIN`/`PLAY` do not reach legacy Account, Entity, or binding effects. +- Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect after its protected receiving chain is qualified, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. +- Earlier first-party post-logout replay behavior is historical and unreachable while first-party admission fails closed. Recheck it when the protected receiver is qualified; durable transcript retention alone must not establish reconnect eligibility. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. @@ -343,11 +355,11 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including the implemented `/auth/bootstrap/join` controller and local JOIN RPC; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token production currently fails closed after bootstrap/scope validation | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; 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 | -| Game Session | Text parser/interpreter, login/play/logout, Redis session context, takeover/resume, gameplay presence, admission normalization, command/control-plane routing, and redraw; StartSession retains the Account-compared owner tuple and checks it again through launch preparation | Text-command protocol; WebSocket ingress; Game Session gRPC/control plane; Account and World/Entity calls; owner-tuple consequence in [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | +| Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | +| Game Session | Text parser/interpreter, generic login/play/logout, Redis session context, takeover/resume, gameplay presence, admission normalization, command/control-plane routing, and redraw; first-party signed-context/route/private-handle receiving sources are local preparation, while bare first-party LOGIN/PLAY deny before downstream effects; StartSession retains and rechecks the Account-compared owner tuple | Text-command protocol; WebSocket ingress; Game Session gRPC/control plane; Account and World/Entity calls; first-party context consequence in [Authentication and authorization](../../architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative); owner-tuple consequence in [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | World and Entity Management | Current room/runtime authority, gameplay admission dependencies, runtime teardown, actor/item/room reads, and presence cleanup | Gameplay-attested gRPC/REST seams; World termination and Entity cleanup called by Game Session | | Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | diff --git a/dev-tools/smoke/held-admission-qualification.sh b/dev-tools/smoke/held-admission-qualification.sh new file mode 100644 index 0000000000..867c7dd760 --- /dev/null +++ b/dev-tools/smoke/held-admission-qualification.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + echo "Held-admission qualification must be invoked by sourcing it from the run-owned smoke wrapper." >&2 + exit 2 +fi + +HELD_ADMISSION_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + +run_held_admission_qualification() { + local gateway_api_base="${SMOKE_GATEWAY_API_BASE:-http://localhost:8080}" + local tcp_proxy_api_base="${SMOKE_TCP_PROXY_API_BASE:-http://localhost:8089}" + local telnet_host="${SMOKE_TELNET_HOST:-localhost}" + local telnet_port="${TCP_PROXY_PORT:-2323}" + + if [[ "${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-}" != "held" ]]; then + echo "Set FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held to run this qualification." >&2 + return 1 + fi + if [[ "$gateway_api_base" != "http://localhost:8080" ]]; then + echo "Held-admission Gateway probe requires the canonical localhost:8080 endpoint." >&2 + return 1 + fi + if [[ "$tcp_proxy_api_base" != "http://localhost:8089" ]]; then + echo "Held-admission TCP Proxy probe requires the canonical localhost:8089 endpoint." >&2 + return 1 + fi + if [[ "$telnet_host" != "localhost" || "$telnet_port" != "2323" ]]; then + echo "Held-admission Telnet probe requires the canonical localhost:2323 endpoint." >&2 + return 1 + fi + if ! declare -F require_run_owned_compose_service >/dev/null; then + echo "Held-admission qualification requires the run-owned Compose service guard." >&2 + return 1 + fi + + require_run_owned_compose_service gateway 8080 8080 || return 1 + require_run_owned_compose_service tcp-proxy-service 8080 8089 || return 1 + require_run_owned_compose_service tcp-proxy-service 2323 2323 || return 1 + + export SMOKE_GATEWAY_API_BASE="$gateway_api_base" + export SMOKE_TCP_PROXY_API_BASE="$tcp_proxy_api_base" + export SMOKE_TELNET_HOST="$telnet_host" + export TCP_PROXY_PORT="$telnet_port" + PYTHONPATH="$HELD_ADMISSION_REPO_ROOT/dev-tools/smoke${PYTHONPATH:+:$PYTHONPATH}" \ + python3 - "$@" <<'PY' +import sys + +from held_admission_qualification import run_qualification + +raise SystemExit(run_qualification(sys.argv[1:])) +PY +} diff --git a/dev-tools/smoke/held_admission_qualification.py b/dev-tools/smoke/held_admission_qualification.py new file mode 100644 index 0000000000..fa330c9ecc --- /dev/null +++ b/dev-tools/smoke/held_admission_qualification.py @@ -0,0 +1,616 @@ +#!/usr/bin/env python3 +"""Prove current held-admission behavior against a run-owned Compose stack.""" + +from __future__ import annotations + +import http.client +import ipaddress +import json +import os +import socket +import subprocess +import sys +import time +from urllib.parse import urlsplit + +from smoke_common import is_localhost_equivalent + +REQUIRED_SERVICES = ( + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "gateway", + "logging-admin-service", + "minio", + "postgres", + "redis-cache", + "redis-coord", + "social-groups-service", + "tcp-proxy-service", + "world-management-service", +) +HELD_ADMISSION_SERVICES = frozenset({"gateway", "tcp-proxy-service"}) +GATEWAY_ERROR_CLASS_HEADER = "X-Firemud-Handshake-Error-Class" +GATEWAY_HELD_ERROR_CLASS = "CONNECT_REPLAY_PROTECTION_UNAVAILABLE" +TELNET_HELD_DENIAL = ( + "DISCONNECT startup_unavailable Gameplay path starting; please reconnect\n" +) +MAX_HTTP_RESPONSE_BYTES = 64 * 1024 +MAX_GATEWAY_PROBE_OUTPUT_BYTES = 4096 + +GATEWAY_CONTAINER_PROBE_SCRIPT = r"""set -eu +timeout_seconds="${1:?bounded probe timeout is required}" +allow_value="${FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS:-false}" +tls_value="${FIREMUD_GATEWAY_TCP_PROXY_TLS_ENABLED:-false}" +cidr_zero="${FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0:-}" +if [ "$allow_value" = true ]; then allow_state=true; else allow_state=unexpected; fi +if [ "$tls_value" = false ]; then tls_state=false; else tls_state=unexpected; fi +if [ "$cidr_zero" = 172.16.0.0/12 ]; then cidr_state=172.16.0.0/12; else cidr_state=unexpected; fi +extra_indexes="$(env | awk -F= '$1 ~ /^FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_[0-9]+$/ && $1 != "FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0" { found=1 } END { print found ? "present" : "none" }')" +printf 'SMOKE_GATEWAY_TRUST allow=%s tls=%s cidr0=%s extra_indexes=%s\n' "$allow_state" "$tls_state" "$cidr_state" "$extra_indexes" +if [ "$allow_state" != true ] || [ "$tls_state" != false ] || [ "$cidr_state" != 172.16.0.0/12 ] || [ "$extra_indexes" != none ]; then + exit 21 +fi +probe_tmp="$(mktemp -d /tmp/firemud-held-admission.XXXXXX)" +trap 'rm -rf "$probe_tmp"' EXIT +trap 'exit 130' HUP INT TERM +if curl --silent --show-error --noproxy '*' --http1.1 --connect-timeout "$timeout_seconds" --max-time "$timeout_seconds" --max-filesize 65536 \ + --dump-header "$probe_tmp/headers" --output "$probe_tmp/body" \ + --write-out '%{local_ip}\t%{remote_ip}\t%{http_code}\t%{size_download}\n' \ + -H 'Connection: Upgrade' -H 'Upgrade: websocket' \ + -H 'Sec-WebSocket-Key: MDEyMzQ1Njc4OWFiY2RlZg==' -H 'Sec-WebSocket-Version: 13' \ + -H 'Cookie: Firemud-Connect-Token=held-admission-probe.invalid' \ + http://127.0.0.1:8080/ws/game >"$probe_tmp/metrics"; then + curl_state=ok +else + curl_state=failed +fi +header_bytes="$(wc -c < "$probe_tmp/headers" | tr -d '[:space:]')" +body_bytes="$(wc -c < "$probe_tmp/body" | tr -d '[:space:]')" +if [ "$header_bytes" -le 32768 ]; then + class_pair="$(awk -F: 'tolower($1) == "x-firemud-handshake-error-class" { count++; value=$2; sub(/^[[:space:]]+/, "", value); sub(/\r$/, "", value) } END { printf "%d\t%s", count, value }' "$probe_tmp/headers")" + class_count="${class_pair%%$(printf '\t')*}" + class_value="${class_pair#*$(printf '\t')}" + headers_state=ok +else + class_count=oversized + class_value= + headers_state=oversized +fi +case "$class_count:$class_value" in + 1:CONNECT_REPLAY_PROTECTION_UNAVAILABLE) class_state=expected ;; + 0:*) class_state=missing ;; + *) class_state=unexpected ;; +esac +IFS="$(printf '\t')" read -r local_ip remote_ip http_status download_bytes < "$probe_tmp/metrics" || true +printf 'SMOKE_GATEWAY_RESULT local_ip=%s remote_ip=%s status=%s class=%s class_count=%s body_bytes=%s curl=%s headers=%s downloaded=%s\n' \ + "${local_ip:-missing}" "${remote_ip:-missing}" "${http_status:-missing}" "$class_state" \ + "$class_count" "$body_bytes" "$curl_state" "$headers_state" "${download_bytes:-missing}" +""" + + +class QualificationFailure(RuntimeError): + """A required held-admission condition was missing or contradictory.""" + + +def parse_compose_status(output: str) -> dict[str, dict[str, object]]: + """Parse Compose's JSON array or newline-delimited JSON status output.""" + stripped = output.strip() + if not stripped: + raise QualificationFailure("Compose status output was empty") + try: + if stripped.startswith("["): + entries = json.loads(stripped) + else: + entries = [json.loads(line) for line in stripped.splitlines() if line.strip()] + except json.JSONDecodeError as exc: + raise QualificationFailure(f"Compose status output was malformed JSON: {exc}") from exc + if not isinstance(entries, list) or not entries: + raise QualificationFailure("Compose status output did not contain service records") + + services: dict[str, dict[str, object]] = {} + for entry in entries: + if not isinstance(entry, dict): + raise QualificationFailure("Compose status contained a non-object service record") + service = entry.get("Service") + state = entry.get("State") + health = entry.get("Health", "") + if not isinstance(service, str) or not service or not isinstance(state, str): + raise QualificationFailure("Compose status omitted a service name or state") + if not isinstance(health, str): + raise QualificationFailure(f"Compose status for {service} had a malformed health state") + if service in services: + raise QualificationFailure(f"Compose status duplicated service {service}") + services[service] = entry + return services + + +def classify_compose_status( + services: dict[str, dict[str, object]], +) -> tuple[str, str]: + """Return ready/pending or fail on an unexpected held-edge health state.""" + missing = [service for service in REQUIRED_SERVICES if service not in services] + if missing: + return "pending", f"missing required Compose services: {', '.join(missing)}" + + pending: list[str] = [] + for service in REQUIRED_SERVICES: + entry = services[service] + state = entry.get("State") + health = entry.get("Health", "") + if state != "running": + if state in {"created", "restarting"}: + pending.append(f"{service}: state={state}") + continue + raise QualificationFailure(f"Required Compose service {service} is not running: {state}") + + if service in HELD_ADMISSION_SERVICES: + if health == "healthy": + raise QualificationFailure( + f"{service} unexpectedly reported healthy during held-admission qualification" + ) + if health == "unhealthy": + continue + if health == "starting": + pending.append(f"{service}: health=starting") + continue + raise QualificationFailure( + f"{service} did not expose an expected health state: {health or 'missing'}" + ) + + if health == "healthy": + continue + if health in {"starting", "unhealthy"}: + pending.append(f"{service}: health={health}") + continue + raise QualificationFailure( + f"{service} did not expose a required health state: {health or 'missing'}" + ) + + if pending: + return "pending", "; ".join(pending) + return "ready", "all required services are running; only Gateway and TCP Proxy are unhealthy" + + +def validate_out_of_service_response( + status_code: int, body: bytes, service_name: str, component_name: str +) -> None: + if status_code != 503: + raise QualificationFailure( + f"{service_name} readiness returned HTTP {status_code}; expected HTTP 503" + ) + if not body: + raise QualificationFailure(f"{service_name} readiness returned an empty body") + try: + payload = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise QualificationFailure( + f"{service_name} readiness returned malformed JSON: {exc}" + ) from exc + if not isinstance(payload, dict) or payload.get("status") != "OUT_OF_SERVICE": + raise QualificationFailure( + f"{service_name} readiness did not report OUT_OF_SERVICE" + ) + components = payload.get("components") + if components is not None: + if not isinstance(components, dict): + raise QualificationFailure(f"{service_name} readiness components were malformed") + component = components.get(component_name) + if not isinstance(component, dict) or component.get("status") != "OUT_OF_SERVICE": + raise QualificationFailure( + f"{service_name} readiness component {component_name} was missing or unexpected" + ) + + +def validate_gateway_first_party_denial( + status_code: int, headers: dict[str, str], body: bytes +) -> None: + if status_code != 403: + raise QualificationFailure( + f"Gateway first-party WebSocket handshake returned HTTP {status_code}; expected HTTP 403" + ) + normalized = {name.casefold(): value for name, value in headers.items()} + observed = normalized.get(GATEWAY_ERROR_CLASS_HEADER.casefold()) + if observed != GATEWAY_HELD_ERROR_CLASS: + raise QualificationFailure( + "Gateway first-party WebSocket handshake omitted the expected " + f"{GATEWAY_ERROR_CLASS_HEADER}: {GATEWAY_HELD_ERROR_CLASS}" + ) + if body: + raise QualificationFailure("Gateway first-party denial unexpectedly returned a response body") + + +def validate_telnet_denial(response: bytes, closed: bool) -> None: + if not closed: + raise QualificationFailure("Telnet held-admission response did not close the connection") + try: + decoded = response.decode("ascii") + except UnicodeDecodeError as exc: + raise QualificationFailure("Telnet held-admission response was not ASCII") from exc + if decoded != TELNET_HELD_DENIAL: + raise QualificationFailure( + "Telnet held-admission response was missing or unexpected: " + f"{decoded.strip()!r}" + ) + + +def _local_http_endpoint(base_url: str, name: str) -> tuple[str, int]: + parsed = urlsplit(base_url) + if ( + parsed.scheme != "http" + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.path not in {"", "/"} + or parsed.query + or parsed.fragment + or not is_localhost_equivalent(parsed.hostname) + ): + raise QualificationFailure( + f"{name} endpoint must be an unauthenticated localhost HTTP base URL" + ) + try: + port = parsed.port or 80 + except ValueError as exc: + raise QualificationFailure(f"{name} endpoint had an invalid port") from exc + return parsed.hostname, port + + +def _http_request( + host: str, port: int, method: str, path: str, timeout_seconds: int, headers=None +) -> tuple[int, dict[str, str], bytes]: + connection = http.client.HTTPConnection(host, port, timeout=timeout_seconds) + try: + connection.request(method, path, headers=headers or {}) + response = connection.getresponse() + body = response.read(MAX_HTTP_RESPONSE_BYTES + 1) + if len(body) > MAX_HTTP_RESPONSE_BYTES: + raise QualificationFailure(f"HTTP {method} {host}:{port}{path} returned an oversized body") + return response.status, dict(response.getheaders()), body + except (OSError, http.client.HTTPException) as exc: + raise QualificationFailure(f"HTTP {method} {host}:{port}{path} failed: {exc}") from exc + finally: + connection.close() + + +def _assert_readiness_out_of_service( + base_url: str, timeout_seconds: int, service_name: str, component_name: str +) -> None: + host, port = _local_http_endpoint(base_url, service_name) + status, _, body = _http_request( + host, port, "GET", "/actuator/health/readiness", timeout_seconds + ) + validate_out_of_service_response(status, body, service_name, component_name) + print(f"Confirmed {service_name} public readiness is OUT_OF_SERVICE.") + + +def _parse_probe_record(line: str, prefix: str, keys: set[str]) -> dict[str, str]: + if not line.startswith(f"{prefix} "): + raise QualificationFailure(f"Gateway container probe omitted its {prefix} record") + fields: dict[str, str] = {} + for item in line[len(prefix) + 1 :].split(" "): + if "=" not in item: + raise QualificationFailure(f"Gateway container probe had a malformed {prefix} record") + name, value = item.split("=", 1) + if name not in keys or name in fields or not value: + raise QualificationFailure(f"Gateway container probe had an unexpected {prefix} field") + fields[name] = value + if fields.keys() != keys: + raise QualificationFailure(f"Gateway container probe had an incomplete {prefix} record") + return fields + + +def parse_gateway_container_probe_output( + output: str, +) -> tuple[dict[str, str], dict[str, str]]: + if len(output.encode("utf-8")) > MAX_GATEWAY_PROBE_OUTPUT_BYTES: + raise QualificationFailure("Gateway container probe output exceeded its 4 KiB bound") + lines = output.splitlines() + if len(lines) != 2: + raise QualificationFailure("Gateway container probe output was missing or malformed") + trust = _parse_probe_record( + lines[0], + "SMOKE_GATEWAY_TRUST", + {"allow", "tls", "cidr0", "extra_indexes"}, + ) + result = _parse_probe_record( + lines[1], + "SMOKE_GATEWAY_RESULT", + { + "local_ip", + "remote_ip", + "status", + "class", + "class_count", + "body_bytes", + "curl", + "headers", + "downloaded", + }, + ) + return trust, result + + +def validate_gateway_container_first_party_result( + trust: dict[str, str], result: dict[str, str] +) -> None: + expected_trust = { + "allow": "true", + "tls": "false", + "cidr0": "172.16.0.0/12", + "extra_indexes": "none", + } + if trust != expected_trust: + raise QualificationFailure( + "Gateway runtime trust configuration did not match the local Compose contract: " + f"allow={trust.get('allow', 'missing')}, tls={trust.get('tls', 'missing')}, " + f"cidr0={trust.get('cidr0', 'missing')}, " + f"extra_indexes={trust.get('extra_indexes', 'missing')}" + ) + + observed_addresses = {} + for field in ("local_ip", "remote_ip"): + try: + observed_ip = ipaddress.ip_address(result[field]) + except (KeyError, ValueError) as exc: + raise QualificationFailure( + f"Gateway container probe had an invalid {field} socket address" + ) from exc + if observed_ip != ipaddress.IPv4Address("127.0.0.1"): + raise QualificationFailure( + f"Gateway container probe {field} was {observed_ip}; expected loopback 127.0.0.1" + ) + observed_addresses[field] = observed_ip + try: + configured_trust_cidr = ipaddress.ip_network(trust["cidr0"], strict=True) + except (KeyError, ValueError) as exc: + raise QualificationFailure("Gateway runtime trust CIDR was malformed") from exc + if observed_addresses["remote_ip"] in configured_trust_cidr: + raise QualificationFailure( + "Gateway loopback peer falls inside the configured insecure TCP trust CIDR" + ) + + expected_result = { + "status": "403", + "class": "expected", + "class_count": "1", + "body_bytes": "0", + "curl": "ok", + "headers": "ok", + "downloaded": "0", + } + for field, expected in expected_result.items(): + if result.get(field) != expected: + raise QualificationFailure( + "Gateway container loopback handshake had an unexpected result: " + f"{field}={result.get(field, 'missing')}, expected {expected}" + ) + # HeaderTrustFilter(-4) short-circuits trusted session traffic without a + # proxy client IP; this later handshake class proves the observed loopback + # request continued as an untrusted peer. + + +def _assert_gateway_first_party_denial( + compose_args: list[str], timeout_seconds: int +) -> None: + command = [ + "docker", + "compose", + *compose_args, + "exec", + "-T", + "gateway", + "sh", + "-c", + GATEWAY_CONTAINER_PROBE_SCRIPT, + "held-admission-gateway-probe", + str(timeout_seconds), + ] + try: + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + encoding="ascii", + errors="replace", + timeout=timeout_seconds, + ) + except subprocess.TimeoutExpired as exc: + raise QualificationFailure( + "Gateway container loopback handshake timed out within its bounded request time" + ) from exc + except OSError as exc: + raise QualificationFailure("Could not execute the run-owned Gateway container probe") from exc + + if len(result.stdout.encode("utf-8")) > MAX_GATEWAY_PROBE_OUTPUT_BYTES: + raise QualificationFailure("Gateway container probe output exceeded its 4 KiB bound") + lines = result.stdout.splitlines() + if result.returncode != 0: + if lines and lines[0].startswith("SMOKE_GATEWAY_TRUST "): + trust = _parse_probe_record( + lines[0], + "SMOKE_GATEWAY_TRUST", + {"allow", "tls", "cidr0", "extra_indexes"}, + ) + expected_trust = { + "allow": "true", + "tls": "false", + "cidr0": "172.16.0.0/12", + "extra_indexes": "none", + } + if trust != expected_trust: + raise QualificationFailure( + "Gateway runtime trust configuration did not match the local Compose contract: " + f"allow={trust['allow']}, tls={trust['tls']}, cidr0={trust['cidr0']}, " + f"extra_indexes={trust['extra_indexes']}" + ) + raise QualificationFailure( + f"Run-owned Gateway container probe exited with status {result.returncode}" + ) + + trust, probe = parse_gateway_container_probe_output(result.stdout) + validate_gateway_container_first_party_result(trust, probe) + print( + "Observed run-owned Gateway TCP trust inputs: insecure=true, TLS=false, " + "environment CIDR[0]=172.16.0.0/12, higher environment indexes=none." + ) + print( + "Confirmed the run-owned Gateway container's public listener received the first-party " + f"loopback handshake at {probe['remote_ip']} and denied it with " + f"{GATEWAY_HELD_ERROR_CLASS}; this does not prove host-published ingress." + ) + + +def _assert_telnet_denial(host: str, port: int, timeout_seconds: int) -> None: + if not is_localhost_equivalent(host): + raise QualificationFailure("Held-admission plaintext Telnet probe requires localhost") + if not 1 <= port <= 65535: + raise QualificationFailure("Held-admission Telnet port is outside the valid range") + deadline = time.monotonic() + timeout_seconds + response = bytearray() + try: + with socket.create_connection((host, port), timeout=timeout_seconds) as connection: + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise QualificationFailure( + "Telnet held-admission response timed out before the connection closed" + ) + connection.settimeout(remaining) + try: + chunk = connection.recv(4096) + except TimeoutError as exc: + raise QualificationFailure( + "Telnet held-admission response timed out before the connection closed" + ) from exc + if not chunk: + break + response.extend(chunk) + if len(response) > 1024: + raise QualificationFailure("Telnet held-admission response was oversized") + except QualificationFailure: + raise + except OSError as exc: + raise QualificationFailure(f"Telnet held-admission connection failed: {exc}") from exc + validate_telnet_denial(bytes(response), closed=True) + print("Confirmed Telnet startup_unavailable denial and closed connection.") + + +def _positive_env_int(name: str, default: int) -> int: + raw = os.environ.get(name, str(default)) + try: + value = int(raw) + except ValueError as exc: + raise QualificationFailure(f"{name} must be a positive integer") from exc + if value <= 0: + raise QualificationFailure(f"{name} must be a positive integer") + return value + + +def wait_for_compose_state(compose_args: list[str], timeout_seconds: int, poll_seconds: int) -> None: + deadline = time.monotonic() + timeout_seconds + last_output = "" + last_pending = "Compose status has not been read" + command = ["docker", "compose", *compose_args, "ps", "--all", "--format", "json"] + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + try: + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + timeout=remaining, + ) + except subprocess.TimeoutExpired as exc: + raise QualificationFailure( + "Timed out inspecting run-owned Compose status before the health deadline" + ) from exc + except OSError as exc: + raise QualificationFailure(f"Could not inspect run-owned Compose status: {exc}") from exc + if result.returncode != 0: + raise QualificationFailure( + "Could not inspect run-owned Compose status: " + f"{result.stderr.strip() or result.stdout.strip() or 'docker compose ps failed'}" + ) + last_output = result.stdout + state, detail = classify_compose_status(parse_compose_status(result.stdout)) + if state == "ready": + print("Confirmed required Compose services are running in the held-admission state.") + return + last_pending = detail + remaining = deadline - time.monotonic() + if remaining <= 0: + break + time.sleep(min(poll_seconds, remaining)) + raise QualificationFailure( + f"Timed out waiting for the required held-admission Compose state: {last_pending}. " + f"Last Compose status: {last_output.strip() or ''}" + ) + + +def _compose_file_args_are_valid(compose_args: list[str]) -> bool: + if not compose_args or len(compose_args) % 2 != 0: + return False + for index in range(0, len(compose_args), 2): + if compose_args[index] != "-f" or not compose_args[index + 1]: + return False + return True + + +def format_success_message() -> str: + return ( + "Held-admission edge qualification passed. It proves Gateway/Telnet denial only; " + "the direct backend positive proof is separate. Successful public Gateway/Telnet " + "admission remains unproved." + ) + + +def run_qualification(compose_args: list[str]) -> int: + try: + if os.environ.get("FIREMUD_SMOKE_ADMISSION_QUALIFICATION") != "held": + raise QualificationFailure( + "Set FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held to run this qualification" + ) + if not _compose_file_args_are_valid(compose_args): + raise QualificationFailure("Expected the exact run-owned Compose -f file arguments") + + health_timeout = _positive_env_int("SMOKE_HEALTH_TIMEOUT_SECONDS", 240) + poll_interval = _positive_env_int("SMOKE_HEALTH_POLL_INTERVAL_SECONDS", 5) + request_timeout = _positive_env_int("SMOKE_TIMEOUT_SECONDS", 10) + wait_for_compose_state(compose_args, health_timeout, poll_interval) + _assert_readiness_out_of_service( + os.environ.get("SMOKE_GATEWAY_API_BASE", "http://localhost:8080"), + request_timeout, + "Gateway", + "gameplayRouteReadiness", + ) + _assert_gateway_first_party_denial(compose_args, request_timeout) + _assert_readiness_out_of_service( + os.environ.get("SMOKE_TCP_PROXY_API_BASE", "http://localhost:8089"), + request_timeout, + "TCP Proxy", + "trafficAdmissionReadiness", + ) + telnet_host = os.environ.get("SMOKE_TELNET_HOST", "localhost") + telnet_port = _positive_env_int("TCP_PROXY_PORT", 2323) + _assert_telnet_denial(telnet_host, telnet_port, request_timeout) + except QualificationFailure as exc: + print(f"Held-admission qualification failed: {exc}", file=sys.stderr) + return 1 + print(format_success_message()) + return 0 + + +if __name__ == "__main__": + print( + "Held-admission checks must be invoked by the run-owned smoke wrapper.", + file=sys.stderr, + ) + raise SystemExit(2) diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index f333c6567d..0c6f7b45b3 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1014,7 +1014,9 @@ require_contains( require_contains( "design/architecture/system-architecture-cicd.md", [ - "builds pull-request images locally and runs applicable full-stack smoke without a registry-write token", + "builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token", + "This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior", + "it does not establish successful public admission", "publish-pr-runtime-images.yml", "pr-merge-", "never checks out or executes PR source", diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 7341840bd8..624f41e1ef 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -11,7 +11,7 @@ for service_dir in "$ROOT_DIR"/services/*/; do done cp "$ROOT_DIR/dev-tools/validation/"{run-locked-gradle.sh,gradle-run-supervisor.py,inspect-test-results.sh} "$FIXTURE_ROOT/dev-tools/validation/" cp "$ROOT_DIR/dev-tools/"{verify-fresh-bootstrap.sh,ensure-local-compose-env.sh} "$FIXTURE_ROOT/dev-tools/" -cp "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" "$FIXTURE_ROOT/dev-tools/smoke/" +cp "$ROOT_DIR/dev-tools/smoke/"{run-owned-compose.sh,held-admission-qualification.sh} "$FIXTURE_ROOT/dev-tools/smoke/" cp "$ROOT_DIR/.env.sample" "$FIXTURE_ROOT/.env.sample" LOCKED_RUNNER="$FIXTURE_ROOT/dev-tools/validation/run-locked-gradle.sh" INSPECTOR="$FIXTURE_ROOT/dev-tools/validation/inspect-test-results.sh" diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 571f312501..99eaa6e2dc 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -35,6 +35,47 @@ docker() { fi return 0 ;; + "ps --filter") + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true ]]; then + local arguments=" $* " + case "$arguments" in + *"label=com.docker.compose.service=gateway"*) printf 'mock-gateway\n' ;; + *"label=com.docker.compose.service=tcp-proxy-service"*) printf 'mock-tcp-proxy-service\n' ;; + *) + echo "Unexpected smoke service lookup: $*" >&2 + return 90 + ;; + esac + return 0 + fi + command docker "$@" + ;; + "port mock-gateway"|"port mock-tcp-proxy-service") + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true ]]; then + local host_port="" + case "$2 $3" in + "mock-gateway 8080/tcp") + host_port=8080 + [[ "${SMOKE_TEST_MISSING_BINDING:-}" != gateway ]] || host_port=8180 + ;; + "mock-tcp-proxy-service 8080/tcp") + host_port=8089 + [[ "${SMOKE_TEST_MISSING_BINDING:-}" != tcp-management ]] || host_port=8189 + ;; + "mock-tcp-proxy-service 2323/tcp") + host_port=2323 + [[ "${SMOKE_TEST_MISSING_BINDING:-}" != tcp-telnet ]] || host_port=2324 + ;; + *) + echo "Unexpected smoke service port lookup: $*" >&2 + return 90 + ;; + esac + printf '0.0.0.0:%s\n' "$host_port" + return 0 + fi + command docker "$@" + ;; compose\ *) if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true ]]; then local arguments=" $* " @@ -84,6 +125,16 @@ docker() { } export -f docker +python3() { + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true && "${1:-}" == "-" \ + && "${2:-}" == "-f" ]]; then + printf 'MOCK_HELD_ADMISSION_PROBE\n' + return "${SMOKE_TEST_HELD_ADMISSION_STATUS:-0}" + fi + command python3 "$@" +} +export -f python3 + bash() { if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" != true ]]; then command bash "$@" @@ -156,6 +207,12 @@ run_diagnostic_smoke_case() { local probe_status="$3" local logs_fail="$4" local expected_status="$5" + local admission_mode="${7:-baseline}" + local gateway_api_base="${8:-}" + local tcp_proxy_api_base="${9:-}" + local telnet_host="${10:-}" + local telnet_port="${11:-}" + local missing_binding="${12:-}" local run_id="${TEST_RUN_ID}-${suffix}" local actual_status=0 local keep_args=() @@ -172,6 +229,12 @@ run_diagnostic_smoke_case() { SMOKE_IMAGE_TAG=contract-smoke-tag \ SMOKE_COMPOSE_CONFIG_ONLY="$config_only" \ SMOKE_TEST_DIAGNOSTICS_MODE=true \ + FIREMUD_SMOKE_ADMISSION_QUALIFICATION="$admission_mode" \ + SMOKE_GATEWAY_API_BASE="$gateway_api_base" \ + SMOKE_TCP_PROXY_API_BASE="$tcp_proxy_api_base" \ + SMOKE_TELNET_HOST="$telnet_host" \ + TCP_PROXY_PORT="$telnet_port" \ + SMOKE_TEST_MISSING_BINDING="$missing_binding" \ SMOKE_TEST_PROBE_STATUS="$probe_status" \ SMOKE_TEST_LOG_CAPTURE_FAIL="$logs_fail" \ bash "$ROOT_DIR/dev-tools/verify-smoke-images.sh" "${keep_args[@]}" >"$OUT_FILE" 2>"$ERR_FILE" @@ -213,6 +276,81 @@ run_failure_diagnostic_regressions() { cat "$ERR_FILE" >&2 return 1 fi + if ! grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE" || ! grep -Fq 'MOCK_TELNET_PROBE' "$OUT_FILE"; then + echo "baseline image smoke did not preserve both positive transport probes" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + run_diagnostic_smoke_case held-success false 0 false 0 "" held + if ! grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE" || + ! grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE" || + grep -Fq 'MOCK_TELNET_PROBE' "$OUT_FILE" || + ! grep -Fq 'public successful admission remains unproved' "$OUT_FILE"; then + echo "held-admission image smoke did not retain truthful qualification and backend proof" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + SMOKE_TEST_HELD_ADMISSION_STATUS=37 run_diagnostic_smoke_case held-probe-failure false 0 false 37 "" held + if [[ -e "$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-held-probe-failure.resources" ]]; then + echo "held-admission probe failure did not clean up its run-owned Compose project" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + if grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE"; then + echo "held-admission image smoke continued to positive backend proof after a failed edge assertion" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + run_diagnostic_smoke_case held-gateway-override false 0 false 1 "" held http://localhost:8180 + grep -Fq 'requires the canonical localhost:8080 endpoint' "$ERR_FILE" + if grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held-admission Gateway override reached the edge probe" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + run_diagnostic_smoke_case held-tcp-management-override false 0 false 1 "" held "" http://localhost:8189 + grep -Fq 'requires the canonical localhost:8089 endpoint' "$ERR_FILE" + if grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held-admission TCP management override reached the edge probe" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + run_diagnostic_smoke_case held-telnet-host-override false 0 false 1 "" held "" "" 127.0.0.1 + grep -Fq 'requires the canonical localhost:2323 endpoint' "$ERR_FILE" + if grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held-admission Telnet host override reached the edge probe" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + run_diagnostic_smoke_case held-telnet-port-override false 0 false 1 "" held "" "" "" 2324 + grep -Fq 'requires the canonical localhost:2323 endpoint' "$ERR_FILE" + if grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held-admission Telnet port override reached the edge probe" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + for binding in gateway tcp-management tcp-telnet; do + run_diagnostic_smoke_case \ + "held-unbound-$binding" false 0 false 1 "" held "" "" "" "" "$binding" + if ! grep -Fq 'does not publish' "$ERR_FILE" || grep -Fq 'MOCK_HELD_ADMISSION_PROBE' "$OUT_FILE"; then + echo "held-admission proof did not fail its run-owned $binding port attribution" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + done run_diagnostic_smoke_case config-only true 37 false 0 if grep -Fq 'MOCK_LOG service=' "$OUT_FILE" || grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE"; then diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index c6b533f88a..5ba372047b 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -48,6 +48,7 @@ root = Path(sys.argv[1]) sys.path.insert(0, str(root / "dev-tools" / "smoke")) import smoke_common +import held_admission_qualification as held_admission from smoke_common import ( open_telnet_socket, run_telnet_smoke_session, @@ -55,6 +56,293 @@ from smoke_common import ( run_websocket_smoke_session, ) +assert held_admission.format_success_message() == ( + "Held-admission edge qualification passed. It proves Gateway/Telnet denial only; " + "the direct backend positive proof is separate. Successful public Gateway/Telnet " + "admission remains unproved." +) + + +held_services = { + service: { + "Service": service, + "State": "running", + "Health": ( + "unhealthy" + if service in held_admission.HELD_ADMISSION_SERVICES + else "healthy" + ), + } + for service in held_admission.REQUIRED_SERVICES +} +assert held_admission.classify_compose_status(held_services)[0] == "ready" +pending_services = dict(held_services) +pending_services.pop("world-management-service") +assert held_admission.classify_compose_status(pending_services)[0] == "pending" + +assert held_admission.parse_compose_status( + json.dumps(list(held_services.values())) +)["gateway"]["Health"] == "unhealthy" +for invalid_status_output in ("", "not-json", '{"Service":"gateway"}'): + try: + held_admission.parse_compose_status(invalid_status_output) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError( + f"malformed Compose status was accepted: {invalid_status_output!r}" + ) + + +expected_compose_command = [ + "docker", + "compose", + "-f", + "compose.yml", + "ps", + "--all", + "--format", + "json", +] + + +def timeout_compose_status(command, **options): + assert command == expected_compose_command + assert 0 < options["timeout"] <= 10 + raise subprocess.TimeoutExpired(command, options["timeout"]) + + +with patch.object(held_admission.subprocess, "run", side_effect=timeout_compose_status): + try: + held_admission.wait_for_compose_state(["-f", "compose.yml"], 10, 5) + except held_admission.QualificationFailure as exc: + assert "Timed out inspecting run-owned Compose status" in str(exc) + else: + raise AssertionError("a stalled Compose status command did not hit its bounded timeout") + +exited_services = dict(held_services) +exited_services[held_admission.REQUIRED_SERVICES[0]] = { + **exited_services[held_admission.REQUIRED_SERVICES[0]], + "State": "exited", +} + + +def exited_compose_status(command, **options): + assert command == expected_compose_command + return subprocess.CompletedProcess( + command, + 0, + stdout=json.dumps(list(exited_services.values())), + stderr="", + ) + + +with patch.object(held_admission.subprocess, "run", side_effect=exited_compose_status): + try: + held_admission.wait_for_compose_state(["-f", "compose.yml"], 10, 5) + except held_admission.QualificationFailure as exc: + assert f"{held_admission.REQUIRED_SERVICES[0]} is not running: exited" in str(exc) + else: + raise AssertionError("an exited required Compose service was not rejected immediately") + +for service in held_admission.HELD_ADMISSION_SERVICES: + unexpectedly_ready_services = dict(held_services) + unexpectedly_ready_services[service] = { + **held_services[service], + "Health": "healthy", + } + try: + held_admission.classify_compose_status(unexpectedly_ready_services) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError(f"held admission must fail when {service} reports healthy") + +held_admission.validate_out_of_service_response( + 503, + b'{"status":"OUT_OF_SERVICE"}', + "Gateway", + "gameplayRouteReadiness", +) +for status_code, body in ( + (200, b'{"status":"UP"}'), + (503, b""), + (503, b"not-json"), + (503, b'{"status":"DOWN"}'), +): + try: + held_admission.validate_out_of_service_response( + status_code, body, "Gateway", "gameplayRouteReadiness" + ) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError("malformed or unexpected readiness result was accepted") + +held_admission.validate_gateway_first_party_denial( + 403, + {held_admission.GATEWAY_ERROR_CLASS_HEADER: held_admission.GATEWAY_HELD_ERROR_CLASS}, + b"", +) +for status_code, headers, body in ( + (101, {}, b""), + (403, {}, b""), + (403, {held_admission.GATEWAY_ERROR_CLASS_HEADER: "CONNECT_TOKEN_MISSING"}, b""), + ( + 403, + { + held_admission.GATEWAY_ERROR_CLASS_HEADER: + held_admission.GATEWAY_HELD_ERROR_CLASS + }, + b"unexpected", + ), +): + try: + held_admission.validate_gateway_first_party_denial( + status_code, headers, body + ) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError("missing or unexpected Gateway handshake result was accepted") + +gateway_probe_output = ( + "SMOKE_GATEWAY_TRUST allow=true tls=false cidr0=172.16.0.0/12 extra_indexes=none\n" + "SMOKE_GATEWAY_RESULT local_ip=127.0.0.1 remote_ip=127.0.0.1 status=403 " + "class=expected class_count=1 body_bytes=0 curl=ok headers=ok downloaded=0\n" +) +gateway_trust, gateway_probe = held_admission.parse_gateway_container_probe_output( + gateway_probe_output +) +held_admission.validate_gateway_container_first_party_result( + gateway_trust, gateway_probe +) +for invalid_gateway_output in ( + gateway_probe_output.replace("remote_ip=127.0.0.1", "remote_ip=172.16.0.2"), + gateway_probe_output.replace("class=expected", "class=missing"), + gateway_probe_output.replace("status=403", "status=101"), + gateway_probe_output.replace("class_count=1", "class_count=2"), + gateway_probe_output.replace("body_bytes=0", "body_bytes=1"), + gateway_probe_output.replace("extra_indexes=none", "extra_indexes=present"), + gateway_probe_output.replace("tls=false", "tls=unexpected"), + gateway_probe_output.replace("downloaded=0", "downloaded=1"), + gateway_probe_output.splitlines()[0] + "\n", + "SMOKE_GATEWAY_TRUST allow=true allow=true tls=false cidr0=172.16.0.0/12 extra_indexes=none\n" + + gateway_probe_output.splitlines()[1] + + "\n", + gateway_probe_output + "x" * held_admission.MAX_GATEWAY_PROBE_OUTPUT_BYTES, +): + try: + parsed_trust, parsed_probe = held_admission.parse_gateway_container_probe_output( + invalid_gateway_output + ) + held_admission.validate_gateway_container_first_party_result( + parsed_trust, parsed_probe + ) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError("unexpected Gateway container peer or response evidence was accepted") + + +def successful_gateway_container_probe(command, **options): + assert command[:9] == [ + "docker", + "compose", + "-f", + "compose.yml", + "exec", + "-T", + "gateway", + "sh", + "-c", + ] + assert command[-2:] == ["held-admission-gateway-probe", "5"] + probe_script = command[9] + assert "http://127.0.0.1:8080/ws/game" in probe_script + assert "--noproxy '*'" in probe_script + assert "--max-time \"$timeout_seconds\"" in probe_script + assert "X-Proxy-Client-IP" not in probe_script + assert "remote_ip" in probe_script and "local_ip" in probe_script + assert options["timeout"] == 5 + assert options["capture_output"] and options["text"] + return subprocess.CompletedProcess(command, 0, stdout=gateway_probe_output, stderr="") + + +with patch.object(held_admission.subprocess, "run", side_effect=successful_gateway_container_probe): + with contextlib.redirect_stdout(io.StringIO()) as gateway_probe_log: + held_admission._assert_gateway_first_party_denial(["-f", "compose.yml"], 5) + assert "does not prove host-published ingress" in gateway_probe_log.getvalue() + +trust_mismatch = subprocess.CompletedProcess( + ["docker", "compose"], + 21, + stdout=( + "SMOKE_GATEWAY_TRUST allow=true tls=false cidr0=unexpected extra_indexes=none\n" + ), + stderr="", +) +with patch.object(held_admission.subprocess, "run", return_value=trust_mismatch): + try: + held_admission._assert_gateway_first_party_denial(["-f", "compose.yml"], 5) + except held_admission.QualificationFailure as exc: + assert "trust configuration did not match" in str(exc) + assert "cidr0=unexpected" in str(exc) + else: + raise AssertionError("unexpected Gateway TCP trust inputs were accepted") + +with patch.object( + held_admission.subprocess, + "run", + side_effect=subprocess.TimeoutExpired(["docker", "compose"], 5), +): + try: + held_admission._assert_gateway_first_party_denial(["-f", "compose.yml"], 5) + except held_admission.QualificationFailure as exc: + assert "loopback handshake timed out" in str(exc) + else: + raise AssertionError("a stalled Gateway container probe did not hit its bounded timeout") + +held_admission.validate_telnet_denial( + held_admission.TELNET_HELD_DENIAL.encode("ascii"), closed=True +) +for response, closed in ( + (b"", True), + (b"", False), + (b"DISCONNECT other reason\n", True), +): + try: + held_admission.validate_telnet_denial(response, closed) + except held_admission.QualificationFailure: + pass + else: + raise AssertionError("missing, silent, or unexpected Telnet result was accepted") + +silent_listener = socket.socket() +silent_listener.bind(("127.0.0.1", 0)) +silent_listener.listen(1) +silent_port = silent_listener.getsockname()[1] + + +def hold_telnet_connection_silent(): + peer, _ = silent_listener.accept() + with peer: + time.sleep(0.2) + + +silent_peer = threading.Thread(target=hold_telnet_connection_silent, daemon=True) +silent_peer.start() +try: + held_admission._assert_telnet_denial("127.0.0.1", silent_port, 0.05) +except held_admission.QualificationFailure as exc: + assert "timed out" in str(exc) +else: + raise AssertionError("a silent Telnet connection did not fail on its bounded timeout") +finally: + silent_listener.close() + silent_peer.join(timeout=1) +assert not silent_peer.is_alive() + for local_host in ( "localhost", @@ -1291,6 +1579,13 @@ assert_command_rejects() { fi } +assert_command_rejects \ + "must be invoked by sourcing it from the run-owned smoke wrapper" \ + bash "$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" +assert_command_rejects \ + "must be invoked by the run-owned smoke wrapper" \ + python3 "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" + for script in \ "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" \ "$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh"; do @@ -1402,6 +1697,23 @@ for script in "$ROOT_DIR/dev-tools/verify-fresh-bootstrap.sh" "$ROOT_DIR/dev-too done done +# shellcheck disable=SC2016 # Assert literal shell source rather than expanded values. +for script in "$ROOT_DIR/dev-tools/verify-fresh-bootstrap.sh" "$ROOT_DIR/dev-tools/verify-smoke-images.sh"; do + grep -Fq 'FIREMUD_SMOKE_ADMISSION_QUALIFICATION="${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}"' "$script" + grep -Fq 'baseline|held)' "$script" + grep -Fq 'source "$HELD_ADMISSION_QUALIFICATION_SCRIPT"' "$script" + grep -Fq 'run_held_admission_qualification "${COMPOSE_FILES[@]}"' "$script" + grep -Fq 'bash "$WS_SMOKE_SCRIPT"' "$script" + grep -Fq 'public successful admission remains unproved' "$script" +done +grep -Fq 'FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held' "$ROOT_DIR/.github/workflows/runtime-images.yml" +grep -Fq 'does not prove host-published ingress' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" +grep -Fq 'docker' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" +grep -Fq 'Confirmed Telnet startup_unavailable denial and closed connection.' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" +grep -Fq 'require_run_owned_compose_service gateway 8080 8080' "$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" +grep -Fq 'require_run_owned_compose_service tcp-proxy-service 8080 8089' "$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" +grep -Fq 'require_run_owned_compose_service tcp-proxy-service 2323 2323' "$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" + restart_script="$ROOT_DIR/dev-tools/verify-restart-state.sh" grep -q 'run-owned-compose.sh' "$restart_script" restart_helper_source_line="$(grep -n 'run-owned-compose.sh' "$restart_script" | head -1 | cut -d: -f1)" diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 493f667272..9f4cde2b14 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -10,11 +10,14 @@ COMPOSE_FILES=( TCP_SMOKE_SCRIPT="$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh" WS_SMOKE_SCRIPT="$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" HEALTH_SCRIPT="$ROOT_DIR/dev-tools/verify-compose-health.sh" +HELD_ADMISSION_QUALIFICATION_SCRIPT="$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" BUILD_JARS_SCRIPT="$ROOT_DIR/dev-tools/build-compose-service-jars.sh" ENSURE_CERTS_SCRIPT="$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" ENSURE_ENV_SCRIPT="$ROOT_DIR/dev-tools/ensure-local-compose-env.sh" # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" +# shellcheck source=dev-tools/smoke/held-admission-qualification.sh +source "$HELD_ADMISSION_QUALIFICATION_SCRIPT" export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json unset FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH @@ -43,6 +46,17 @@ case "$SMOKE_MUTATION_EXTENSION" in ;; esac +FIREMUD_SMOKE_ADMISSION_QUALIFICATION="${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" +case "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" in + baseline|held) + export FIREMUD_SMOKE_ADMISSION_QUALIFICATION + ;; + *) + echo "FIREMUD_SMOKE_ADMISSION_QUALIFICATION must be baseline or held; refusing to run." >&2 + exit 1 + ;; +esac + initialize_run_owned_compose_proof "$@" install_run_owned_compose_proof_traps @@ -88,7 +102,11 @@ if [[ -n "$FIREMUD_SMOKE_NO_CACHE_SERVICES" ]]; then done fi -echo "Fresh bootstrap proof: destroy this run-owned compose project's containers, networks, and named volumes, then rebuild and run WebSocket/Telnet LOGIN -> PLAY -> LOOK baseline proofs." +if [[ "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" == "baseline" ]]; then + echo "Fresh bootstrap proof: destroy this run-owned compose project's containers, networks, and named volumes, then rebuild and run WebSocket/Telnet LOGIN -> PLAY -> LOOK baseline proofs." +else + echo "Fresh bootstrap proof: destroy this run-owned compose project's containers, networks, and named volumes, then rebuild and run held-admission edge checks plus the isolated backend LOGIN -> PLAY -> LOOK proof." +fi echo "Destroyed named volumes: postgres-data, redis-coord-data, minio-data" if [[ -n "$FIREMUD_SMOKE_NO_CACHE_SERVICES" ]]; then echo "Forcing no-cache compose rebuild for: ${FIREMUD_SMOKE_NO_CACHE_SERVICES//,/ }" @@ -130,8 +148,17 @@ else fi docker compose "${COMPOSE_FILES[@]}" up -d --remove-orphans -bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" -# Both transport legs are baseline-only; mutation parity requires independent -# transport identities/state and is rejected by this wrapper above. -bash "$WS_SMOKE_SCRIPT" -bash "$TCP_SMOKE_SCRIPT" +if [[ "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" == "baseline" ]]; then + bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" + # Both transport legs are baseline-only; mutation parity requires independent + # transport identities/state and is rejected by this wrapper above. + bash "$WS_SMOKE_SCRIPT" + bash "$TCP_SMOKE_SCRIPT" +else + echo "Smoke admission qualification: held (direct backend LOGIN -> PLAY -> LOOK plus Gateway/Telnet fail-closed proof)." + run_held_admission_qualification "${COMPOSE_FILES[@]}" + # This is the existing isolated backend positive proof. Public successful + # admission remains a separate runtime obligation. + bash "$WS_SMOKE_SCRIPT" + echo "Held-admission smoke qualification passed; public successful admission remains unproved." +fi diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index c94a83c779..4f03e02b15 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -16,6 +16,7 @@ COMPOSE_CONFIG_FILE="" TCP_SMOKE_SCRIPT="$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh" WS_SMOKE_SCRIPT="$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" HEALTH_CHECK_SCRIPT="$ROOT_DIR/dev-tools/verify-compose-health.sh" +HELD_ADMISSION_QUALIFICATION_SCRIPT="$ROOT_DIR/dev-tools/smoke/held-admission-qualification.sh" ENSURE_CERTS_SCRIPT="$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" COMPOSE_UP_ARGS=(up -d --remove-orphans) SMOKE_COMPOSE_UP_ATTEMPTS="${SMOKE_COMPOSE_UP_ATTEMPTS:-3}" @@ -23,6 +24,8 @@ SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS="${SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS:-5} COMPOSE_START_ATTEMPTED=false # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" +# shellcheck source=dev-tools/smoke/held-admission-qualification.sh +source "$HELD_ADMISSION_QUALIFICATION_SCRIPT" export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json unset FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH @@ -83,6 +86,17 @@ case "$SMOKE_MINIO_LOCAL_ONLY" in ;; esac +FIREMUD_SMOKE_ADMISSION_QUALIFICATION="${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" +case "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" in + baseline|held) + export FIREMUD_SMOKE_ADMISSION_QUALIFICATION + ;; + *) + echo "FIREMUD_SMOKE_ADMISSION_QUALIFICATION must be baseline or held; refusing to run." >&2 + exit 1 + ;; +esac + # The proof's mTLS profile must be last so it supersedes the ordinary local # plaintext override and all image/MinIO-specific overlays. COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" ) @@ -262,12 +276,30 @@ fi if [[ "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" == "true" ]]; then exit 0 fi + +case "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" in + baseline) + echo "Smoke admission qualification: baseline (both transports must complete LOGIN -> PLAY -> LOOK)." + ;; + held) + echo "Smoke admission qualification: held (direct backend LOGIN -> PLAY -> LOOK plus Gateway/Telnet fail-closed proof)." + ;; +esac + docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans COMPOSE_START_ATTEMPTED=true compose_up_with_retry -bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" -# Both transport legs are baseline-only; mutation parity requires independent -# transport identities/state and is rejected by this wrapper above. -bash "$WS_SMOKE_SCRIPT" -bash "$TCP_SMOKE_SCRIPT" +if [[ "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" == "baseline" ]]; then + bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" + # Both transport legs are baseline-only; mutation parity requires independent + # transport identities/state and is rejected by this wrapper above. + bash "$WS_SMOKE_SCRIPT" + bash "$TCP_SMOKE_SCRIPT" +else + run_held_admission_qualification "${COMPOSE_FILES[@]}" + # This is the existing isolated backend positive proof. Public successful + # admission remains a separate runtime obligation. + bash "$WS_SMOKE_SCRIPT" + echo "Held-admission smoke qualification passed; public successful admission remains unproved." +fi diff --git a/docker/README.md b/docker/README.md index 66f5b53bca..c6efc1b29b 100644 --- a/docker/README.md +++ b/docker/README.md @@ -47,7 +47,7 @@ export FIREMUD_SMOKE_OWNERSHIP_TOKEN="$(openssl rand -hex 32)" ``` -These entrypoints run the read-only `LOGIN` -> `PLAY` -> `LOOK` baseline over both transports. The fresh-bootstrap and restart-state chain below intentionally reuses the same explicit run ID/project and ownership token; image smoke uses a separate run ID/project and a fresh token. By default each wrapper performs authenticated teardown before returning, including on proof failure or a handled signal. `--keep-running` explicitly retains the stack and claim for authenticated manual inspection/direct teardown; the caller must retain the original token and perform final owner-guarded teardown. Restart preserves volumes during its proof, while its default final cleanup disposes the run-owned deployment. Successful probes with failed or ambiguous cleanup are an overall failure; an earlier failed-proof status remains the primary exit status. A retained live project prevents admission to a new expensive proof session, even with its original capability; continuation proofs must stay within the original owning resource session. Do not use keep mode to park completed automated stacks. +By default these entrypoints run the read-only `LOGIN` -> `PLAY` -> `LOOK` baseline over both transports. The fresh-bootstrap and restart-state chain below intentionally reuses the same explicit run ID/project and ownership token; image smoke uses a separate run ID/project and a fresh token. By default each wrapper performs authenticated teardown before returning, including on proof failure or a handled signal. `--keep-running` explicitly retains the stack and claim for authenticated manual inspection/direct teardown; the caller must retain the original token and perform final owner-guarded teardown. Restart preserves volumes during its proof, while its default final cleanup disposes the run-owned deployment. Successful probes with failed or ambiguous cleanup are an overall failure; an earlier failed-proof status remains the primary exit status. A retained live project prevents admission to a new expensive proof session, even with its original capability; continuation proofs must stay within the original owning resource session. Do not use keep mode to park completed automated stacks. The owner-guarded `stop_run_owned_compose_project` helper in [`run-owned-compose.sh`](../dev-tools/smoke/run-owned-compose.sh) is the cleanup path. It requires the original run ID, Compose project name, and capability, plus the same Compose files (including the smoke-image override and matching tag for image smoke). It performs the guarded `down -v` and releases the marker only after project resources are absent. Do not remove the marker manually. The helper stores only a capability digest in its private marker; local runs derive that digest from the ownership token. @@ -95,7 +95,7 @@ The 40-hex value shown above is a placeholder, not a usable image tag. Obtain a The PR Full-Stack Smoke job also sets `SMOKE_MINIO_LOCAL_ONLY=true` after building the pinned MinIO server and client sources. It passes unique local image tags and the build-reported `sha256:` IDs to `dev-tools/verify-smoke-images.sh`; the wrapper verifies the tags still resolve to those IDs and that the optional PR Compose overlay renders those tags with `pull_policy: never`. Leave this option unset for ordinary published smoke so the canonical Compose files continue to own dependency image selection. -Do not request mutating parity through these entrypoints; the wrappers reject `SMOKE_MUTATION_EXTENSION=true` until independent transport state exists. Do not treat `docker/docker-compose.smoke-images.override.yml` as a standalone ad hoc compose file. Its contract is to be driven through the explicit ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries), with `SMOKE_IMAGE_TAG=` passed to `dev-tools/verify-smoke-images.sh`; the script writes the required local env override and runs the baseline smoke flow. +Do not request mutating parity through these entrypoints; the wrappers reject `SMOKE_MUTATION_EXTENSION=true` until independent transport state exists. Do not treat `docker/docker-compose.smoke-images.override.yml` as a standalone ad hoc compose file. Its contract is to be driven through the explicit ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries), with `SMOKE_IMAGE_TAG=` passed to `dev-tools/verify-smoke-images.sh`; the script writes the required local env override and runs the baseline smoke flow by default. For the currently held first-party admission path, explicitly set `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held`; it checks public readiness and published-port ownership, sends the classified Gateway handshake from inside the run-owned Gateway container to its loopback listener, checks real Telnet denial, and then runs the existing direct backend positive proof. The loopback handshake does not prove host-published Gateway ingress or successful public admission; both limits and the exact qualification contract are documented in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). Fresh-bootstrap and image smoke intentionally use guarded `down -v` teardown for their claimed Compose project, deleting that project's `postgres-data`, `redis-coord-data`, and `minio-data` volumes. Restart-state preserves named volumes during restart; its default final proof cleanup disposes them, while explicit `--keep-running` retains them. `devDown` preserves named volumes. This disposes a test deployment; it is not authority to reset Coordination Redis. Follow the owning [Redis reset and recovery](../design/architecture/system-architecture-redis-reset-and-recovery.md) contract for reset questions. diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index cdc67734bc..3098cc46a8 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -11,7 +11,6 @@ x-service-environment: &service-env FIREMUD_POSTGRES_USER: ${FIREMUD_POSTGRES_USER} FIREMUD_POSTGRES_PASSWORD: ${FIREMUD_POSTGRES_PASSWORD} FIREMUD_AUTH_JWT_SECRET: ${FIREMUD_AUTH_JWT_SECRET} - FIREMUD_GATEWAY_CONNECT_CONTEXT_JWT_SECRET: ${FIREMUD_GATEWAY_CONNECT_CONTEXT_JWT_SECRET} FIREMUD_REDIS_HOST: ${FIREMUD_REDIS_HOST} FIREMUD_REDIS_PORT: ${FIREMUD_REDIS_PORT} FIREMUD_REDIS_COORD_HOST: ${FIREMUD_REDIS_COORD_HOST} diff --git a/services/account-service/README.md b/services/account-service/README.md index 49e843a6cd..7409f99d2f 100644 --- a/services/account-service/README.md +++ b/services/account-service/README.md @@ -3,4 +3,8 @@ The complete design for this service is documented in the central repository: [📄 Account Service Design](../../design/architecture/microservices/account-service/README.md) -This README is only a stub linking to that document. **Do not add design details here.** +This README links to the service's canonical design. **Do not duplicate design details here.** + +## Current gameplay connect-token availability + +`/auth/connect-token` validates the authenticated bootstrap and connect scope, then returns `AUTH_UNAVAILABLE` before reading cached success, minting a token, or mutating replay/session state. The canonical gameplay connect-context producer is not qualified. See [Account Runtime and Data](../../design/architecture/microservices/account-service/runtime-and-data.md#implementation-status) and the [Player Access and Session tracker](../../design/project-management/implementation-tracking/player-access-and-session.md#canonical-first-party-receiving-preparation) for current implementation status and proof limits. 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 a8c697754b..4d4f6d2ba6 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 @@ -1163,179 +1163,8 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); ConnectScopeContext scopeContext = requireConnectScopeContext(request.connectScopeId()); validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); - Optional< - net.firedevops.firemud.accountservice.service.session.SessionService.ConnectTokenReplay> - cachedReplay = - sessionService.getConnectTokenReplay( - scopeContext.tenantId(), - bootstrapContext.accountId(), - request.connectScopeId(), - request.requestId()); - if (cachedReplay.isPresent()) { - var replay = cachedReplay.orElseThrow(); - if (replay.success()) { - logger.info( - "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.worldSlug(), - scopeContext.realmSlug(), - request.requestId()); - return replayedConnectTokenResult(replay.result()); - } - logger.info( - "Replayed failed connect-token attempt for account {} tenant {} world {} realm {} requestId {} code {}", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.worldSlug(), - scopeContext.realmSlug(), - request.requestId(), - replay.errorCode()); - throw new AuthenticationException(replay.errorCode(), replay.errorMessage()); - } - try { - return issueConnectTokenFresh(bootstrapContext, scopeContext, request); - } catch (AuthenticationException ex) { - if (!"AUTH_UNAVAILABLE".equals(ex.getCode()) - && !"ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { - sessionService.storeConnectTokenReplay( - scopeContext.tenantId(), - bootstrapContext.accountId(), - request.connectScopeId(), - request.requestId(), - new net.firedevops.firemud.accountservice.service.session.SessionService - .ConnectTokenReplay(false, null, ex.getCode(), ex.getMessage()), - remainingConnectScopeReplayTtl(scopeContext)); - } - throw ex; - } - } - - private ConnectTokenResult issueConnectTokenFresh( - BootstrapContext bootstrapContext, - ConnectScopeContext scopeContext, - ConnectTokenRequest request) { - RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - RuntimeMembershipDto membership = - getTenantMembershipForRuntime( - bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - - if (membership.membershipExists() - && !"ACTIVE".equals(membership.membershipLifecycleState()) - && !"INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); - } - if (membership.membershipExists() - && "INACTIVE".equals(membership.membershipLifecycleState()) - && isPublicProductionRealm(realm)) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - - if (!membership.membershipExists()) { - if (!isPublicProductionRealm(realm)) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - - String jti = - stableId( - "gameplay-connect", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.gameInstanceId(), - scopeContext.realmSlug(), - request.requestId()); - long issuedAt = System.currentTimeMillis(); - long expiresAt = issuedAt + tokenProperties.getConnectTokenExpirationMs(); - String connectToken = - mintToken( - String.valueOf(bootstrapContext.accountId()), - tokenProperties.getConnectTokenExpirationMs(), - Map.of( - "aud", - "gameplay-connect", - "accountId", - bootstrapContext.accountId(), - "tenantId", - scopeContext.tenantId(), - "gameInstanceId", - scopeContext.gameInstanceId(), - "pointerVersion", - scopeContext.pointerVersion(), - "realmSlug", - scopeContext.realmSlug(), - "worldSlug", - scopeContext.worldSlug(), - "connectScopeId", - request.connectScopeId(), - "requestId", - request.requestId(), - "jti", - jti)); - sessionService.storeSession( - scopeContext.tenantId(), - bootstrapContext.accountId(), - connectToken, - tokenProperties.getConnectTokenExpirationMs()); - ConnectTokenResult result = - new ConnectTokenResult( - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.gameInstanceId(), - scopeContext.realmSlug(), - request.connectScopeId(), - connectToken, - jti, - request.requestId(), - Instant.ofEpochMilli(issuedAt).toString(), - Instant.ofEpochMilli(expiresAt).toString(), - false); - sessionService.storeConnectTokenReplay( - scopeContext.tenantId(), - bootstrapContext.accountId(), - request.connectScopeId(), - request.requestId(), - new net.firedevops.firemud.accountservice.service.session.SessionService.ConnectTokenReplay( - true, result, "", ""), - Math.min( - tokenProperties.getConnectTokenExpirationMs(), - remainingConnectScopeReplayTtl(scopeContext))); - logger.info( - "Issued connect token for account {} tenant {} world {} realm {} gameInstance {} requestId {} jti {}", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.worldSlug(), - scopeContext.realmSlug(), - scopeContext.gameInstanceId(), - request.requestId(), - jti); - return result; + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable"); } @Override @@ -1475,27 +1304,6 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { } } - private RuntimeRealmTarget requireAdmissibleRealm( - BootstrapContext bootstrapContext, - Long expectedTenantId, - String worldSlug, - String realmSlug) { - RuntimeRealmTarget realm = requireRealmTarget(expectedTenantId, worldSlug, realmSlug); - 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"); - } - return realm; - } - private RuntimeRealmTarget requireRealmTarget( Long expectedTenantId, String worldSlug, String realmSlug) { try { @@ -1948,12 +1756,6 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( return currentRealm; } - private long remainingConnectScopeReplayTtl(ConnectScopeContext scopeContext) { - long remainingMs = - scopeContext.connectScopeExpiresAt().toEpochMilli() - System.currentTimeMillis(); - return Math.max(1L, remainingMs); - } - private Optional findAccountForAuthentication(String usernameOrEmail) { Optional emailMatch = accountRepository.findByEmail(EmailCanonicalization.normalize(usernameOrEmail)); @@ -3361,21 +3163,6 @@ private record JoinAuditPayload( long membershipVersion, String requestId) {} - private ConnectTokenResult replayedConnectTokenResult(ConnectTokenResult result) { - return new ConnectTokenResult( - result.accountId(), - result.tenantId(), - result.gameInstanceId(), - result.realmSlug(), - result.connectScopeId(), - result.connectToken(), - result.jti(), - result.requestId(), - result.issuedAt(), - result.expiresAt(), - true); - } - private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { return buildRuntimeRealmTarget( 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 316a813e0e..7a50923772 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 @@ -257,6 +257,27 @@ void listBootstrapCharactersReturnsCharacters() throws Exception { .andExpect(jsonPath("$.data[0].characterName").value("Mara")); } + @Test + void connectTokenReportsUnavailableWithoutSettingCookie() throws Exception { + ConnectTokenRequest request = new ConnectTokenRequest("scope-1", "req-unavailable"); + when(accountService.issueConnectToken( + "boot123", new ConnectTokenRequest("scope-1", "req-unavailable"))) + .thenThrow( + new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable")); + + mockMvc + .perform( + post("/auth/connect-token") + .header(HttpHeaders.AUTHORIZATION, "Bearer boot123") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect(jsonPath("$.error.code").value("AUTH_UNAVAILABLE")) + .andExpect(header().doesNotExist(HttpHeaders.SET_COOKIE)); + } + @Test void listBootstrapCharactersRejectsMissingConnectScopeIdBeforeDispatch() throws Exception { mockMvc 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 4928bef0b8..76154b0392 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 @@ -215,12 +215,6 @@ void setup() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); - when(sessionService.getConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString())) - .thenReturn(Optional.empty()); when(mailProperties.getResetUrl()).thenReturn("http://reset/%s"); when(mailProperties.getVerificationUrl()).thenReturn("http://verify/%s"); service = @@ -527,10 +521,22 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { 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")); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); + AuthenticationException connectTokenUnavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join"))); assertTrue(first.success()); assertEquals("JOINED", first.outcomeCode()); @@ -541,7 +547,8 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { assertTrue(readbackReplay.success()); assertTrue(readbackReplay.replayed()); assertEquals(committedOperation, retainedOperation.get()); - assertNotNull(onboardingToken.connectToken()); + assertEquals("AUTH_UNAVAILABLE", connectTokenUnavailable.getCode()); + assertNoLegacyConnectTokenEffects(); assertEquals(REALM_ID, retainedScope.get().realmId().toString()); assertEquals( first, @@ -554,8 +561,6 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { 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), @@ -575,8 +580,6 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { 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), @@ -3161,56 +3164,65 @@ void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { } @Test - void issueConnectTokenReturnsShortLivedConnectToken() { - 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)); + void issueConnectTokenFailsClosedBeforeLegacyIssuanceOrReplayState() { + ConnectScopeFixture fixture = prepareConnectScopeForIssue(); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + fixture.bootstrapToken(), + new ConnectTokenRequest(fixture.connectScopeId(), "req-unavailable"))); - ConnectTokenResult result = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-3")); - - assertEquals(11L, result.accountId()); - assertEquals(7L, result.tenantId()); - assertEquals(44L, result.gameInstanceId()); - assertEquals(connectScopeId, result.connectScopeId()); - assertNotNull(result.connectToken()); - assertNotNull(result.jti()); - assertEquals("req-3", result.requestId()); - assertNotNull(result.issuedAt()); - assertNotNull(result.expiresAt()); - assertTrue(!result.replayed()); - var connectTokenClaims = - new JwtUtil("mysecretkey123456789012345678901", 30000L) - .parseToken(result.connectToken()) - .getPayload(); - assertEquals("gameplay-connect", connectTokenClaims.getAudience().iterator().next()); - assertEquals(17L, ((Number) connectTokenClaims.get("pointerVersion")).longValue()); - org.mockito.Mockito.verify(sessionService) - .storeSession( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq(30000L)); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertNoLegacyConnectTokenEffects(); } @Test - void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFailure() { + void issueConnectTokenDoesNotReturnCachedLegacySuccess() { + ConnectScopeFixture fixture = prepareConnectScopeForIssue(); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); + ConnectTokenResult cachedLegacySuccess = + new ConnectTokenResult( + 11L, + 7L, + 44L, + "production", + fixture.connectScopeId(), + "legacy-hmac-connect-token", + "legacy-jti", + "req-cached-success", + "2026-10-14T00:00:00Z", + "2026-10-14T00:00:30Z", + false); + when(sessionService.getConnectTokenReplay( + 7L, 11L, fixture.connectScopeId(), "req-cached-success")) + .thenReturn( + Optional.of(new SessionService.ConnectTokenReplay(true, cachedLegacySuccess, "", ""))); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + fixture.bootstrapToken(), + new ConnectTokenRequest(fixture.connectScopeId(), "req-cached-success"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertNoLegacyConnectTokenEffects(); + } + + private ConnectScopeFixture prepareConnectScopeForIssue() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3223,48 +3235,50 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail active.setId(22L); active.setTenantId(7L); active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(active), java.util.List.of(), java.util.List.of(active)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-entitlement-retry"); + return new ConnectScopeFixture(bootstrap.bootstrapToken(), connectScopeId); + } - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + private void assertNoLegacyConnectTokenEffects() { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) .storeConnectTokenReplay( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq("req-entitlement-retry"), - org.mockito.ArgumentMatchers.argThat( - replay -> - !replay.success() && "ENTITLEMENT_UNAVAILABLE".equals(replay.errorCode())), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), org.mockito.ArgumentMatchers.anyLong()); - - ConnectTokenResult retried = service.issueConnectToken(bootstrap.bootstrapToken(), request); - - assertEquals("req-entitlement-retry", retried.requestId()); - assertNotNull(retried.connectToken()); - assertFalse(retried.replayed()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(1)) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), - org.mockito.ArgumentMatchers.eq("req-entitlement-retry"), - org.mockito.ArgumentMatchers.argThat(replay -> replay.success()), + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(accountTenantMembershipRepository); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) + .getAdmissionPointer( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantId(org.mockito.ArgumentMatchers.anyLong()); } + private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) {} + @Test - void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { + void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3278,55 +3292,51 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { active.setTenantId(7L); active.setStatus("active"); when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + net.firedevops.firemud.entitymanagement.v1.Character character = + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("char-1") + .setName("Mara") + .setLevel(12) + .build(); + when(entityManagementClient.listCharactersByAccount( + 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(java.util.List.of(character)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("99") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-4"))); + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - // The catalog and pointer disagree before Account has a valid current pair to compare. - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); - assertEquals( - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - ex.getMessage()); + assertEquals(1, characters.size()); + assertEquals("char-1", characters.getFirst().characterId()); + assertEquals("Mara", characters.getFirst().characterName()); + assertEquals("SHARED", characters.getFirst().stateScope()); + assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); } - @Test - void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { + @ParameterizedTest + @CsvSource({"false", "true"}) + void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( + boolean membershipExists) { 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))); + if (membershipExists) { + AccountTenantMembership membership = membership(account, 7L); + membership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership)); + } else { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + } Subscription active = new Subscription(); active.setId(22L); active.setTenantId(7L); @@ -3337,663 +3347,73 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("sandbox") - .setWorldDisplayName("Builder Sandbox") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - AuthenticationException ex = + AuthenticationException exception = assertThrows( AuthenticationException.class, () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-world-mismatch"))); + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); + if (membershipExists) { + assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); + assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); + } else { + assertEquals("JOIN_REQUIRED", exception.getCode()); + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); } @Test - void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { + void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { 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)); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository, subscriptionRepository); - - Subscription canceled = new Subscription(); - canceled.setId(23L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); AuthenticationException exception = assertThrows( AuthenticationException.class, () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-routing-first"))); + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .findByAccountIdAndTenantId(11L, 7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantId(7L); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); + order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); + order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyNoInteractions(entityManagementClient); } - @Test - void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { + @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)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - ConnectTokenResult firstResult = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); - - when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) - .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("99") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); - - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); - } - - @Test - void issueConnectTokenRequiresExplicitPublicProductionMembership() { - 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.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-join-2"))); - - assertEquals("JOIN_REQUIRED", exception.getCode()); - assertEquals( - "Join the selected world before requesting a connect token", exception.getMessage()); - org.mockito.Mockito.verify(sessionService) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), - org.mockito.ArgumentMatchers.eq("req-join-2"), - org.mockito.ArgumentMatchers.argThat( - replay -> - !replay.success() - && "JOIN_REQUIRED".equals(replay.errorCode()) - && exception.getMessage().equals(replay.errorMessage())), - org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - } - - @Test - void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { - 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.empty()); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - 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-join-disabled"))); - - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); - 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(); - 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.empty()); - Subscription active = new Subscription(); - active.setId(21L); - active.setTenantId(7L); - active.setStatus("active"); - Subscription canceled = new Subscription(); - canceled.setId(22L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(active), java.util.List.of(canceled)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-gameplay-disabled"); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - - assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); - assertEquals("Gameplay is not available for this tenant", exception.getMessage()); - org.mockito.Mockito.verify(sessionService) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), - org.mockito.ArgumentMatchers.eq("req-gameplay-disabled"), - org.mockito.ArgumentMatchers.argThat( - replay -> !replay.success() && "TENANT_BILLING_BLOCKED".equals(replay.errorCode())), - org.mockito.ArgumentMatchers.anyLong()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - - when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-gameplay-disabled")) - .thenReturn( - Optional.of( - new SessionService.ConnectTokenReplay( - false, null, "TENANT_BILLING_BLOCKED", exception.getMessage()))); - AuthenticationException replayed = - assertThrows( - AuthenticationException.class, - () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - - assertEquals("TENANT_BILLING_BLOCKED", replayed.getCode()); - assertEquals(exception.getMessage(), replayed.getMessage()); - } - - @ParameterizedTest - @CsvSource({"true,production", "false,preview"}) - void issueConnectTokenRejectsPresentNonAdmittingMembership( - boolean publicProductionRealm, String realmSlug) { - 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 deniedMembership = membership(account, 7L); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(deniedMembership)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug(realmSlug) - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(true) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", realmSlug)) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug(realmSlug) - .setRealmDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(true) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", realmSlug)) - .thenReturn(true); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - deniedMembership.setGameplayAdmissionAllowed(false); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-membership-denied"))); - - assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); - assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - } - - @Test - void issueConnectTokenReplaysSameFailureForSameRequestId() { - Account account = new Account(); - account.setId(11L); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("99") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - AuthenticationException firstFailure = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - // 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, "ADMISSION_POINTER_UNAVAILABLE", firstFailure.getMessage()))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - AuthenticationException replayedFailure = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", replayedFailure.getCode()); - assertEquals(firstFailure.getMessage(), replayedFailure.getMessage()); - assertEquals( - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - replayedFailure.getMessage()); - } - - @Test - void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { - 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)); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-1") - .setName("Mara") - .setLevel(12) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertEquals(1, characters.size()); - assertEquals("char-1", characters.getFirst().characterId()); - assertEquals("Mara", characters.getFirst().characterName()); - assertEquals("SHARED", characters.getFirst().stateScope()); - assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); - } - - @ParameterizedTest - @CsvSource({"false", "true"}) - void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( - boolean membershipExists) { - 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)); - if (membershipExists) { - AccountTenantMembership membership = membership(account, 7L); - membership.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership)); - } else { - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - } - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - - if (membershipExists) { - assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); - assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); - } else { - assertEquals("JOIN_REQUIRED", exception.getCode()); - assertEquals("Join the selected world before discovering characters", exception.getMessage()); - } - verifyNoInteractions(entityManagementClient); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - } - - @Test - void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { - 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)); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - - 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("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); - org.mockito.InOrder order = - org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); - order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); - order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); - 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); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.of(inactiveMembership)); Subscription subscription = new Subscription(); @@ -5309,103 +4729,6 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( assertFalse(realms.getFirst().connectScopeId().isBlank()); } - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( - boolean visible, boolean publicProductionRealm) { - Account account = new Account(); - account.setId(11L); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); - - 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-preview-1"))); - - assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); - assertEquals( - "Existing game membership is required for this non-public realm", exception.getMessage()); - org.mockito.Mockito.verify(sessionService) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), - org.mockito.ArgumentMatchers.eq("req-preview-1"), - org.mockito.ArgumentMatchers.argThat( - replay -> - !replay.success() - && "NON_PUBLIC_ENROLLMENT_REQUIRED".equals(replay.errorCode()) - && exception.getMessage().equals(replay.errorMessage())), - org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - } - @Test void grantRealmAccessUpsertsRuntimeGrant() { Account account = new Account(); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java new file mode 100644 index 0000000000..6add8183bd --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java @@ -0,0 +1,1307 @@ +package net.firedevops.firemud.common.security; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Canonical Gateway-owned JWS envelope for the protected first-party gameplay handoff. + * + *

This codec validates a typed source projection and signs the context; it does not establish + * that the source token, replay record, Gateway key delivery, or transport was qualified. A live + * producer must supply claims obtained from the canonical protected route and Gateway-derived + * address metadata. The verified context is not a Game Session admission decision. + */ +public final class GatewayFirstPartyConnectContextEnvelope { + public static final String PROTECTED_TYPE = "application/firemud-connect-context.v1+jws"; + public static final String AUDIENCE = "game-session"; + public static final String RECIPIENT = "game-session-service"; + public static final String TRANSPORT_CLASS = "first_party_web"; + + private static final int MAX_HEADER_BYTES = 2 * 1024; + private static final int MAX_PAYLOAD_BYTES = 12 * 1024; + private static final int MAX_COMPACT_BYTES = 16 * 1024; + private static final int MAX_CLOCK_SKEW_MILLIS = 5_000; + private static final long MAX_LIFETIME_MILLIS = 30_000L; + private static final long JCS_MAX_SAFE_INTEGER = 9_007_199_254_740_991L; + private static final BigInteger MAX_POSITIVE_BIGINT = BigInteger.valueOf(Long.MAX_VALUE); + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SAFE_CORRELATION = Pattern.compile("[A-Za-z0-9._:-]{1,256}"); + private static final Set AUTHORITY_REQUIRED_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set TENANT_CUTOFF_FIELDS = + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"); + private static final Set GRANT_FIELDS = + Set.of("tenantId", "worldSlug", "realmSlug", "playtestLifecycleId", "grantVersion"); + private static final Set CONTEXT_REQUIRED_FIELDS = + Set.of( + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "pointerVersion", + "catalogRevision", + "connectScopeId", + "connectRequestId", + "audience", + "recipient", + "authorityTuple", + "membershipVersion", + "connectTokenJti", + "replayAdmissionFence", + "issuedAt", + "verifiedAt", + "expiresAt", + "gatewayRequestId", + "canonicalClientAddress", + "transportClass"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private GatewayFirstPartyConnectContextEnvelope() {} + + /** Signs one complete typed source projection with a dedicated Gateway private key. */ + public static String sign( + GameplayConnectSource source, GatewayContextMetadata metadata, GatewaySigningKey signingKey) { + Objects.requireNonNull(source, "gameplay-connect source is required"); + Objects.requireNonNull(metadata, "Gateway context metadata is required"); + Objects.requireNonNull(signingKey, "Gateway signing key is required"); + validateLifetime( + metadata.issuedAtMillis(), + metadata.verifiedAtMillis(), + metadata.expiresAtMillis(), + source.sourceExpiresAtEpochSeconds(), + metadata.issuedAtMillis(), + 0); + + Map header = + Map.of("alg", "RS256", "kid", signingKey.keyId(), "typ", PROTECTED_TYPE); + ContextClaims context = ContextClaims.from(source, metadata); + requireAuthorityTupleBound(context.authorityTuple().toMap()); + byte[] headerBytes = canonicalJson(header); + byte[] payloadBytes = canonicalJson(context.toMap()); + requireEncodedBounds(headerBytes, payloadBytes); + + String encodedHeader = encode(headerBytes); + String encodedPayload = encode(payloadBytes); + String signingInput = encodedHeader + "." + encodedPayload; + try { + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(signingKey.privateKey); + signer.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + String compact = signingInput + "." + encode(signer.sign()); + if (compact.length() > MAX_COMPACT_BYTES) { + throw new IllegalArgumentException("Connect context exceeds its compact size bound"); + } + return compact; + } catch (IllegalArgumentException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Gateway connect-context signing failed", failure); + } + } + + /** Verifies canonical encoding, the dedicated Gateway key, exact schema, and expiry bounds. */ + public static VerifiedContext verify( + String compactJws, + GatewayVerificationKeySource keySource, + long nowMillis, + int allowedClockSkewMillis) { + Objects.requireNonNull(keySource, "Gateway verification-key source is required"); + if (nowMillis <= 0L + || allowedClockSkewMillis < 0 + || allowedClockSkewMillis > MAX_CLOCK_SKEW_MILLIS) { + throw reject(FailureReason.INVALID_LIFETIME); + } + CompactParts parts = splitCompact(compactJws); + Map header = parseObject(parts.header(), MAX_HEADER_BYTES); + String keyId = validateHeader(header); + byte[] canonicalHeader = canonicalJson(header); + if (!java.util.Arrays.equals(parts.header(), canonicalHeader)) { + throw reject(FailureReason.NON_CANONICAL_ENCODING); + } + + RSAPublicKey verificationKey; + try { + verificationKey = keySource.publicKeyFor(keyId); + } catch (KeySourceUnavailableException unavailable) { + throw reject(FailureReason.KEY_SOURCE_UNAVAILABLE); + } catch (RuntimeException unavailable) { + throw reject(FailureReason.KEY_SOURCE_UNAVAILABLE); + } + if (verificationKey == null) { + throw reject(FailureReason.UNKNOWN_KEY_ID); + } + try { + requireRsaKey(verificationKey); + } catch (IllegalArgumentException invalidKey) { + throw reject(FailureReason.INVALID_SIGNATURE); + } + verifySignature(parts, verificationKey); + + Map payload = parseObject(parts.payload(), MAX_PAYLOAD_BYTES); + byte[] canonicalPayload = canonicalJson(payload); + if (!java.util.Arrays.equals(parts.payload(), canonicalPayload)) { + throw reject(FailureReason.NON_CANONICAL_ENCODING); + } + ContextClaims context; + try { + context = ContextClaims.fromMap(payload); + } catch (VerificationException failure) { + throw failure; + } catch (RuntimeException invalidPayload) { + throw reject(FailureReason.INVALID_SCHEMA); + } + validateLifetime( + context.issuedAtMillis(), + context.verifiedAtMillis(), + context.expiresAtMillis(), + 0L, + nowMillis, + allowedClockSkewMillis); + return new VerifiedContext(keyId, context); + } + + private static void verifySignature(CompactParts parts, RSAPublicKey key) { + try { + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(key); + verifier.update(parts.signingInput().getBytes(StandardCharsets.US_ASCII)); + if (!verifier.verify(parts.signature())) { + throw reject(FailureReason.INVALID_SIGNATURE); + } + } catch (VerificationException failure) { + throw failure; + } catch (Exception failure) { + throw reject(FailureReason.INVALID_SIGNATURE); + } + } + + private static String validateHeader(Map header) { + if (!header.keySet().equals(Set.of("alg", "kid", "typ")) + || !"RS256".equals(header.get("alg")) + || !PROTECTED_TYPE.equals(header.get("typ")) + || !(header.get("kid") instanceof String keyId) + || !KEY_ID.matcher(keyId).matches()) { + throw reject(FailureReason.INVALID_HEADER); + } + return keyId; + } + + private static CompactParts splitCompact(String compact) { + if (compact == null || compact.isEmpty() || compact.length() > MAX_COMPACT_BYTES) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + for (int index = 0; index < compact.length(); index++) { + if (compact.charAt(index) > 0x7f) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + } + String[] segments = compact.split("\\.", -1); + if (segments.length != 3 + || segments[0].isEmpty() + || segments[1].isEmpty() + || segments[2].isEmpty()) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + byte[] header = decode(segments[0]); + byte[] payload = decode(segments[1]); + byte[] signature = decode(segments[2]); + if (header.length > MAX_HEADER_BYTES || payload.length > MAX_PAYLOAD_BYTES) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + return new CompactParts(header, payload, signature, segments[0] + "." + segments[1]); + } + + private static byte[] decode(String segment) { + if (!segment.matches("[A-Za-z0-9_-]+")) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + if (!encode(decoded).equals(segment)) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + return decoded; + } catch (IllegalArgumentException failure) { + throw reject(FailureReason.MALFORMED_COMPACT); + } + } + + private static Map parseObject(byte[] bytes, int maximumBytes) { + if (bytes.length == 0 || bytes.length > maximumBytes) { + throw reject(FailureReason.MALFORMED_JSON); + } + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map parsed = JSON.readValue(json, OBJECT); + if (parsed == null) { + throw reject(FailureReason.MALFORMED_JSON); + } + return parsed; + } catch (VerificationException failure) { + throw failure; + } catch (Exception failure) { + throw reject(FailureReason.MALFORMED_JSON); + } + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static void requireEncodedBounds(byte[] header, byte[] payload) { + if (header.length == 0 + || header.length > MAX_HEADER_BYTES + || payload.length == 0 + || payload.length > MAX_PAYLOAD_BYTES) { + throw new IllegalArgumentException("Connect context exceeds its encoded size bound"); + } + } + + private static void requireAuthorityTupleBound(Map authorityTuple) { + if (canonicalJson(authorityTuple).length + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static void validateLifetime( + long issuedAt, + long verifiedAt, + long expiresAt, + long sourceExpiresAtEpochSeconds, + long nowMillis, + int allowedClockSkewMillis) { + try { + BigInteger sourceExpiryMillis = + sourceExpiresAtEpochSeconds > 0L + ? BigInteger.valueOf(sourceExpiresAtEpochSeconds).multiply(BigInteger.valueOf(1_000L)) + : null; + long latestAllowedIssue = Math.addExact(nowMillis, allowedClockSkewMillis); + long earliestAllowedExpiry = Math.subtractExact(nowMillis, allowedClockSkewMillis); + long lifetime = Math.subtractExact(expiresAt, issuedAt); + if (issuedAt <= 0L + || issuedAt > JCS_MAX_SAFE_INTEGER + || verifiedAt <= 0L + || verifiedAt > JCS_MAX_SAFE_INTEGER + || expiresAt <= 0L + || expiresAt > JCS_MAX_SAFE_INTEGER + || nowMillis > JCS_MAX_SAFE_INTEGER + || sourceExpiresAtEpochSeconds < 0L + || verifiedAt > issuedAt + || issuedAt > latestAllowedIssue + || expiresAt <= issuedAt + || lifetime > MAX_LIFETIME_MILLIS + || sourceExpiryMillis != null + && BigInteger.valueOf(expiresAt).compareTo(sourceExpiryMillis) > 0 + || expiresAt <= earliestAllowedExpiry) { + throw reject(FailureReason.INVALID_LIFETIME); + } + } catch (ArithmeticException overflow) { + throw reject(FailureReason.INVALID_LIFETIME); + } + } + + private static String requiredString(Map map, String field, int maxUtf8Bytes) { + Object value = map.get(field); + if (!(value instanceof String text)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + requireText(text, maxUtf8Bytes, field); + return text; + } + + private static String optionalString(Map map, String field, int maxUtf8Bytes) { + if (!map.containsKey(field)) { + return null; + } + return requiredString(map, field, maxUtf8Bytes); + } + + private static long requiredPositiveSafeInteger(Map map, String field) { + Object value = map.get(field); + if (!(value instanceof Number number)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + try { + long result = new BigDecimal(number.toString()).longValueExact(); + if (result <= 0L || result > JCS_MAX_SAFE_INTEGER) { + throw reject(FailureReason.INVALID_SCHEMA); + } + return result; + } catch (ArithmeticException | NumberFormatException failure) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static void requireText(String value, int maxUtf8Bytes, String field) { + if (value == null + || value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Malformed " + field); + } + } + + private static UUID requireUuid(UUID value, String field) { + if (value == null + || value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L) { + throw new IllegalArgumentException("Malformed " + field); + } + return value; + } + + private static UUID parseUuid(Object value, String field) { + if (!(value instanceof String text) || !CANONICAL_UUID.matcher(text).matches()) { + throw reject(FailureReason.INVALID_SCHEMA); + } + try { + UUID parsed = UUID.fromString(text); + if (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw reject(FailureReason.INVALID_SCHEMA); + } + return parsed; + } catch (IllegalArgumentException failure) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static String requirePositiveLongDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Malformed " + field); + } + try { + if (new BigInteger(value).compareTo(MAX_POSITIVE_BIGINT) > 0) { + throw new IllegalArgumentException("Malformed " + field); + } + } catch (NumberFormatException failure) { + throw new IllegalArgumentException("Malformed " + field); + } + return value; + } + + private static String parsePositiveLongDecimal(Object value, String field) { + if (!(value instanceof String text)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + try { + return requirePositiveLongDecimal(text, field); + } catch (IllegalArgumentException failure) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static Map copyStringMap(Map source, String field) { + if (source == null) { + throw new IllegalArgumentException("Missing " + field); + } + Map result = new LinkedHashMap<>(); + source.forEach( + (key, value) -> { + requireCanonicalUuidText(key, field + " key"); + result.put(key, requirePositiveLongDecimal(value, field)); + }); + return Collections.unmodifiableMap(result); + } + + private static String requireCanonicalUuidText(String value, String field) { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + throw new IllegalArgumentException("Malformed " + field); + } + UUID parsed = UUID.fromString(value); + if (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw new IllegalArgumentException("Malformed " + field); + } + return value; + } + + private static boolean isCanonicalClientAddress(String value) { + if (value == null || value.isEmpty() || value.length() > 64) { + return false; + } + if (value.indexOf(':') >= 0) { + if (!value.matches("[0-9a-f:]+")) { + return false; + } + try { + byte[] address = InetAddress.getByName(value).getAddress(); + // InetAddress#getHostAddress emits the JDK's uncompressed IPv6 spelling. That spelling + // is the canonical address representation for this envelope, including the full eight + // groups; compressed IPv6 text is intentionally rejected. + return address.length == 16 + && !isIpv4MappedIpv6(address) + && InetAddress.getByAddress(address).getHostAddress().equals(value); + } catch (Exception ignored) { + return false; + } + } + String[] octets = value.split("\\.", -1); + if (octets.length != 4) { + return false; + } + byte[] address = new byte[4]; + for (int index = 0; index < octets.length; index++) { + String octet = octets[index]; + if (octet.isEmpty() || (octet.length() > 1 && octet.charAt(0) == '0')) { + return false; + } + try { + int parsed = Integer.parseInt(octet); + if (parsed < 0 || parsed > 255 || !Integer.toString(parsed).equals(octet)) { + return false; + } + address[index] = (byte) parsed; + } catch (NumberFormatException failure) { + return false; + } + } + try { + return InetAddress.getByAddress(address).getHostAddress().equals(value); + } catch (Exception ignored) { + return false; + } + } + + private static boolean isIpv4MappedIpv6(byte[] address) { + if (address.length != 16) { + return false; + } + for (int index = 0; index < 10; index++) { + if (address[index] != 0) { + return false; + } + } + return address[10] == (byte) 0xff && address[11] == (byte) 0xff; + } + + private static Map parseStringCounterMap(Object value, String field) { + if (!(value instanceof Map source)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + requireCanonicalUuidTextForRead(key); + result.put(key, parsePositiveLongDecimal(entry.getValue(), field)); + } + return Collections.unmodifiableMap(result); + } + + private static void requireCanonicalUuidTextForRead(String value) { + if (!CANONICAL_UUID.matcher(value).matches()) { + throw reject(FailureReason.INVALID_SCHEMA); + } + try { + UUID parsed = UUID.fromString(value); + if (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } catch (IllegalArgumentException failure) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static Map requireObject(Map parent, String field) { + Object value = parent.get(field); + if (!(value instanceof Map source)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static void exactFields( + Map object, Set required, Set optional) { + Set allowed = new LinkedHashSet<>(required); + allowed.addAll(optional); + if (!object.keySet().containsAll(required) || !allowed.containsAll(object.keySet())) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + + private static void requireRsaKey(java.security.Key key) { + int size = + key instanceof RSAPublicKey publicKey + ? publicKey.getModulus().bitLength() + : key instanceof RSAPrivateKey privateKey ? privateKey.getModulus().bitLength() : 0; + if (size < 2_048) { + throw new IllegalArgumentException("Gateway context key must be RSA-2048 or stronger"); + } + } + + private static VerificationException reject(FailureReason reason) { + return new VerificationException(reason); + } + + private static String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + /** A fresh, complete source projection supplied only after the Gateway route validator. */ + public record GameplayConnectSource( + UUID accountId, + UUID tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID gameInstanceId, + String pointerVersion, + String catalogRevision, + String connectScopeId, + String requestId, + AuthorityTuple authorityTuple, + Map membershipVersion, + String connectTokenJti, + String replayAdmissionFence, + String playtestLifecycleId, + String playtestStateGeneration, + long sourceExpiresAtEpochSeconds) { + public GameplayConnectSource { + accountId = requireUuid(accountId, "accountId"); + tenantId = requireUuid(tenantId, "tenantId"); + realmId = requireUuid(realmId, "realmId"); + worldSlug = GameplayRoutingBundleValidator.requireCanonicalSlug(worldSlug, "worldSlug"); + realmSlug = GameplayRoutingBundleValidator.requireCanonicalSlug(realmSlug, "realmSlug"); + playableStateNamespaceId = requireUuid(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope) && !"ISOLATED".equals(playableStateScope)) { + throw new IllegalArgumentException("Malformed playableStateScope"); + } + gameInstanceId = requireUuid(gameInstanceId, "gameInstanceId"); + pointerVersion = requirePositiveLongDecimal(pointerVersion, "pointerVersion"); + catalogRevision = requirePositiveLongDecimal(catalogRevision, "catalogRevision"); + requireText(connectScopeId, 2_048, "connectScopeId"); + requireText(requestId, 128, "requestId"); + Objects.requireNonNull(authorityTuple, "authorityTuple is required"); + membershipVersion = copyStringMap(membershipVersion, "membershipVersion"); + requireText(connectTokenJti, 128, "connectTokenJti"); + replayAdmissionFence = + requirePositiveLongDecimal(replayAdmissionFence, "replayAdmissionFence"); + if (sourceExpiresAtEpochSeconds <= 0L) { + throw new IllegalArgumentException("Malformed source expiry"); + } + if (playtestLifecycleId == null) { + if (playtestStateGeneration != null) { + throw new IllegalArgumentException("Incomplete playtest context"); + } + } else { + playtestLifecycleId = requireCanonicalUuidText(playtestLifecycleId, "playtestLifecycleId"); + playtestStateGeneration = + requirePositiveLongDecimal(playtestStateGeneration, "playtestStateGeneration"); + } + authorityTuple.validateForTarget( + accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, membershipVersion); + } + + @Override + public Map membershipVersion() { + return Map.copyOf(membershipVersion); + } + + @Override + public String toString() { + return "GameplayConnectSource[redacted]"; + } + } + + /** Gateway metadata projection; callers supply its trusted provenance and canonical address. */ + public record GatewayContextMetadata( + String canonicalClientAddress, + String gatewayRequestId, + long issuedAtMillis, + long verifiedAtMillis, + long expiresAtMillis) { + public GatewayContextMetadata { + requireText(canonicalClientAddress, 64, "canonicalClientAddress"); + if (!isCanonicalClientAddress(canonicalClientAddress)) { + throw new IllegalArgumentException("Malformed canonicalClientAddress"); + } + if (gatewayRequestId == null || !SAFE_CORRELATION.matcher(gatewayRequestId).matches()) { + throw new IllegalArgumentException("Malformed gatewayRequestId"); + } + if (issuedAtMillis <= 0L || verifiedAtMillis <= 0L || expiresAtMillis <= 0L) { + throw new IllegalArgumentException("Malformed context timestamps"); + } + } + + @Override + public String toString() { + return "GatewayContextMetadata[redacted]"; + } + } + + /** Exact copied Account authority evidence, validated in the fresh gameplay-connect profile. */ + public record AuthorityTuple( + String issuerAuthGeneration, + String accountAuthorityGeneration, + Map tenantAuthorityGeneration, + Map membershipAuthorityGeneration, + List privateRealmGrantVersions, + AccountSecurityCutoff accountSecurityCutoff, + Map tenantBillingCutoff) { + public AuthorityTuple { + issuerAuthGeneration = + requirePositiveLongDecimal(issuerAuthGeneration, "issuerAuthGeneration"); + accountAuthorityGeneration = + requirePositiveLongDecimal(accountAuthorityGeneration, "accountAuthorityGeneration"); + tenantAuthorityGeneration = + copyStringMap(tenantAuthorityGeneration, "tenantAuthorityGeneration"); + membershipAuthorityGeneration = + copyStringMap(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + privateRealmGrantVersions = List.copyOf(Objects.requireNonNull(privateRealmGrantVersions)); + if (privateRealmGrantVersions.size() > 1) { + throw new IllegalArgumentException("Too many private-realm grant entries"); + } + if ("1".equals(accountAuthorityGeneration) != (accountSecurityCutoff == null)) { + throw new IllegalArgumentException("Account cutoff presence does not match its generation"); + } + tenantBillingCutoff = immutableMap(tenantBillingCutoff, "tenantBillingCutoff"); + if (tenantBillingCutoff.size() > 1) { + throw new IllegalArgumentException("Too many tenant billing cutoffs"); + } + } + + @Override + public Map tenantAuthorityGeneration() { + return Map.copyOf(tenantAuthorityGeneration); + } + + @Override + public Map membershipAuthorityGeneration() { + return Map.copyOf(membershipAuthorityGeneration); + } + + @Override + public Map tenantBillingCutoff() { + return Map.copyOf(tenantBillingCutoff); + } + + @Override + public String toString() { + return "AuthorityTuple[redacted]"; + } + + private void validateForTarget( + UUID accountId, + UUID tenantId, + String worldSlug, + String realmSlug, + String playtestLifecycleId, + Map membershipVersion) { + String tenant = tenantId.toString(); + if (!tenantAuthorityGeneration.keySet().equals(Set.of(tenant)) + || !membershipAuthorityGeneration.keySet().equals(Set.of(tenant)) + || !membershipVersion.keySet().equals(Set.of(tenant))) { + throw new IllegalArgumentException("Authority maps must name the exact selected tenant"); + } + if (accountSecurityCutoff != null) { + if (!accountSecurityCutoff.accountAuthorityGeneration().equals(accountAuthorityGeneration) + || !accountSecurityCutoff.outboxStreamKey().equals(accountStream(accountId))) { + throw new IllegalArgumentException("Account cutoff does not match the source authority"); + } + } + if (tenantBillingCutoff.size() == 1) { + TenantBillingCutoff cutoff = tenantBillingCutoff.get(tenant); + if (cutoff == null + || !cutoff.tenantAuthorityGeneration().equals(tenantAuthorityGeneration.get(tenant)) + || !cutoff.outboxStreamKey().equals(tenantStream(tenantId))) { + throw new IllegalArgumentException("Tenant cutoff does not match the source authority"); + } + } + if (playtestLifecycleId == null) { + if (!privateRealmGrantVersions.isEmpty()) { + throw new IllegalArgumentException("Public target cannot carry a private grant"); + } + } else { + if (privateRealmGrantVersions.size() != 1) { + throw new IllegalArgumentException("Non-public target requires its exact grant"); + } + PrivateRealmGrantVersion grant = privateRealmGrantVersions.get(0); + if (!grant.tenantId().equals(tenant) + || !grant.worldSlug().equals(worldSlug) + || !grant.realmSlug().equals(realmSlug) + || !grant.playtestLifecycleId().equals(playtestLifecycleId)) { + throw new IllegalArgumentException("Private grant does not match the selected target"); + } + } + } + + private Map toMap() { + Map result = new LinkedHashMap<>(); + result.put("issuerAuthGeneration", issuerAuthGeneration); + result.put("accountAuthorityGeneration", accountAuthorityGeneration); + result.put("tenantAuthorityGeneration", tenantAuthorityGeneration); + result.put("membershipAuthorityGeneration", membershipAuthorityGeneration); + result.put( + "privateRealmGrantVersions", + privateRealmGrantVersions.stream().map(PrivateRealmGrantVersion::toMap).toList()); + if (accountSecurityCutoff != null) { + result.put("accountSecurityCutoff", accountSecurityCutoff.toMap()); + } + if (!tenantBillingCutoff.isEmpty()) { + Map cutoffs = new LinkedHashMap<>(); + tenantBillingCutoff.forEach((key, cutoff) -> cutoffs.put(key, cutoff.toMap())); + result.put("tenantBillingCutoff", cutoffs); + } + return Collections.unmodifiableMap(result); + } + + private static AuthorityTuple fromMap(Map source, UUID tenantId) { + exactFields( + source, + AUTHORITY_REQUIRED_FIELDS, + Set.of("accountSecurityCutoff", "tenantBillingCutoff")); + String issuerGeneration = + parsePositiveLongDecimal(source.get("issuerAuthGeneration"), "issuerAuthGeneration"); + String accountGeneration = + parsePositiveLongDecimal( + source.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + Map tenantGenerations = + parseStringCounterMap( + source.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + Map membershipGenerations = + parseStringCounterMap( + source.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + Object grantsValue = source.get("privateRealmGrantVersions"); + if (!(grantsValue instanceof List grants)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + List parsedGrants = new ArrayList<>(); + for (Object value : grants) { + if (!(value instanceof Map raw)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + Map grant = stringObject(raw); + exactFields(grant, GRANT_FIELDS, Set.of()); + parsedGrants.add( + new PrivateRealmGrantVersion( + parseUuid(grant.get("tenantId"), "tenantId").toString(), + requiredString(grant, "worldSlug", 120), + requiredString(grant, "realmSlug", 120), + parseUuid(grant.get("playtestLifecycleId"), "playtestLifecycleId").toString(), + parsePositiveLongDecimal(grant.get("grantVersion"), "grantVersion"))); + } + AccountSecurityCutoff accountCutoff = null; + if (source.containsKey("accountSecurityCutoff")) { + Map cutoff = stringObject(requireObject(source, "accountSecurityCutoff")); + exactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, Set.of()); + accountCutoff = + new AccountSecurityCutoff( + parsePositiveLongDecimal( + cutoff.get("accountAuthorityGeneration"), "account cutoff generation"), + requiredString(cutoff, "outboxStreamKey", 2_048), + parsePositiveLongDecimal(cutoff.get("outboxSequence"), "account cutoff sequence")); + } + Map billingCutoffs = Map.of(); + if (source.containsKey("tenantBillingCutoff")) { + Map rawCutoffs = requireObject(source, "tenantBillingCutoff"); + if (rawCutoffs.size() != 1 || !rawCutoffs.containsKey(tenantId.toString())) { + throw reject(FailureReason.INVALID_SCHEMA); + } + Map cutoff = + stringObject(requireNestedObject(rawCutoffs.get(tenantId.toString()))); + exactFields(cutoff, TENANT_CUTOFF_FIELDS, Set.of()); + billingCutoffs = + Map.of( + tenantId.toString(), + new TenantBillingCutoff( + parsePositiveLongDecimal( + cutoff.get("tenantAuthorityGeneration"), "billing cutoff generation"), + parsePositiveLongDecimal( + cutoff.get("tenantBillingSequence"), "billing cutoff sequence"), + requiredString(cutoff, "outboxStreamKey", 2_048), + parsePositiveLongDecimal( + cutoff.get("outboxSequence"), "billing cutoff sequence"))); + } + try { + return new AuthorityTuple( + issuerGeneration, + accountGeneration, + tenantGenerations, + membershipGenerations, + parsedGrants, + accountCutoff, + billingCutoffs); + } catch (IllegalArgumentException invalid) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + } + + public record PrivateRealmGrantVersion( + String tenantId, + String worldSlug, + String realmSlug, + String playtestLifecycleId, + String grantVersion) { + public PrivateRealmGrantVersion { + tenantId = requireCanonicalUuidText(tenantId, "grant tenantId"); + worldSlug = GameplayRoutingBundleValidator.requireCanonicalSlug(worldSlug, "worldSlug"); + realmSlug = GameplayRoutingBundleValidator.requireCanonicalSlug(realmSlug, "realmSlug"); + playtestLifecycleId = requireCanonicalUuidText(playtestLifecycleId, "playtestLifecycleId"); + grantVersion = requirePositiveLongDecimal(grantVersion, "grantVersion"); + } + + @Override + public String toString() { + return "PrivateRealmGrantVersion[redacted]"; + } + + private Map toMap() { + return Map.of( + "tenantId", tenantId, + "worldSlug", worldSlug, + "realmSlug", realmSlug, + "playtestLifecycleId", playtestLifecycleId, + "grantVersion", grantVersion); + } + } + + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) { + public AccountSecurityCutoff { + accountAuthorityGeneration = + requirePositiveLongDecimal(accountAuthorityGeneration, "cutoff account generation"); + requireText(outboxStreamKey, 2_048, "cutoff outboxStreamKey"); + outboxSequence = requirePositiveLongDecimal(outboxSequence, "cutoff outboxSequence"); + if (outboxStreamKey.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Malformed cutoff outboxStreamKey"); + } + } + + @Override + public String toString() { + return "AccountSecurityCutoff[redacted]"; + } + + private Map toMap() { + return Map.of( + "accountAuthorityGeneration", accountAuthorityGeneration, + "outboxStreamKey", outboxStreamKey, + "outboxSequence", outboxSequence); + } + } + + public record TenantBillingCutoff( + String tenantAuthorityGeneration, + String tenantBillingSequence, + String outboxStreamKey, + String outboxSequence) { + public TenantBillingCutoff { + tenantAuthorityGeneration = + requirePositiveLongDecimal(tenantAuthorityGeneration, "billing tenant generation"); + tenantBillingSequence = + requirePositiveLongDecimal(tenantBillingSequence, "tenantBillingSequence"); + requireText(outboxStreamKey, 2_048, "billing outboxStreamKey"); + outboxSequence = requirePositiveLongDecimal(outboxSequence, "billing outboxSequence"); + if (outboxStreamKey.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Malformed billing outboxStreamKey"); + } + } + + @Override + public String toString() { + return "TenantBillingCutoff[redacted]"; + } + + private Map toMap() { + return Map.of( + "tenantAuthorityGeneration", tenantAuthorityGeneration, + "tenantBillingSequence", tenantBillingSequence, + "outboxStreamKey", outboxStreamKey, + "outboxSequence", outboxSequence); + } + } + + public record ContextClaims( + UUID accountId, + UUID tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID gameInstanceId, + String pointerVersion, + String catalogRevision, + String connectScopeId, + String connectRequestId, + AuthorityTuple authorityTuple, + Map membershipVersion, + String connectTokenJti, + String replayAdmissionFence, + long issuedAtMillis, + long verifiedAtMillis, + long expiresAtMillis, + String gatewayRequestId, + String canonicalClientAddress, + String playtestLifecycleId, + String playtestStateGeneration) { + public ContextClaims { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(realmId); + Objects.requireNonNull(playableStateNamespaceId); + Objects.requireNonNull(gameInstanceId); + Objects.requireNonNull(authorityTuple); + membershipVersion = copyStringMap(membershipVersion, "membershipVersion"); + if (issuedAtMillis <= 0L || verifiedAtMillis <= 0L || expiresAtMillis <= 0L) { + throw new IllegalArgumentException("Malformed context timestamps"); + } + } + + @Override + public Map membershipVersion() { + return Map.copyOf(membershipVersion); + } + + @Override + public String toString() { + return "ContextClaims[redacted]"; + } + + private static ContextClaims from( + GameplayConnectSource source, GatewayContextMetadata metadata) { + return new ContextClaims( + source.accountId(), + source.tenantId(), + source.realmId(), + source.worldSlug(), + source.realmSlug(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.gameInstanceId(), + source.pointerVersion(), + source.catalogRevision(), + source.connectScopeId(), + source.requestId(), + source.authorityTuple(), + source.membershipVersion(), + source.connectTokenJti(), + source.replayAdmissionFence(), + metadata.issuedAtMillis(), + metadata.verifiedAtMillis(), + metadata.expiresAtMillis(), + metadata.gatewayRequestId(), + metadata.canonicalClientAddress(), + source.playtestLifecycleId(), + source.playtestStateGeneration()); + } + + private Map toMap() { + Map result = new LinkedHashMap<>(); + result.put("accountId", accountId.toString()); + result.put("tenantId", tenantId.toString()); + result.put("realmId", realmId.toString()); + result.put("worldSlug", worldSlug); + result.put("realmSlug", realmSlug); + result.put("playableStateNamespaceId", playableStateNamespaceId.toString()); + result.put("playableStateScope", playableStateScope); + result.put("gameInstanceId", gameInstanceId.toString()); + result.put("pointerVersion", pointerVersion); + result.put("catalogRevision", catalogRevision); + result.put("connectScopeId", connectScopeId); + result.put("connectRequestId", connectRequestId); + result.put("audience", AUDIENCE); + result.put("recipient", RECIPIENT); + result.put("authorityTuple", authorityTuple.toMap()); + result.put("membershipVersion", membershipVersion); + result.put("connectTokenJti", connectTokenJti); + result.put("replayAdmissionFence", replayAdmissionFence); + result.put("issuedAt", issuedAtMillis); + result.put("verifiedAt", verifiedAtMillis); + result.put("expiresAt", expiresAtMillis); + result.put("gatewayRequestId", gatewayRequestId); + result.put("canonicalClientAddress", canonicalClientAddress); + result.put("transportClass", TRANSPORT_CLASS); + if (playtestLifecycleId != null) { + result.put("playtestLifecycleId", playtestLifecycleId); + result.put("playtestStateGeneration", playtestStateGeneration); + } + return Collections.unmodifiableMap(result); + } + + private static ContextClaims fromMap(Map value) { + exactFields( + value, CONTEXT_REQUIRED_FIELDS, Set.of("playtestLifecycleId", "playtestStateGeneration")); + String audience = requiredString(value, "audience", 32); + if (!AUDIENCE.equals(audience)) { + throw reject(FailureReason.AUDIENCE_MISMATCH); + } + String recipient = requiredString(value, "recipient", 64); + if (!RECIPIENT.equals(recipient)) { + throw reject(FailureReason.RECIPIENT_MISMATCH); + } + String transportClass = requiredString(value, "transportClass", 32); + if (!TRANSPORT_CLASS.equals(transportClass)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + UUID accountId = parseUuid(value.get("accountId"), "accountId"); + UUID tenantId = parseUuid(value.get("tenantId"), "tenantId"); + UUID realmId = parseUuid(value.get("realmId"), "realmId"); + String worldSlug = requiredString(value, "worldSlug", 120); + String realmSlug = requiredString(value, "realmSlug", 120); + UUID namespace = parseUuid(value.get("playableStateNamespaceId"), "playableStateNamespaceId"); + String stateScope = requiredString(value, "playableStateScope", 16); + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + UUID gameInstance = parseUuid(value.get("gameInstanceId"), "gameInstanceId"); + String pointerVersion = + parsePositiveLongDecimal(value.get("pointerVersion"), "pointerVersion"); + String catalogRevision = + parsePositiveLongDecimal(value.get("catalogRevision"), "catalogRevision"); + String connectScopeId = requiredString(value, "connectScopeId", 2_048); + String requestId = requiredString(value, "connectRequestId", 128); + Map rawTuple = requireObject(value, "authorityTuple"); + AuthorityTuple authorityTuple = AuthorityTuple.fromMap(rawTuple, tenantId); + requireAuthorityTupleBound(authorityTuple.toMap()); + Map membershipVersion = + parseStringCounterMap(value.get("membershipVersion"), "membershipVersion"); + String jti = requiredString(value, "connectTokenJti", 128); + String replayFence = + parsePositiveLongDecimal(value.get("replayAdmissionFence"), "replayAdmissionFence"); + long issuedAt = requiredPositiveSafeInteger(value, "issuedAt"); + long verifiedAt = requiredPositiveSafeInteger(value, "verifiedAt"); + long expiresAt = requiredPositiveSafeInteger(value, "expiresAt"); + String gatewayRequestId = requiredString(value, "gatewayRequestId", 256); + if (!SAFE_CORRELATION.matcher(gatewayRequestId).matches()) { + throw reject(FailureReason.INVALID_SCHEMA); + } + String address = requiredString(value, "canonicalClientAddress", 64); + if (!isCanonicalClientAddress(address)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + String lifecycle = optionalString(value, "playtestLifecycleId", 36); + String stateGeneration = optionalString(value, "playtestStateGeneration", 19); + if ((lifecycle == null) != (stateGeneration == null)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + if (lifecycle != null) { + lifecycle = parseUuid(lifecycle, "playtestLifecycleId").toString(); + stateGeneration = parsePositiveLongDecimal(stateGeneration, "playtestStateGeneration"); + } + try { + ContextClaims context = + new ContextClaims( + accountId, + tenantId, + realmId, + GameplayRoutingBundleValidator.requireCanonicalSlug(worldSlug, "worldSlug"), + GameplayRoutingBundleValidator.requireCanonicalSlug(realmSlug, "realmSlug"), + namespace, + stateScope, + gameInstance, + pointerVersion, + catalogRevision, + connectScopeId, + requestId, + authorityTuple, + membershipVersion, + jti, + replayFence, + issuedAt, + verifiedAt, + expiresAt, + gatewayRequestId, + address, + lifecycle, + stateGeneration); + authorityTuple.validateForTarget( + accountId, tenantId, worldSlug, realmSlug, lifecycle, membershipVersion); + return context; + } catch (IllegalArgumentException invalid) { + throw reject(FailureReason.INVALID_SCHEMA); + } + } + } + + public static final class VerifiedContext { + private final String keyId; + private final ContextClaims claims; + + private VerifiedContext(String keyId, ContextClaims claims) { + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Malformed Gateway key id"); + } + this.keyId = keyId; + this.claims = Objects.requireNonNull(claims); + } + + public String keyId() { + return keyId; + } + + public ContextClaims claims() { + return claims; + } + } + + public static final class GatewaySigningKey { + private final String keyId; + private final PrivateKey privateKey; + + public GatewaySigningKey(String keyId, PrivateKey privateKey) { + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Malformed Gateway key id"); + } + this.privateKey = + Objects.requireNonNull(privateKey, "Gateway private signing key is required"); + requireRsaKey(this.privateKey); + this.keyId = keyId; + } + + public String keyId() { + return keyId; + } + } + + @FunctionalInterface + public interface GatewayVerificationKeySource { + /** Returns the dedicated Gateway public key, or {@code null} when the key id is unknown. */ + RSAPublicKey publicKeyFor(String keyId) throws KeySourceUnavailableException; + } + + public static final class KeySourceUnavailableException extends RuntimeException { + public KeySourceUnavailableException() { + super("Gateway verification keys are unavailable"); + } + } + + public enum FailureReason { + MALFORMED_COMPACT, + MALFORMED_JSON, + INVALID_HEADER, + NON_CANONICAL_ENCODING, + UNKNOWN_KEY_ID, + KEY_SOURCE_UNAVAILABLE, + INVALID_SIGNATURE, + INVALID_SCHEMA, + INVALID_LIFETIME, + AUDIENCE_MISMATCH, + RECIPIENT_MISMATCH + } + + public static final class VerificationException extends RuntimeException { + private final FailureReason reason; + + private VerificationException(FailureReason reason) { + super( + "Gateway connect context rejected: " + reason.name().toLowerCase(java.util.Locale.ROOT)); + this.reason = reason; + } + + public FailureReason reason() { + return reason; + } + } + + private record CompactParts( + byte[] header, byte[] payload, byte[] signature, String signingInput) {} + + private static String accountStream(UUID accountId) { + return "account:auth-authority:v1:account/" + accountId; + } + + private static String tenantStream(UUID tenantId) { + return "account:auth-authority:v1:tenant/" + tenantId; + } + + private static Map immutableMap( + Map source, String field) { + if (source == null) { + throw new IllegalArgumentException("Missing " + field); + } + Map result = new LinkedHashMap<>(); + source.forEach( + (key, value) -> { + requireCanonicalUuidText(key, field + " key"); + result.put(key, Objects.requireNonNull(value, field + " value")); + }); + return Collections.unmodifiableMap(result); + } + + private static Map requireNestedObject(Object value) { + if (!(value instanceof Map source)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + return stringObject(source); + } + + private static Map stringObject(Map source) { + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw reject(FailureReason.INVALID_SCHEMA); + } + result.put(key, entry.getValue()); + } + return result; + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java new file mode 100644 index 0000000000..7c9c0e3a5a --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java @@ -0,0 +1,797 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +class GatewayFirstPartyConnectContextEnvelopeTest { + private static final String KEY_ID = "gateway-key-1"; + private static final UUID ACCOUNT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID REALM_ID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID NAMESPACE_ID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID LIFECYCLE_ID = UUID.fromString("60000000-0000-4000-8000-000000000006"); + private static final long NOW_MILLIS = 1_800_000_000_000L; + private static final String MAX_BIGINT = "9223372036854775807"; + private static final String SAFE_INTEGER = "9007199254740991"; + private static final String FIRST_WIDE_INTEGER = "9007199254740992"; + private static final String FIRST_WIDE_INTEGER_PLUS_ONE = "9007199254740993"; + + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private KeyPair keyPair; + private GatewayFirstPartyConnectContextEnvelope.GatewaySigningKey signingKey; + private GatewayFirstPartyConnectContextEnvelope.GatewayVerificationKeySource keySource; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2_048); + keyPair = generator.generateKeyPair(); + signingKey = + new GatewayFirstPartyConnectContextEnvelope.GatewaySigningKey(KEY_ID, keyPair.getPrivate()); + keySource = kid -> KEY_ID.equals(kid) ? (RSAPublicKey) keyPair.getPublic() : null; + } + + @Test + void signsAndVerifiesCompletePublicContextWithoutChangingCopiedAccountClaims() throws Exception { + var source = + source( + SAFE_INTEGER, FIRST_WIDE_INTEGER, SAFE_INTEGER, FIRST_WIDE_INTEGER, MAX_BIGINT, false); + + String compact = GatewayFirstPartyConnectContextEnvelope.sign(source, metadata(), signingKey); + var verified = + GatewayFirstPartyConnectContextEnvelope.verify(compact, keySource, NOW_MILLIS, 5_000); + Map payload = payload(compact); + + assertThat(verified.keyId()).isEqualTo(KEY_ID); + assertThat(verified.claims().accountId()).isEqualTo(ACCOUNT_ID); + assertThat(verified.claims().tenantId()).isEqualTo(TENANT_ID); + assertThat(payload) + .containsEntry("audience", "game-session") + .containsEntry("recipient", "game-session-service") + .containsEntry("transportClass", "first_party_web") + .containsEntry("pointerVersion", SAFE_INTEGER) + .containsEntry("catalogRevision", FIRST_WIDE_INTEGER) + .containsEntry("replayAdmissionFence", MAX_BIGINT) + .containsEntry("canonicalClientAddress", "203.0.113.8") + .containsEntry("gatewayRequestId", "webflux-request-17") + .doesNotContainKeys( + "iss", "requestId", "sourceExpiresAtEpochSeconds", "playtestLifecycleId"); + assertThat(payload.get("authorityTuple")).isEqualTo(authorityTupleMap(source.authorityTuple())); + assertThat(payload.get("membershipVersion")) + .isEqualTo(Map.of(TENANT_ID.toString(), MAX_BIGINT)); + assertThat((String) payload.get("connectRequestId")).isEqualTo("request-operation-17"); + assertThat(verified.claims().replayAdmissionFence()).isEqualTo(MAX_BIGINT); + } + + @Test + void signsExactLifecycleGrantAndGenerationForNonPublicTarget() throws Exception { + var source = source("8", "9", MAX_BIGINT, MAX_BIGINT, "9", true); + + String compact = GatewayFirstPartyConnectContextEnvelope.sign(source, metadata(), signingKey); + var verified = + GatewayFirstPartyConnectContextEnvelope.verify(compact, keySource, NOW_MILLIS, 0); + Map payload = payload(compact); + + assertThat(verified.claims().playtestLifecycleId()).isEqualTo(LIFECYCLE_ID.toString()); + assertThat(verified.claims().playtestStateGeneration()).isEqualTo("9"); + assertThat(payload.get("playtestLifecycleId")).isEqualTo(LIFECYCLE_ID.toString()); + assertThat(payload.get("playtestStateGeneration")).isEqualTo("9"); + assertThat(payload.get("authorityTuple")).isEqualTo(authorityTupleMap(source.authorityTuple())); + } + + @Test + void acceptsSafeBoundaryAdjacentWideValuesAndOwnerMaximumAsCanonicalStrings() { + assertThat(source(SAFE_INTEGER, SAFE_INTEGER, SAFE_INTEGER, SAFE_INTEGER, SAFE_INTEGER, false)) + .extracting( + GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource::pointerVersion, + GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource::catalogRevision, + GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource::replayAdmissionFence) + .containsExactly(SAFE_INTEGER, SAFE_INTEGER, SAFE_INTEGER); + assertThat( + source( + FIRST_WIDE_INTEGER, + FIRST_WIDE_INTEGER, + FIRST_WIDE_INTEGER, + FIRST_WIDE_INTEGER, + FIRST_WIDE_INTEGER, + false) + .pointerVersion()) + .isEqualTo(FIRST_WIDE_INTEGER); + var adjacentWideSource = + source( + FIRST_WIDE_INTEGER_PLUS_ONE, + FIRST_WIDE_INTEGER_PLUS_ONE, + FIRST_WIDE_INTEGER_PLUS_ONE, + FIRST_WIDE_INTEGER_PLUS_ONE, + FIRST_WIDE_INTEGER_PLUS_ONE, + false); + String adjacentWideCompact = + GatewayFirstPartyConnectContextEnvelope.sign(adjacentWideSource, metadata(), signingKey); + var adjacentWideVerified = + GatewayFirstPartyConnectContextEnvelope.verify( + adjacentWideCompact, keySource, NOW_MILLIS, 0); + Map adjacentWidePayload = payload(adjacentWideCompact); + assertThat(adjacentWidePayload) + .containsEntry("pointerVersion", FIRST_WIDE_INTEGER_PLUS_ONE) + .containsEntry("catalogRevision", FIRST_WIDE_INTEGER_PLUS_ONE) + .containsEntry("replayAdmissionFence", FIRST_WIDE_INTEGER_PLUS_ONE); + assertThat(adjacentWidePayload.get("authorityTuple")) + .isEqualTo(authorityTupleMap(adjacentWideSource.authorityTuple())); + assertThat(adjacentWideVerified.claims().pointerVersion()) + .isEqualTo(FIRST_WIDE_INTEGER_PLUS_ONE); + var maximumSource = source(MAX_BIGINT, MAX_BIGINT, MAX_BIGINT, MAX_BIGINT, MAX_BIGINT, false); + String maximumCompact = + GatewayFirstPartyConnectContextEnvelope.sign(maximumSource, metadata(), signingKey); + var maximumVerified = + GatewayFirstPartyConnectContextEnvelope.verify(maximumCompact, keySource, NOW_MILLIS, 0); + Map maximumPayload = payload(maximumCompact); + assertThat(maximumPayload) + .containsEntry("pointerVersion", MAX_BIGINT) + .containsEntry("catalogRevision", MAX_BIGINT) + .containsEntry("replayAdmissionFence", MAX_BIGINT); + assertThat(maximumPayload.get("authorityTuple")) + .isEqualTo(authorityTupleMap(maximumSource.authorityTuple())); + assertThat(maximumVerified.claims().pointerVersion()).isEqualTo(MAX_BIGINT); + } + + @Test + void rejectsMalformedCounterAliasesAndValuesAboveTheOwnerBigintMaximum() { + for (String malformed : + List.of("0", "00", "+1", "01", "1.0", "1e0", " 1", "9223372036854775808")) { + assertThatThrownBy(() -> source(malformed, "1", "1", "1", "1", false)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> source("1", "1", "1", "1", "0", false)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> source("1", "1", "1", "1", "9223372036854775808", false)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMapKeyMismatchExtraTenantAndWrongNestedCounterType() { + var tuple = authorityTuple("1", "1", "1", "1", false); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + "world", + "realm", + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "1", + "1", + "scope-1", + "request-1", + tuple, + Map.of(UUID.randomUUID().toString(), "1"), + "jti-1", + "1", + null, + null, + NOW_MILLIS / 1_000L + 30L)) + .isInstanceOf(IllegalArgumentException.class); + + Map extraTenant = new LinkedHashMap<>(); + extraTenant.put(TENANT_ID.toString(), "1"); + extraTenant.put(UUID.randomUUID().toString(), "2"); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + "world", + "realm", + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "1", + "1", + "scope-1", + "request-1", + tuple, + extraTenant, + "jti-1", + "1", + null, + null, + NOW_MILLIS / 1_000L + 30L)) + .isInstanceOf(IllegalArgumentException.class); + + Map unsafeAuthority = new LinkedHashMap<>(authorityTupleMap(tuple)); + unsafeAuthority.put("issuerAuthGeneration", 1L); + Map payload = payloadMap(source("1", "1", "1", "1", "1", false)); + payload.put("authorityTuple", unsafeAuthority); + String compact = token(payload); + assertRejected(compact, GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + + unsafeAuthority.put("issuerAuthGeneration", 1.0d); + payload.put("authorityTuple", unsafeAuthority); + assertRejected( + token(payload), GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + + payload = payloadMap(source("1", "1", "1", "1", "1", false)); + payload.put("pointerVersion", 9_007_199_254_740_991L); + assertRejected( + token(payload), GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + + payload = payloadMap(source("1", "1", "1", "1", "1", false)); + payload.put("replayAdmissionFence", "01"); + assertRejected( + token(payload), GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + } + + @Test + void validatesOptionalCutoffPresenceAndPositiveSequenceValues() { + String tenant = TENANT_ID.toString(); + var cutoff = + new GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff( + MAX_BIGINT, "account:auth-authority:v1:account/" + ACCOUNT_ID, MAX_BIGINT); + var billing = + new GatewayFirstPartyConnectContextEnvelope.TenantBillingCutoff( + MAX_BIGINT, + "9223372036854775806", + "account:auth-authority:v1:tenant/" + TENANT_ID, + "1"); + var tuple = + new GatewayFirstPartyConnectContextEnvelope.AuthorityTuple( + MAX_BIGINT, + MAX_BIGINT, + Map.of(tenant, MAX_BIGINT), + Map.of(tenant, MAX_BIGINT), + List.of(), + cutoff, + Map.of(tenant, billing)); + var valid = sourceWithTuple(tuple, MAX_BIGINT); + String compact = GatewayFirstPartyConnectContextEnvelope.sign(valid, metadata(), signingKey); + assertThat(payload(compact).get("authorityTuple")).isEqualTo(authorityTupleMap(tuple)); + + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff( + "2", "account:auth-authority:v1:account/" + ACCOUNT_ID, "0")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.AuthorityTuple( + "1", "2", Map.of(tenant, "1"), Map.of(tenant, "1"), List.of(), null, Map.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsWrongProtectedTypeAlgorithmUnknownHeadersAndUnknownKeyIds() throws Exception { + Map payload = payloadMap(source("1", "1", "1", "1", "1", false)); + assertRejected( + token(payload, Map.of("alg", "RS256", "kid", KEY_ID, "typ", "JWT")), + GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_HEADER); + assertRejected( + token( + payload, + Map.of( + "alg", + "HS256", + "kid", + KEY_ID, + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)), + GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_HEADER); + assertRejected( + token( + payload, + Map.of( + "alg", + "RS256", + "kid", + KEY_ID, + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE, + "crit", + List.of("x"))), + GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_HEADER); + + String unknownKey = + token( + payload, + Map.of( + "alg", + "RS256", + "kid", + "unknown-key", + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)); + assertRejected( + unknownKey, GatewayFirstPartyConnectContextEnvelope.FailureReason.UNKNOWN_KEY_ID); + } + + @Test + void rejectsAudienceRecipientMissingFieldsUnknownFieldsAndAlteredSignature() throws Exception { + Map base = payloadMap(source("1", "1", "1", "1", "1", false)); + Map wrongAudience = new LinkedHashMap<>(base); + wrongAudience.put("audience", "internal-service"); + assertRejected( + token(wrongAudience), + GatewayFirstPartyConnectContextEnvelope.FailureReason.AUDIENCE_MISMATCH); + Map wrongRecipient = new LinkedHashMap<>(base); + wrongRecipient.put("recipient", "account-service"); + assertRejected( + token(wrongRecipient), + GatewayFirstPartyConnectContextEnvelope.FailureReason.RECIPIENT_MISMATCH); + Map missing = new LinkedHashMap<>(base); + missing.remove("accountId"); + assertRejected( + token(missing), GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + Map extra = new LinkedHashMap<>(base); + extra.put("issuer", "not-allowed"); + assertRejected( + token(extra), GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SCHEMA); + + String valid = + GatewayFirstPartyConnectContextEnvelope.sign( + source("1", "1", "1", "1", "1", false), metadata(), signingKey); + String[] parts = valid.split("\\."); + String altered = + parts[0] + + "." + + parts[1] + + "." + + (parts[2].charAt(0) == 'A' ? "B" : "A") + + parts[2].substring(1); + assertRejected( + altered, GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_SIGNATURE); + } + + @Test + void rejectsDuplicateAndNoncanonicalJsonAndPaddedBase64() throws Exception { + String header = + canonical( + Map.of( + "alg", + "RS256", + "kid", + KEY_ID, + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)); + String duplicatePayload = "{\"accountId\":\"one\",\"accountId\":\"two\"}"; + assertRejected( + compactRaw(header, duplicatePayload), + GatewayFirstPartyConnectContextEnvelope.FailureReason.MALFORMED_JSON); + + String validPayload = canonical(payloadMap(source("1", "1", "1", "1", "1", false))); + String noncanonical = " " + validPayload; + assertRejected( + compactRaw(header, noncanonical), + GatewayFirstPartyConnectContextEnvelope.FailureReason.NON_CANONICAL_ENCODING); + + String valid = + GatewayFirstPartyConnectContextEnvelope.sign( + source("1", "1", "1", "1", "1", false), metadata(), signingKey); + String[] parts = valid.split("\\."); + assertRejected( + parts[0] + "=." + parts[1] + "." + parts[2], + GatewayFirstPartyConnectContextEnvelope.FailureReason.MALFORMED_COMPACT); + } + + @Test + void enforcesSourceExpiryThirtySecondLifetimeSafeTimeIntegersAndClockSkew() { + var source = source("1", "1", "1", "1", "1", false); + var metadataPastSource = + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "203.0.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 31_000L); + assertThatThrownBy( + () -> + GatewayFirstPartyConnectContextEnvelope.sign( + source, metadataPastSource, signingKey)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) + .extracting("reason") + .isEqualTo(GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); + + var sourceExpiringInTenSeconds = + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + source.accountId(), + source.tenantId(), + source.realmId(), + source.worldSlug(), + source.realmSlug(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.gameInstanceId(), + source.pointerVersion(), + source.catalogRevision(), + source.connectScopeId(), + source.requestId(), + source.authorityTuple(), + source.membershipVersion(), + source.connectTokenJti(), + source.replayAdmissionFence(), + source.playtestLifecycleId(), + source.playtestStateGeneration(), + NOW_MILLIS / 1_000L + 10L); + assertThatThrownBy( + () -> + GatewayFirstPartyConnectContextEnvelope.sign( + sourceExpiringInTenSeconds, metadata(), signingKey)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) + .extracting("reason") + .isEqualTo(GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); + + var tooLongSource = + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + source.accountId(), + source.tenantId(), + source.realmId(), + source.worldSlug(), + source.realmSlug(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.gameInstanceId(), + source.pointerVersion(), + source.catalogRevision(), + source.connectScopeId(), + source.requestId(), + source.authorityTuple(), + source.membershipVersion(), + source.connectTokenJti(), + source.replayAdmissionFence(), + source.playtestLifecycleId(), + source.playtestStateGeneration(), + NOW_MILLIS / 1_000L + 31L); + var metadata31 = + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "203.0.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 31_000L); + assertThatThrownBy( + () -> + GatewayFirstPartyConnectContextEnvelope.sign(tooLongSource, metadata31, signingKey)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class); + + String valid = GatewayFirstPartyConnectContextEnvelope.sign(source, metadata(), signingKey); + assertRejectedAt( + valid, + NOW_MILLIS + 30_001L, + 0, + GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); + assertRejectedAt( + valid, + NOW_MILLIS, + 5_001, + GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); + } + + @Test + void failsClosedForUnavailableDedicatedKeySourceWithoutLeakingInput() throws Exception { + String secretMarker = "sensitive-context-value"; + Map payload = payloadMap(source("1", "1", "1", "1", "1", false)); + payload.put("connectScopeId", secretMarker); + String token = + token( + payload, + Map.of( + "alg", + "RS256", + "kid", + "missing-key", + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)); + assertThatThrownBy( + () -> + GatewayFirstPartyConnectContextEnvelope.verify( + token, + kid -> { + throw new GatewayFirstPartyConnectContextEnvelope + .KeySourceUnavailableException(); + }, + NOW_MILLIS, + 0)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) + .satisfies( + failure -> { + assertThat(failure.getMessage()).doesNotContain(secretMarker, "missing-key", token); + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo( + GatewayFirstPartyConnectContextEnvelope.FailureReason.KEY_SOURCE_UNAVAILABLE); + }); + } + + @Test + void rejectsNoncanonicalClientAddressInsteadOfAcceptingHeaderLikeInput() { + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "203.000.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "198.51.100.2, 203.0.113.8", + "request-1", + NOW_MILLIS, + NOW_MILLIS, + NOW_MILLIS + 30_000L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsOnlyJdkCanonicalUncompressedIpv6AddressSpelling() { + var metadata = + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:db8:0:0:0:0:0:1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L); + String signed = + GatewayFirstPartyConnectContextEnvelope.sign( + source("1", "1", "1", "1", "1", false), metadata, signingKey); + + var verified = GatewayFirstPartyConnectContextEnvelope.verify(signed, keySource, NOW_MILLIS, 0); + + assertThat(verified.claims().canonicalClientAddress()).isEqualTo("2001:db8:0:0:0:0:0:1"); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:db8::1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:DB8:0:0:0:0:0:1", + "request-1", + NOW_MILLIS, + NOW_MILLIS, + NOW_MILLIS + 30_000L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonAsciiCharactersInIpv6Address() { + assertThatThrownBy( + () -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:db8:0:0:0:0:0:1", + "request-1", + NOW_MILLIS, + NOW_MILLIS, + NOW_MILLIS + 30_000L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource source( + String pointerVersion, + String catalogRevision, + String generation, + String membershipVersion, + String replayFence, + boolean privateTarget) { + var tuple = + authorityTuple(generation, generation, generation, membershipVersion, privateTarget); + return sourceWithTuple(tuple, replayFence, pointerVersion, catalogRevision, privateTarget); + } + + private GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource sourceWithTuple( + GatewayFirstPartyConnectContextEnvelope.AuthorityTuple tuple, String membershipVersion) { + return sourceWithTuple(tuple, membershipVersion, "1", "1", false); + } + + private GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource sourceWithTuple( + GatewayFirstPartyConnectContextEnvelope.AuthorityTuple tuple, + String replayFence, + String pointerVersion, + String catalogRevision, + boolean privateTarget) { + return new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + "world", + "realm", + NAMESPACE_ID, + privateTarget ? "ISOLATED" : "SHARED", + GAME_INSTANCE_ID, + pointerVersion, + catalogRevision, + "scope-1", + "request-operation-17", + tuple, + Map.of(TENANT_ID.toString(), "9223372036854775807"), + "65aabb12c46bf1985dd4d578f20e2d4ce129880acf6f4d70b146ccf795fb0d6c", + replayFence, + privateTarget ? LIFECYCLE_ID.toString() : null, + privateTarget ? "9" : null, + NOW_MILLIS / 1_000L + 30L); + } + + private GatewayFirstPartyConnectContextEnvelope.AuthorityTuple authorityTuple( + String issuerGeneration, + String accountGeneration, + String tenantGeneration, + String memberGeneration, + boolean privateTarget) { + return new GatewayFirstPartyConnectContextEnvelope.AuthorityTuple( + issuerGeneration, + accountGeneration, + Map.of(TENANT_ID.toString(), tenantGeneration), + Map.of(TENANT_ID.toString(), memberGeneration), + privateTarget + ? List.of( + new GatewayFirstPartyConnectContextEnvelope.PrivateRealmGrantVersion( + TENANT_ID.toString(), + "world", + "realm", + LIFECYCLE_ID.toString(), + "9223372036854775807")) + : List.of(), + "1".equals(accountGeneration) + ? null + : new GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff( + accountGeneration, "account:auth-authority:v1:account/" + ACCOUNT_ID, "1"), + Map.of()); + } + + private GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata metadata() { + return new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "203.0.113.8", "webflux-request-17", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L); + } + + private Map payloadMap( + GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource source) { + String compact = GatewayFirstPartyConnectContextEnvelope.sign(source, metadata(), signingKey); + return payload(compact); + } + + private Map authorityTupleMap( + GatewayFirstPartyConnectContextEnvelope.AuthorityTuple tuple) { + Map map = new LinkedHashMap<>(); + map.put("issuerAuthGeneration", tuple.issuerAuthGeneration()); + map.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration()); + map.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + map.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + map.put( + "privateRealmGrantVersions", + tuple.privateRealmGrantVersions().stream() + .map( + grant -> + Map.of( + "tenantId", grant.tenantId(), + "worldSlug", grant.worldSlug(), + "realmSlug", grant.realmSlug(), + "playtestLifecycleId", grant.playtestLifecycleId(), + "grantVersion", grant.grantVersion())) + .toList()); + if (tuple.accountSecurityCutoff() != null) { + map.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + tuple.accountSecurityCutoff().accountAuthorityGeneration(), + "outboxStreamKey", tuple.accountSecurityCutoff().outboxStreamKey(), + "outboxSequence", tuple.accountSecurityCutoff().outboxSequence())); + } + if (!tuple.tenantBillingCutoff().isEmpty()) { + Map cutoffs = new LinkedHashMap<>(); + tuple + .tenantBillingCutoff() + .forEach( + (tenant, cutoff) -> + cutoffs.put( + tenant, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + map.put("tenantBillingCutoff", cutoffs); + } + return map; + } + + private Map payload(String compact) { + try { + byte[] bytes = Base64.getUrlDecoder().decode(compact.split("\\.")[1]); + return JSON.readValue(new String(bytes, StandardCharsets.UTF_8), OBJECT); + } catch (JacksonException failure) { + throw new IllegalStateException(failure); + } + } + + private String token(Map payload) { + return token( + payload, + Map.of( + "alg", + "RS256", + "kid", + KEY_ID, + "typ", + GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)); + } + + private String token(Map payload, Map header) { + return compactRaw(canonical(header), canonical(payload)); + } + + private String compactRaw(String headerJson, String payloadJson) { + try { + String input = + encode(headerJson.getBytes(StandardCharsets.UTF_8)) + + "." + + encode(payloadJson.getBytes(StandardCharsets.UTF_8)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + encode(signer.sign()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } + + private String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private void assertRejected( + String token, GatewayFirstPartyConnectContextEnvelope.FailureReason reason) { + assertThatThrownBy( + () -> GatewayFirstPartyConnectContextEnvelope.verify(token, keySource, NOW_MILLIS, 0)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) + .satisfies( + failure -> + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo(reason)); + } + + private void assertRejectedAt( + String token, + long nowMillis, + int skew, + GatewayFirstPartyConnectContextEnvelope.FailureReason reason) { + assertThatThrownBy( + () -> GatewayFirstPartyConnectContextEnvelope.verify(token, keySource, nowMillis, skew)) + .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) + .satisfies( + failure -> + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo(reason)); + } +} diff --git a/services/game-session-service/README.md b/services/game-session-service/README.md index faa87239bb..4f54ba9797 100644 --- a/services/game-session-service/README.md +++ b/services/game-session-service/README.md @@ -3,11 +3,15 @@ Design details are kept in the architecture docs: [Game Session Service Design](../../design/architecture/microservices/game-session-service/README.md) -This README is only a stub. **Do not place design information here.** +This README links to the service's canonical design. **Do not duplicate design details here.** + +## Current first-party gameplay availability + +Ordinary credential-bearing LOGIN and reconnect behavior remain on their existing transport paths. Public first-party `/ws/game/**` admission is unavailable: Gateway cookie admission and route readiness fail closed, while Game Session bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or gameplay-binding effects. Game Session retains complete signed-context and canonical-route/private-handle revalidation sources and rejects partial selector fallback, but this local preparation does not qualify authenticated ingress or playable first-party LOGIN. See [Authentication and authorization](../../design/architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative), [Session Behavior](../../design/architecture/system-architecture-session-behavior.md#session-types-and-lifetimes), and the [Player Access and Session tracker](../../design/project-management/implementation-tracking/player-access-and-session.md#canonical-first-party-receiving-preparation). ## Account Service dependency -- The Game Session Service delegates credential verification to the Account Service `/auth/login` (or gRPC `Authenticate`) endpoint and stores the issued JWT/session data per the “Login and Session Flow” section of `design/architecture/system-architecture-authentication.md`. +- On maintained credential-bearing paths, the Game Session Service delegates credential verification to Account Service `/auth/login` or gRPC `Authenticate` and stores the resulting session data under the canonical authentication and session contracts. This does not make the public first-party `/ws/game/**` receiving path available. - The login smoke test and local workflows expect either the lightweight Account Service stub or a local Account Service instance to be reachable; without it the `LOGIN ` step cannot complete and later `PLAY` / gameplay commands cannot be admitted. ## Local development diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java index 63a02b4fbb..d5ca7983b0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java @@ -13,6 +13,7 @@ import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; +import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -74,14 +75,25 @@ public void initialize() throws SSLException, IOException { initReloadingClient(); } - public CanonicalGameplayLoginResult authenticate(AuthenticateRequest originalRequest) { + public CanonicalGameplayLoginResult authenticate( + AuthenticateRequest originalRequest, BooleanSupplier originalCustodyCurrent) { CanonicalGameplayLoginResult.requireOriginalRequest(originalRequest); + Objects.requireNonNull(originalCustodyCurrent, "Original custody guard required"); return invokeWithBoundedRetry( (currentStub, overall) -> { var response = currentStub.withDeadline(overall).authenticate(originalRequest); return CanonicalGameplayLoginResult.fromAuthenticatedResponse( response, originalRequest, verifier, clock); - }); + }, + () -> custodyCurrent(originalCustodyCurrent)); + } + + private static boolean custodyCurrent(BooleanSupplier originalCustodyCurrent) { + try { + return originalCustodyCurrent.getAsBoolean(); + } catch (RuntimeException unavailable) { + return false; + } } /** Lifecycle-only call: the workflow retains the exact original nonsecret request identity. */ @@ -94,17 +106,21 @@ public InitialGameplayLoginDisposalResult retireInitialGameplayLogin( currentStub.withDeadline(overall).retireInitialGameplayLogin(originalRequest); return InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( response, originalRequest); - }); + }, + () -> true); } private T invokeWithBoundedRetry( - BiFunction call) { + BiFunction call, + BooleanSupplier operationCurrent) { + Objects.requireNonNull(operationCurrent, "Operation currentness guard required"); Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); if (Context.current().getDeadline() != null) overall = overall.minimum(Context.current().getDeadline()); for (int attempt = 0; attempt < 2; attempt++) { if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); - if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + if (Context.current().isCancelled() || !custodyCurrent(operationCurrent)) + throw failure(Status.Code.CANCELLED); var currentStub = stub(); if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); try { @@ -115,7 +131,8 @@ private T invokeWithBoundedRetry( || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) throw boundedTransportFailure(transport); if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); - if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + if (Context.current().isCancelled() || !custodyCurrent(operationCurrent)) + throw failure(Status.Code.CANCELLED); try { reloadChannel(); } catch (SSLException reloadFailure) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java index 8cb1a20d13..f982374d18 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -63,7 +64,22 @@ public CommunicationCommandHandlingResult handle( meterRegistry.counter(COMMUNICATION_INVOCATIONS_METRIC, "type", typeTag).increment(); meterRegistry.counter(metricPrefix(command.type()) + ".invocations").increment(); - ParsedCommunication parsed = parseCommunication(context, command); + ParsedCommunication parsed; + try { + parsed = parseCommunication(context, command); + } catch (SessionContextUnavailableException unavailable) { + logFailure( + "UNAVAILABLE", + "Recipient session unavailable", + context, + tenantTag, + command.type(), + unavailable); + return new CommunicationCommandHandlingResult( + CommandEnqueueResult.failure( + "COMMUNICATION_NOT_DELIVERED", "Recipient session unavailable"), + List.of()); + } if (!parsed.valid()) { logFailure( "INVALID_ARGUMENT", parsed.errorMessage(), context, tenantTag, command.type(), null); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 4f800c6f8d..7b6c50b189 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -91,6 +91,27 @@ public LoginCommandHandler( public LoginCommandHandlingResult handle( String sessionId, TextCommand command, boolean requiresSoloTick) { + SessionIdParsing.ParsedSessionId transportId = parseSessionId(sessionId); + if (transportId.valid()) { + try { + SessionContext retained = + sessionContextService.findBySessionId(transportId.value()).orElse(null); + FirstPartyConnectContextResolution resolution = + FirstPartyConnectContextResolution.resolve( + transportId.value(), retained, firstPartyConnectContextRegistry); + if (resolution.invalid()) { + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } + if (resolution.connectContext().isPresent()) { + if (!command.args().isEmpty()) { + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } + return failure("FIRST_PARTY_AUTHORITY_UNAVAILABLE", "First-party login is unavailable"); + } + } catch (RuntimeException unavailable) { + return failure(AUTHENTICATION_UNAVAILABLE_CODE, "Authentication service unavailable"); + } + } Optional maybeChallengeRequest = command.emailLoginChallengePayload(); if (maybeChallengeRequest.isPresent()) { @@ -144,16 +165,13 @@ public LoginCommandHandlingResult handle( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); } - invalidateStaleFirstPartyConnectContext(numericSessionId, authenticatedAccountId); persistSessionContext( numericSessionId, instance.getTenantId(), authenticatedAccountId, canonicalLoginName, authResponse.getAuthToken(), - bootstrapGameInstanceId, - null, - null); + bootstrapGameInstanceId); return new LoginCommandHandlingResult( CommandEnqueueResult.success(), List.of( @@ -163,14 +181,6 @@ public LoginCommandHandlingResult handle( Map.of("loginName", canonicalLoginName)))); } - private void invalidateStaleFirstPartyConnectContext(long sessionId, long accountId) { - firstPartyConnectContextRegistry - .find(sessionId) - .filter( - connectContext -> !Objects.equals(connectContext.accountId(), Long.toString(accountId))) - .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); - } - private LoginCommandHandlingResult handleEmailLoginChallenge( String sessionId, TextCommandPayload.EmailLoginChallengeRequest challengeRequest) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); @@ -214,13 +224,6 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI Optional maybeContext = connectContextResolution.connectContext(); if (connectContextResolution.invalid()) { - clearFailedLoginSessionState( - numericSessionId, - existingSession != null ? existingSession.tenantId() : 0L, - existingSession != null ? existingSession.bootstrapGameInstanceId() : 0L, - existingSession != null ? existingSession.worldSlug() : null, - existingSession != null ? existingSession.realmSlug() : null, - existingSession != null ? existingSession.pointerVersion() : 0L); return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); } if (maybeContext.isEmpty()) { @@ -229,102 +232,9 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_MESSAGE); } - - var verifiedContext = maybeContext.get(); - if (existingSession != null - && existingSession.hasAccountIdentity() - && !Objects.equals(existingSession.accountId(), verifiedContext.accountId())) { - firstPartyConnectContextRegistry.unregister(numericSessionId); - return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); - } - long numericAccountId; - try { - numericAccountId = - PositiveLongParsing.requireOptionalText(verifiedContext.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); - } catch (IllegalArgumentException ex) { - clearFailedFirstPartyLoginSessionState( - numericSessionId, - existingSession, - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); - return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); - } - Optional maybeInstance = - gameInstanceRepository.findById(verifiedContext.gameInstanceId()); - if (maybeInstance.isEmpty()) { - clearFailedLoginSessionState( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); - return failure("SESSION_NOT_FOUND", "Session not found"); - } - GameInstance instance = maybeInstance.get(); - if (instance.getTenantId() != verifiedContext.tenantId()) { - clearFailedLoginSessionState( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); - return failure("CONNECT_SCOPE_INVALID", "Connect scope invalid"); - } - Optional maybeCurrentPointer = - currentAdmissionPointer(verifiedContext); - if (maybeCurrentPointer.isEmpty()) { - clearFailedLoginSessionState( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); - return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); - } - - persistSessionContext( - numericSessionId, - verifiedContext.tenantId(), - numericAccountId, - "first-party:" + verifiedContext.accountId(), - null, - verifiedContext.gameInstanceId(), - verifiedContext, - maybeCurrentPointer.orElseThrow().stateScope()); - return new LoginCommandHandlingResult( - CommandEnqueueResult.success(), - List.of( - PlayerOutput.message( - "Logged in as first-party account " + verifiedContext.accountId(), - "message.login.first-party-success", - Map.of("accountId", verifiedContext.accountId())))); - } - - private void clearFailedFirstPartyLoginSessionState( - long sessionId, - SessionContext existingSession, - long fallbackTenantId, - long fallbackBootstrapGameInstanceId, - String worldSlug, - String realmSlug, - long pointerVersion) { - if (existingSession != null && existingSession.hasAccountIdentity()) { - return; - } - clearFailedLoginSessionState( - sessionId, - fallbackTenantId, - fallbackBootstrapGameInstanceId, - worldSlug, - realmSlug, - pointerVersion); + // Preserve the UUID identity and complete handoff. The canonical Account login/lease + // consumer is unavailable; legacy numeric authentication must not install a binding. + return failure("FIRST_PARTY_AUTHORITY_UNAVAILABLE", "First-party login is unavailable"); } private void persistSessionContext( @@ -333,9 +243,7 @@ private void persistSessionContext( long accountId, String loginName, String jwt, - long bootstrapGameInstanceId, - net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, - String verifiedPlayableStateScope) { + long bootstrapGameInstanceId) { if (sessionContextService == null) { return; } @@ -353,17 +261,10 @@ private void persistSessionContext( Optional reusableBootstrapShell = sameAuthenticatedAccount ? Optional.empty() - : reusableBootstrapShell( - existing, - tenantId, - accountId, - bootstrapGameInstanceId, - verifiedConnectContext, - verifiedPlayableStateScope); - // LOGIN authenticates account identity. Preserve gameplay scope only when both account and - // tenant remain unchanged. An unauthenticated shell may retain only a current normalized - // bootstrap route; a verified first-party connect context is additionally required to retain - // its connect selector. Neither path carries a gameplay binding into LOGIN. + : reusableBootstrapShell(existing, tenantId, bootstrapGameInstanceId); + // LOGIN authenticates account identity. An unauthenticated generic shell may retain its + // current normalized bootstrap route, but no connect selector or gameplay binding. A + // first-party connect-context shell is rejected by reusableBootstrapShell. SessionContext context = reusableBootstrapShell.isPresent() ? authenticatedBootstrapContext( @@ -372,8 +273,7 @@ private void persistSessionContext( accountId, loginName, jwt, - reusableBootstrapShell.orElseThrow(), - verifiedConnectContext != null) + reusableBootstrapShell.orElseThrow()) : !sameAuthenticatedAccount ? new SessionContext( sessionId, @@ -406,7 +306,8 @@ private void persistSessionContext( existing.pointerVersion(), existing.playableStateScope(), existing.connectScopeId(), - existing.connectRequestId()); + existing.connectRequestId(), + existing.firstPartyConnectContext()); if (projectedExisting != null && !Objects.equals(projectedExisting.accountId(), accountIdText)) { gameplayPresenceLifecycleService.clearGameplayBinding( @@ -424,12 +325,7 @@ private void persistSessionContext( } private Optional reusableBootstrapShell( - SessionContext existing, - long tenantId, - long accountId, - long bootstrapGameInstanceId, - net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, - String verifiedPlayableStateScope) { + SessionContext existing, long tenantId, long bootstrapGameInstanceId) { if (existing == null || existing.hasAccountIdentity() || existing.tenantId() != tenantId @@ -439,29 +335,13 @@ private Optional reusableBootstrapShell( return Optional.empty(); } - if (verifiedConnectContext == null) { - return currentAdmissionPointer(existing) - .filter(pointer -> Objects.equals(existing.playableStateScope(), pointer.stateScope())) - .map(ignored -> existing); + if (existing.firstPartyConnectContext() != null + || existing.hasPartialPersistedFirstPartyConnectContext()) { + return Optional.empty(); } - - boolean verifiedIdentityAndTargetMatch = - verifiedConnectContext.hasCompleteRoutingScope() - && Objects.equals(verifiedConnectContext.accountId(), Long.toString(accountId)) - && verifiedConnectContext.tenantId() == tenantId - && verifiedConnectContext.gameInstanceId() == bootstrapGameInstanceId - && Objects.equals(existing.playableStateScope(), verifiedPlayableStateScope) - && GameplayAdmissionPointerSnapshots.sameBootstrapRoute( - verifiedConnectContext, - tenantId, - bootstrapGameInstanceId, - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion()) - && Objects.equals(existing.connectScopeId(), verifiedConnectContext.connectScopeId()) - && Objects.equals( - existing.connectRequestId(), verifiedConnectContext.connectRequestId()); - return verifiedIdentityAndTargetMatch ? Optional.of(existing) : Optional.empty(); + return currentAdmissionPointer(existing) + .filter(pointer -> Objects.equals(existing.playableStateScope(), pointer.stateScope())) + .map(ignored -> existing); } private SessionContext authenticatedBootstrapContext( @@ -470,8 +350,7 @@ private SessionContext authenticatedBootstrapContext( long accountId, String loginName, String jwt, - SessionContext bootstrapShell, - boolean preserveConnectSelector) { + SessionContext bootstrapShell) { return new SessionContext( sessionId, tenantId, @@ -488,8 +367,9 @@ private SessionContext authenticatedBootstrapContext( bootstrapShell.realmSlug(), bootstrapShell.pointerVersion(), bootstrapShell.playableStateScope(), - preserveConnectSelector ? bootstrapShell.connectScopeId() : null, - preserveConnectSelector ? bootstrapShell.connectRequestId() : null); + null, + null, + bootstrapShell.firstPartyConnectContext()); } private long resolveBootstrapGameInstanceId(long sessionId) { @@ -504,20 +384,6 @@ private long resolveBootstrapGameInstanceId(long sessionId) { .orElse(0L); } - private Optional currentAdmissionPointer( - net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedContext) { - if (verifiedContext == null || !verifiedContext.hasCompleteRoutingScope()) { - return Optional.empty(); - } - return currentAdmissionPointer( - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion(), - null); - } - private Optional currentAdmissionPointer( SessionContext bootstrapShell) { if (bootstrapShell == null @@ -619,7 +485,8 @@ private void clearFailedLoginSessionState( preservedPointerVersion, null, projectedExisting != null ? projectedExisting.connectScopeId() : null, - projectedExisting != null ? projectedExisting.connectRequestId() : null)); + projectedExisting != null ? projectedExisting.connectRequestId() : null, + projectedExisting != null ? projectedExisting.firstPartyConnectContext() : null)); } private static final Map CANONICAL_ERROR_MAP = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java index 6bcf832df5..7dc23906f8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java @@ -212,7 +212,8 @@ private SessionContext updatedContext(SessionContext current, RoomInstanceRef de current.pointerVersion(), current.playableStateScope(), current.connectScopeId(), - current.connectRequestId()); + current.connectRequestId(), + current.firstPartyConnectContext()); } private boolean validDestination(SessionContext current, RoomInstanceRef destination) { 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 775c145547..c86cc986dd 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 @@ -26,10 +26,8 @@ import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; @@ -122,6 +120,44 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { Objects.requireNonNull(sessionId, "sessionId must not be null"); Objects.requireNonNull(command, "command must not be null"); + Optional transportId = + net.firedevops.firemud.gamesession.service.SessionIdParsing.parse(sessionId) + .optionalValue(); + if (transportId.isPresent()) { + try { + SessionContext retained = + sessionContextService.findBySessionId(transportId.orElseThrow()).orElse(null); + FirstPartyConnectContextResolution resolution = + FirstPartyConnectContextResolution.resolve( + transportId.orElseThrow(), retained, firstPartyConnectContextRegistry); + if (resolution.invalid()) { + return connectContextInvalidFailure("unknown", null); + } + if (resolution.connectContext().isPresent()) { + // Current canonical target is reread by resolution before legacy Account, roster or + // binding work. + return failure( + "FIRST_PARTY_AUTHORITY_UNAVAILABLE", + "First-party gameplay is unavailable", + null, + Map.of(), + "unknown", + null, + null, + null); + } + } catch (RuntimeException unavailable) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + "unknown", + null, + null, + null); + } + } Optional maybeContext = sessionAuthenticationService.resolveSessionContext(sessionId); String tenantTag = @@ -186,6 +222,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } GameplayWorldCatalog.WorldView selectedWorld = maybeWorld.get(); + // Registry or session state can change between the top-level check and this reread. FirstPartyConnectContextResolution connectContextResolution = FirstPartyConnectContextResolution.resolve( context.sessionId(), context, firstPartyConnectContextRegistry); @@ -196,11 +233,22 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { ? Long.toString(context.bootstrapGameInstanceId()) : null); } + if (connectContextResolution.connectContext().isPresent()) { + return failure( + "FIRST_PARTY_AUTHORITY_UNAVAILABLE", + "First-party gameplay is unavailable", + null, + Map.of(), + tenantTag, + null, + null, + null); + } Optional maybeRealm = selection.explicitRealmSelector() != null ? gameplayWorldCatalog.resolveRealmForAdmission( selectedWorld, selection.explicitRealmSelector()) - : selectDefaultRealm(selectedWorld, connectContextResolution.connectContext()); + : selectDefaultRealm(selectedWorld); if (maybeRealm.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, @@ -222,12 +270,6 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { try (GameplayLoggingContext worldContext = GameplayLoggingContext.open( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), null, null)) { - Optional connectScopeFailure = - validateFirstPartyConnectScope( - connectContextResolution, selectedWorld, selectedRealm, selectedTenantTag); - if (connectScopeFailure.isPresent()) { - return connectScopeFailure.get(); - } Optional authorityFailure = validateRuntimeAdmission(context, selectedWorld, selectedRealm, selectedTenantTag, 0L); if (authorityFailure.isPresent()) { @@ -319,7 +361,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { selectedRealm.pointerVersion(), selectedRealm.stateScope(), context.connectScopeId(), - context.connectRequestId()); + context.connectRequestId(), + context.firstPartyConnectContext()); sessionContextService.save(updated); gameplayPresenceLifecycleService.registerConnected(updated); publishCommandEvent(updated, command); @@ -372,42 +415,6 @@ private Optional validateModerationPolicy( return Optional.empty(); } - private Optional validateFirstPartyConnectScope( - FirstPartyConnectContextResolution connectContextResolution, - GameplayWorldCatalog.WorldView selectedWorld, - GameplayWorldCatalog.RealmView selectedRealm, - String tenantTag) { - return connectContextResolution - .connectContext() - .flatMap( - connectContext -> { - if (!connectContext.hasCompleteRoutingScope()) { - return Optional.of( - connectContextInvalidFailure( - tenantTag, Long.toString(selectedRealm.gameInstanceId()))); - } - if (!GameplayAdmissionPointerSnapshots.sameBootstrapRoute( - connectContext, - selectedRealm.tenantId(), - selectedRealm.gameInstanceId(), - selectedWorld.slug(), - selectedRealm.slug(), - selectedRealm.pointerVersion())) { - return Optional.of( - failure( - "CONNECT_SCOPE_MISMATCH", - "Connect scope mismatch", - "error.play.connect-scope-mismatch", - Map.of(), - tenantTag, - Long.toString(selectedRealm.gameInstanceId()), - null, - null)); - } - return Optional.empty(); - }); - } - private PlayCommandHandlingResult connectContextInvalidFailure( String tenantTag, String gameInstanceTag) { return failure( @@ -982,17 +989,7 @@ private Optional resolveSelection( } private Optional selectDefaultRealm( - GameplayWorldCatalog.WorldView selectedWorld, - Optional connectContext) { - if (connectContext.isPresent() - && StringUtils.hasText(connectContext.orElseThrow().realmSlug())) { - Optional hintedRealm = - gameplayWorldCatalog.resolveRealmForAdmission( - selectedWorld, connectContext.orElseThrow().realmSlug()); - if (hintedRealm.isPresent()) { - return hintedRealm; - } - } + GameplayWorldCatalog.WorldView selectedWorld) { if (gameplayWorldCatalog.requiresExplicitRealmSelection(selectedWorld)) { return Optional.empty(); } @@ -1121,7 +1118,8 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) requestedPointerVersion, null, context.connectScopeId(), - context.connectRequestId())); + context.connectRequestId(), + context.firstPartyConnectContext())); LOG.debug( "Cleared stale gameplay binding after denied reconnect-style PLAY for tenant {} session {} world {} realm {} reason {}", tenantTag, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java index 33defe407a..3c346027a4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java @@ -1,21 +1,19 @@ package net.firedevops.firemud.gamesession.config; -import net.firedevops.firemud.common.security.JwtUtil; -import org.springframework.beans.factory.annotation.Qualifier; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GatewayVerificationKeySource; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.KeySourceUnavailableException; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; @Configuration public class FirstPartyConnectContextConfig { - + /** Production key delivery is not implemented. Missing dedicated keys deny every context. */ @Bean - @Qualifier("firstPartyConnectContextJwtUtil") - public JwtUtil firstPartyConnectContextJwtUtil(FirstPartyConnectContextProperties properties) { - String secret = properties.getJwtSecret(); - if (!StringUtils.hasText(secret)) { - secret = "missing-first-party-connect-context-secret"; - } - return new JwtUtil(secret, properties.getTtlMs()); + @ConditionalOnMissingBean(GatewayVerificationKeySource.class) + public GatewayVerificationKeySource gatewayVerificationKeySource() { + return keyId -> { + throw new KeySourceUnavailableException(); + }; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java index 715bc11f80..3f07c9143f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java @@ -6,6 +6,6 @@ @Data @ConfigurationProperties(prefix = "firemud.gateway.connect-context") public class FirstPartyConnectContextProperties { - private String jwtSecret; private long ttlMs = 30_000L; + private int allowedClockSkewMs = 0; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java index f7b687aa25..14b7c392cb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java @@ -33,7 +33,7 @@ * aggregate validation are non-admitting: no context CAS, ACTIVE/currentness lease, Redis writer, * orphan retirement or authenticated public-ingress authority is supplied by this value. */ -public final class CanonicalGameplayLoginResult { +public final class CanonicalGameplayLoginResult implements AutoCloseable { // Each projection is contained in Account's bounded 8 KiB initial owner bundle. private static final int MAX_CHECKPOINT_PROJECTION_BYTES = 8 * 1024; private static final JsonMapper JSON = @@ -63,6 +63,8 @@ public final class CanonicalGameplayLoginResult { GameSessionAccountDelegationJwtProfileValidator::validateInitialClaims); private final byte[] compactJwt; private final NonSecretEvidence evidence; + private final Object lifecycleMutex = new Object(); + private boolean closed; private CanonicalGameplayLoginResult(byte[] compactJwt, NonSecretEvidence evidence) { this.compactJwt = compactJwt.clone(); @@ -291,7 +293,21 @@ private static UUID v4(String text) { } public byte[] compactJwtBytes() { - return compactJwt.clone(); + synchronized (lifecycleMutex) { + if (closed) throw new IllegalStateException("Canonical LOGIN private result is closed"); + return compactJwt.clone(); + } + } + + /** Ends this invocation's owned compact-token custody and overwrites its private byte array. */ + @Override + public void close() { + synchronized (lifecycleMutex) { + if (!closed) { + Arrays.fill(compactJwt, (byte) 0); + closed = true; + } + } } public NonSecretEvidence evidence() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java index ee987930a1..7d0faf923f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java @@ -7,7 +7,8 @@ public interface ActiveTransportSessionRegistry { void register(long sessionId, WebSocketSession session); - void unregister(long sessionId, WebSocketSession session); + /** Returns true only when this exact currently registered transport was atomically removed. */ + boolean unregister(long sessionId, WebSocketSession session); Optional find(long sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java index dbc9c5d04a..b805571c26 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java @@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; @@ -71,7 +72,19 @@ private void deliverView( SendCommunicationResponse response, CommunicationRecipientView view) { try (GameplayLoggingContext actorLoggingContext = GameplayLoggingContext.from(actorContext)) { - Optional maybeRecipient = resolveRecipient(actorContext, view); + Optional maybeRecipient; + try { + maybeRecipient = resolveRecipient(actorContext, view); + } catch (SessionContextUnavailableException unavailable) { + LOG.warn( + "Unable to read retained recipient session context for role {}", + roleTag(view), + unavailable); + meterRegistry + .counter("gamesession.communication.delivery.failed", "role", roleTag(view)) + .increment(); + return; + } if (maybeRecipient.isEmpty()) { meterRegistry .counter("gamesession.communication.delivery.missed", "role", roleTag(view)) @@ -170,7 +183,15 @@ private void push( meterRegistry .counter("gamesession.communication.delivery.failed", "role", roleTag(view)) .increment(); - activeTransportSessionRegistry.unregister(recipient.sessionId(), session); + try { + // Only the owned close callback removes registration and commits disconnect cleanup. + session.close(CloseStatus.SERVER_ERROR.withReason("internal_error")); + } catch (IOException closeFailure) { + LOG.warn( + "Failed to close transport after delivery failure for session {}", + recipient.sessionId(), + closeFailure); + } } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java index f2b6e237fe..f914e40b6e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java @@ -1,30 +1,99 @@ package net.firedevops.firemud.gamesession.service; import java.io.Serializable; -import org.springframework.util.StringUtils; - -public record FirstPartyConnectContext( - String accountId, - long tenantId, - String worldSlug, - String realmSlug, - long gameInstanceId, - long pointerVersion, - String connectScopeId, - String connectTokenJti, - String connectRequestId, - String gatewayRequestId) - implements Serializable { - private static final long serialVersionUID = 1L; +import java.util.Objects; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.VerifiedContext; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; + +/** Retains the full signed handoff and its resolved owner snapshot, never login authority. */ +public final class FirstPartyConnectContext implements Serializable { + private static final long serialVersionUID = 2L; + private final String compactJws; + private final CanonicalPlayableTarget resolvedTarget; + private final transient VerifiedContext verifiedContext; + + FirstPartyConnectContext( + String compactJws, VerifiedContext verifiedContext, CanonicalPlayableTarget resolvedTarget) { + this.compactJws = Objects.requireNonNull(compactJws); + this.verifiedContext = Objects.requireNonNull(verifiedContext); + this.resolvedTarget = Objects.requireNonNull(resolvedTarget); + } + + public String compactJws() { + return compactJws; + } + + public CanonicalPlayableTarget resolvedTarget() { + return resolvedTarget; + } + + public ContextClaims claims() { + if (verifiedContext == null) { + throw new IllegalStateException("Retained first-party context requires verification"); + } + return verifiedContext.claims(); + } + + public String accountId() { + return claims().accountId().toString(); + } + + /** Private row handles are supplied only by the canonical owner read. */ + public long gameSessionTenantId() { + return resolvedTarget.gameSessionTenantId(); + } + + public long runtimeGameInstanceId() { + return resolvedTarget.gameInstanceId(); + } + + public String worldSlug() { + return claims().worldSlug(); + } + + public String realmSlug() { + return claims().realmSlug(); + } + + public long pointerVersion() { + return resolvedTarget.pointerVersion(); + } + + public String connectScopeId() { + return claims().connectScopeId(); + } + + public String connectRequestId() { + return claims().connectRequestId(); + } + + public String connectTokenJti() { + return claims().connectTokenJti(); + } + + public String gatewayRequestId() { + return claims().gatewayRequestId(); + } public boolean hasCompleteRoutingScope() { - return StringUtils.hasText(accountId) - && tenantId > 0L - && gameInstanceId > 0L - && pointerVersion > 0L - && StringUtils.hasText(worldSlug) - && StringUtils.hasText(realmSlug) - && StringUtils.hasText(connectScopeId) - && StringUtils.hasText(connectRequestId); + return verifiedContext != null && resolvedTarget != null; + } + + @Override + public String toString() { + return "FirstPartyConnectContext[redacted]"; + } + + @Override + public boolean equals(Object other) { + return other instanceof FirstPartyConnectContext that + && Objects.equals(compactJws, that.compactJws) + && Objects.equals(resolvedTarget, that.resolvedTarget); + } + + @Override + public int hashCode() { + return Objects.hash(compactJws, resolvedTarget); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java index 3799e94d7f..2102284812 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java @@ -5,7 +5,13 @@ public interface FirstPartyConnectContextRegistry { void register(long sessionId, FirstPartyConnectContext connectContext); + /** + * Returns a retained context only after validating its signature, expiry, and current route. + * Consumers may trust a present result as fresh at the time of this lookup. + */ Optional find(long sessionId); + FirstPartyConnectContext requireRetained(FirstPartyConnectContext context); + void unregister(long sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java index b3be62a86b..94ce0a676f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java @@ -10,26 +10,41 @@ public record FirstPartyConnectContextResolution( connectContext = Objects.requireNonNull(connectContext, "connectContext must not be null"); } + /** + * Resolves live registry or persisted first-party context. Persisted recovery still requires its + * compact JWS to be valid; losing the registry entry does not extend the signed expiry. + */ public static FirstPartyConnectContextResolution resolve( long sessionId, SessionContext sessionContext, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry) { Objects.requireNonNull( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - Optional registryContext = - firstPartyConnectContextRegistry.find(sessionId); - if (registryContext.isPresent()) { - FirstPartyConnectContext connectContext = registryContext.orElseThrow(); - return new FirstPartyConnectContextResolution( - connectContext.hasCompleteRoutingScope() ? Optional.of(connectContext) : Optional.empty(), - !connectContext.hasCompleteRoutingScope()); - } - if (sessionContext == null) { + try { + Optional registryContext = + firstPartyConnectContextRegistry.find(sessionId); + Optional persisted = + sessionContext == null + ? Optional.empty() + : sessionContext.persistedFirstPartyConnectContext(); + if (sessionContext != null && sessionContext.hasPartialPersistedFirstPartyConnectContext()) { + return new FirstPartyConnectContextResolution(Optional.empty(), true); + } + if (registryContext.isPresent()) { + FirstPartyConnectContext current = registryContext.orElseThrow(); + if (persisted.isPresent() && !current.equals(persisted.orElseThrow())) { + return new FirstPartyConnectContextResolution(Optional.empty(), true); + } + return new FirstPartyConnectContextResolution(Optional.of(current), false); + } + if (persisted.isPresent()) { + return new FirstPartyConnectContextResolution( + Optional.of(firstPartyConnectContextRegistry.requireRetained(persisted.orElseThrow())), + false); + } return new FirstPartyConnectContextResolution(Optional.empty(), false); + } catch (RuntimeException invalidOrUnavailable) { + return new FirstPartyConnectContextResolution(Optional.empty(), true); } - Optional persistedContext = - sessionContext.persistedFirstPartyConnectContext(); - return new FirstPartyConnectContextResolution( - persistedContext, sessionContext.hasPartialPersistedFirstPartyConnectContext()); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java index fa8d707640..682e6f83ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java @@ -1,69 +1,137 @@ package net.firedevops.firemud.gamesession.service; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.JwtException; +import io.micrometer.core.instrument.MeterRegistry; +import java.time.Clock; +import java.util.Objects; import java.util.Optional; -import net.firedevops.firemud.common.security.JwtClaims; -import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.FailureReason; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GatewayVerificationKeySource; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.VerificationException; import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; @Component @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "Injected configuration properties are framework-managed singletons") -public class FirstPartyConnectContextService { - private static final Logger logger = - LoggerFactory.getLogger(FirstPartyConnectContextService.class); + justification = "Configuration and authority/key sources are framework-managed dependencies") +public final class FirstPartyConnectContextService { + private static final String PARSE_FAILURES_METRIC = + "gamesession.first_party_connect_context.parse.failures"; + private static final String FAILURE_REASON_TAG = "reason"; + private static final String KEY_UNAVAILABLE = "key_unavailable"; + private static final String INVALID_ENVELOPE = "invalid_envelope"; + private static final String OWNER_UNAVAILABLE = "owner_unavailable"; + private static final String TARGET_MISMATCH = "target_mismatch"; private final FirstPartyConnectContextProperties properties; - private final JwtUtil jwtUtil; + private final GatewayVerificationKeySource keySource; + private final CanonicalPlayerRouteReadService routes; + private final Clock clock; + private final MeterRegistry meterRegistry; + @Autowired public FirstPartyConnectContextService( FirstPartyConnectContextProperties properties, - @Qualifier("firstPartyConnectContextJwtUtil") JwtUtil jwtUtil) { + GatewayVerificationKeySource keySource, + ObjectProvider routes, + MeterRegistry meterRegistry) { + this( + properties, + keySource, + routes.getIfAvailable(CanonicalPlayerRouteReadService::unavailable), + Clock.systemUTC(), + meterRegistry); + } + + public FirstPartyConnectContextService( + FirstPartyConnectContextProperties properties, + GatewayVerificationKeySource keySource, + CanonicalPlayerRouteReadService routes, + Clock clock, + MeterRegistry meterRegistry) { this.properties = properties; - this.jwtUtil = jwtUtil; + this.keySource = keySource; + this.routes = routes; + this.clock = clock; + this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry"); } public Optional parse(String token) { - if (!StringUtils.hasText(token) || !StringUtils.hasText(properties.getJwtSecret())) { + if (token == null || token.isBlank()) { + recordParseFailure(INVALID_ENVELOPE); return Optional.empty(); } + GatewayFirstPartyConnectContextEnvelope.VerifiedContext verified; try { - Claims claims = jwtUtil.parseToken(token).getPayload(); - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - claims, "first-party connect context account subject mismatch"); - return Optional.of( - new FirstPartyConnectContext( - Long.toString(routingClaims.accountId()), - routingClaims.tenantId(), - routingClaims.worldSlug(), - routingClaims.realmSlug(), - routingClaims.gameInstanceId(), - routingClaims.pointerVersion(), - requiredTextClaim(claims, "connectScopeId"), - stringClaim(claims, "connectTokenJti"), - requiredTextClaim(claims, "connectRequestId"), - stringClaim(claims, "gatewayRequestId"))); - } catch (IllegalArgumentException | JwtException ex) { - logger.warn("Rejecting invalid first-party connect context", ex); + verified = + GatewayFirstPartyConnectContextEnvelope.verify( + token, keySource, clock.millis(), properties.getAllowedClockSkewMs()); + } catch (VerificationException invalidEnvelope) { + recordParseFailure( + invalidEnvelope.reason() == FailureReason.KEY_SOURCE_UNAVAILABLE + ? KEY_UNAVAILABLE + : INVALID_ENVELOPE); + return Optional.empty(); + } catch (RuntimeException invalidOrUnavailable) { + // Neither signed payload nor key/owner details belong in ordinary logs. + recordParseFailure(INVALID_ENVELOPE); return Optional.empty(); } + CanonicalPlayableTarget target; + try { + target = routes.readCurrentTarget(verified.claims().tenantId()); + } catch (CanonicalPlayerRouteReadService.ReadUnavailableException ownerUnavailable) { + recordParseFailure(OWNER_UNAVAILABLE); + return Optional.empty(); + } catch (RuntimeException invalidOrUnavailable) { + recordParseFailure(INVALID_ENVELOPE); + return Optional.empty(); + } + if (!matches(verified.claims(), target)) { + recordParseFailure(TARGET_MISMATCH); + return Optional.empty(); + } + return Optional.of(new FirstPartyConnectContext(token, verified, target)); } - private static String stringClaim(Claims claims, String key) { - Object value = claims.get(key); - return value == null ? null : value.toString(); + private void recordParseFailure(String reason) { + meterRegistry.counter(PARSE_FAILURES_METRIC, FAILURE_REASON_TAG, reason).increment(); + } + + public FirstPartyConnectContext requireRetained(FirstPartyConnectContext retained) { + if (retained == null) { + throw new IllegalStateException("First-party context is absent"); + } + FirstPartyConnectContext current = + parse(retained.compactJws()) + .orElseThrow( + () -> new IllegalStateException("First-party context is invalid or unavailable")); + if (!current.resolvedTarget().equals(retained.resolvedTarget())) { + throw new IllegalStateException("First-party target changed"); + } + return current; } - private static String requiredTextClaim(Claims claims, String key) { - return JwtClaims.requireText(claims.get(key), key); + private static boolean matches(ContextClaims claims, CanonicalPlayableTarget target) { + // The current canonical resolver supports only public-production SHARED targets. + return target != null + && claims.tenantId().equals(target.canonicalTenantId()) + && claims.realmId().equals(target.realmId()) + && claims.worldSlug().equals(target.worldSlug()) + && claims.realmSlug().equals(target.realmSlug()) + && claims.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + && "SHARED".equals(claims.playableStateScope()) + && claims.playableStateScope().equals(target.playableStateScope()) + && claims.gameInstanceId().equals(target.canonicalGameInstanceId()) + && claims.catalogRevision().equals(Long.toString(target.catalogRevision())) + && claims.pointerVersion().equals(Long.toString(target.pointerVersion())) + && claims.playtestLifecycleId() == null + && claims.playtestStateGeneration() == null; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java index 53e28f43bb..b60b27053a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java @@ -61,6 +61,10 @@ public static SessionContext repairGenericBootstrapShell( if (shell == null) { return null; } + if (shell.firstPartyConnectContext() != null + || shell.hasPartialPersistedFirstPartyConnectContext()) { + return shell; + } List filteredRuntimePointers = runtimePointers == null ? List.of() @@ -101,7 +105,8 @@ public static SessionContext repairGenericBootstrapShell( pointer.pointerVersion(), pointer.stateScope(), normalizedShell.connectScopeId(), - normalizedShell.connectRequestId())) + normalizedShell.connectRequestId(), + normalizedShell.firstPartyConnectContext())) .orElse(clearGenericBootstrapRouting(normalizedShell)); } @@ -157,40 +162,6 @@ public static boolean sameBootstrapRoute(SessionContext existing, SessionContext normalizeScope(incoming.playableStateScope())); } - public static boolean sameBootstrapRoute( - FirstPartyConnectContext existing, - long tenantId, - long bootstrapGameInstanceId, - String worldSlug, - String realmSlug, - long pointerVersion) { - if (existing == null) { - return false; - } - if (existing.tenantId() != tenantId || existing.gameInstanceId() != bootstrapGameInstanceId) { - return false; - } - RoutingBundle existingRoutingBundle = - normalizeRoutingBundle( - existing.worldSlug(), existing.realmSlug(), Long.valueOf(existing.pointerVersion())); - RoutingBundle incomingRoutingBundle = - normalizeRoutingBundle(worldSlug, realmSlug, Long.valueOf(pointerVersion)); - if ((existingRoutingBundle == null) != (incomingRoutingBundle == null)) { - return false; - } - if (incomingRoutingBundle == null) { - return true; - } - if (!sameRoutingIdentity( - existingRoutingBundle.worldSlug(), - existingRoutingBundle.realmSlug(), - incomingRoutingBundle.worldSlug(), - incomingRoutingBundle.realmSlug())) { - return false; - } - return existingRoutingBundle.pointerVersion().equals(incomingRoutingBundle.pointerVersion()); - } - public static Optional singularCompletePointer( List pointers) { if (pointers == null) { @@ -335,7 +306,8 @@ private static SessionContext clearGenericBootstrapRouting(SessionContext shell) 0L, null, shell.connectScopeId(), - shell.connectRequestId()); + shell.connectRequestId(), + shell.firstPartyConnectContext()); } private static SessionContext normalizePartialGenericRouting(SessionContext shell) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java index 7a1a9e83cc..820d7c734a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java @@ -24,7 +24,7 @@ import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Inactive owner-only compare mutation; no context producer, credential storage or admission. */ +/** Unregistered owner-only initial-context mutations; no production qualifier or admission. */ public final class InitialGameplayLoginContextRedisClient { private static final Logger LOG = LoggerFactory.getLogger(InitialGameplayLoginContextRedisClient.class); @@ -65,6 +65,26 @@ public Optional install( } } + /** + * Creates the exact original PENDING aggregate only when its complete Redis key is physically + * absent. The script performs the absence check and SET atomically; a pre-read is never used as + * create authority. A positive result additionally requires the configured acknowledgement and + * independent physical readback under the held external qualification. + */ + public Optional createPending( + InitialGameplayLoginAttemptCoordinates coordinates) { + Objects.requireNonNull(coordinates, "Original coordinates required"); + var desired = InitialGameplayLoginContextState.pending(coordinates); + Optional acquired = acquireQualification(); + if (acquired.isEmpty()) return Optional.empty(); + try (HeldQualification held = acquired.orElseThrow()) { + return mutate(coordinates, desired, "CREATE_PENDING", held); + } catch (RuntimeException unavailable) { + warn("CREATE_PENDING", "QUALIFICATION_RELEASE_FAILED"); + return Optional.empty(); + } + } + Optional acquireQualification() { if (binding == null || catalog == null || qualification == null) { warn("QUALIFICATION", "CONFIGURATION_UNAVAILABLE"); @@ -125,15 +145,24 @@ private Optional mutate( try (StatefulRedisConnection connection = binding.openPinnedConnection()) { RedisCommands commands = requirePinned(connection); requirePrincipal(commands); - byte[] priorBytes = commands.get(key); - var prior = InitialGameplayLoginContextState.decode(priorBytes); - if (!prior.coordinates().equals(coordinates) - || "INSTALL".equals(operation) - && prior.state() != InitialGameplayLoginContextState.State.PENDING - && !(prior.state() == InitialGameplayLoginContextState.State.INSTALLED - && Arrays.equals(priorBytes, desiredBytes))) { - warn(operation, "STALE_CONTEXT"); - return Optional.empty(); + byte[] priorBytes; + if ("CREATE_PENDING".equals(operation)) { + priorBytes = new byte[0]; + if (desired.state() != InitialGameplayLoginContextState.State.PENDING) { + warn(operation, "INVALID_DESIRED_STATE"); + return Optional.empty(); + } + } else { + priorBytes = commands.get(key); + var prior = InitialGameplayLoginContextState.decode(priorBytes); + if (!prior.coordinates().equals(coordinates) + || "INSTALL".equals(operation) + && prior.state() != InitialGameplayLoginContextState.State.PENDING + && !(prior.state() == InitialGameplayLoginContextState.State.INSTALLED + && Arrays.equals(priorBytes, desiredBytes))) { + warn(operation, "STALE_CONTEXT"); + return Optional.empty(); + } } held.requireCurrent(); String loaded = commands.scriptLoad(source); @@ -199,7 +228,7 @@ private RedisScriptDescriptor requireDescriptor() { .equals( List.of( new RedisScriptDescriptor.ArgumentSpec("operation"), - new RedisScriptDescriptor.ArgumentSpec("exactPriorContextUtf8"), + new RedisScriptDescriptor.ArgumentSpec("exactPriorContextUtf8OrEmptyForCreate"), new RedisScriptDescriptor.ArgumentSpec("exactDesiredContextUtf8"))) || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER || descriptor.lossClass() != RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java index c08cd757b8..7a77cf5e88 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java @@ -71,7 +71,10 @@ private InitialGameplayLoginContextState( this.evidence = evidence; } - /** Controlled fixture seed only; the codec provides no Redis creation/reservation operation. */ + /** + * Encodes the exact desired initial value; Redis create-only authority remains in its owner + * script. + */ public static InitialGameplayLoginContextState pending( InitialGameplayLoginAttemptCoordinates coordinates) { return new InitialGameplayLoginContextState(State.PENDING, coordinates, null); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java new file mode 100644 index 0000000000..0740d01f5f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; + +/** + * One credential-bearing text LOGIN presentation transferred into the original-attempt owner. The + * owner wipes this object's mutable secret buffer at the end of its invocation; transport and + * protobuf/library copies are outside that erasure guarantee. + */ +public final class InitialGameplayLoginCredentialPresentation implements AutoCloseable { + private final String normalizedEmail; + private final String canonicalClientAddress; + private final char[] ownedSecret; + private final Object custodyMutex = new Object(); + private boolean current = true; + private boolean requestCreated; + + /** Ownership of {@code ownedSecret} transfers to this presentation. */ + InitialGameplayLoginCredentialPresentation( + String normalizedEmail, String canonicalClientAddress, char[] ownedSecret) { + this.ownedSecret = Objects.requireNonNull(ownedSecret, "Owned credential buffer required"); + try { + this.normalizedEmail = requireEmail(normalizedEmail); + this.canonicalClientAddress = requireAddress(canonicalClientAddress); + if (ownedSecret.length == 0 || ownedSecret.length > 1024) { + throw new IllegalArgumentException("Credential presentation is invalid"); + } + } catch (RuntimeException invalid) { + Arrays.fill(this.ownedSecret, '\0'); + current = false; + throw new IllegalArgumentException("Credential presentation is invalid"); + } + } + + /** + * Builds the only Authenticate envelope for these credentials and binds it to server coordinates. + * The returned protobuf is transient and must not be retained after the Account invocation. + */ + AuthenticateRequest createOriginalRequest(InitialGameplayLoginAttemptCoordinates coordinates) { + synchronized (custodyMutex) { + Objects.requireNonNull(coordinates, "Original coordinates required"); + if (!current || requestCreated) throw new CustodyLostException(); + requestCreated = true; + var request = + AuthenticateRequest.newBuilder() + .setEmail(normalizedEmail) + .setPassword(new String(ownedSecret)) + .setRequestId(coordinates.requestId().toString()) + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(coordinates.callerContextId().toString()) + .setCanonicalClientAddress(canonicalClientAddress) + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + CanonicalGameplayLoginResult.requireOriginalRequest(request); + return request; + } + } + + public boolean isCurrent() { + synchronized (custodyMutex) { + return current; + } + } + + @Override + public void close() { + synchronized (custodyMutex) { + if (current) { + current = false; + Arrays.fill(ownedSecret, '\0'); + } + } + } + + @Override + public String toString() { + return "InitialGameplayLoginCredentialPresentation[redacted]"; + } + + private static String requireEmail(String value) { + if (value == null + || value.isBlank() + || value.length() > 320 + || !value.equals(value.trim()) + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Credential presentation is invalid"); + } + return value; + } + + private static String requireAddress(String value) { + if (value == null + || value.isBlank() + || value.length() > 256 + || !value.equals(value.trim()) + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Credential presentation is invalid"); + } + return value; + } + + static final class CustodyLostException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + CustodyLostException() { + super("Original LOGIN private custody is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java new file mode 100644 index 0000000000..a107392d88 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered source composition for one credential-bearing original LOGIN invocation. Its outcome + * is non-admitting; it does not publish LOGIN wire success, bind gameplay, or recover from retained + * journal evidence. + */ +public final class InitialGameplayLoginOwner { + private static final long INITIAL_ATTEMPT_FENCE = 1L; + + private final InitialGameplayLoginContextRedisClient contexts; + private final InitialGameplayLoginCleanupOwner cleanup; + private final CanonicalGameplayLoginAccountClient account; + + public InitialGameplayLoginOwner( + InitialGameplayLoginContextRedisClient contexts, + InitialGameplayLoginCleanupOwner cleanup, + CanonicalGameplayLoginAccountClient account) { + this.contexts = Objects.requireNonNull(contexts, "Initial context owner required"); + this.cleanup = Objects.requireNonNull(cleanup, "Original cleanup owner required"); + this.account = Objects.requireNonNull(account, "Canonical Account client required"); + } + + /** + * Runs only from the current credential presentation. It reserves and independently reads back + * the original journal coordinates before create-only PENDING, invokes Account as one bounded + * original invocation (including only its permitted same-deadline retry), records only the + * verified nonsecret witness, then compare-installs that exact private result. Successful + * installation transfers the still-live private result to the receiving caller; any uncertain + * result or custody loss selects exact-original cleanup. + */ + public Outcome receive(InitialGameplayLoginCredentialPresentation credentials) { + Objects.requireNonNull(credentials, "Credential custody required"); + var coordinates = newOriginalCoordinates(); + try (credentials) { + try { + requireNoTransaction(); + requireCurrent(credentials); + InitialGameplayLoginJournalSnapshot reserved = cleanup.reserve(coordinates); + requireCoordinates(coordinates, reserved); + if (reserved.abandoned() || reserved.verifiedWitness().isPresent()) { + throw unavailable(); + } + + requireCurrent(credentials); + Optional pending = contexts.createPending(coordinates); + if (pending.isEmpty() + || pending.orElseThrow().state() != InitialGameplayLoginContextState.State.PENDING + || !coordinates.equals(pending.orElseThrow().coordinates())) { + return cleanup(coordinates, null, credentials); + } + + requireCurrent(credentials); + AuthenticateRequest originalRequest = credentials.createOriginalRequest(coordinates); + requireExactRequest(coordinates, originalRequest); + requireCurrent(credentials); + + CanonicalGameplayLoginResult verified = + account.authenticate(originalRequest, credentials::isCurrent); + boolean transferred = false; + try { + InitialGameplayLoginJournalSnapshot witnessed = + cleanup.recordVerifiedResult(coordinates, verified); + requireVerifiedWitness(coordinates, verified, witnessed); + requireCurrent(credentials); + + Optional installed = + contexts.install(coordinates, verified); + if (installed.isEmpty() + || installed.orElseThrow().state() != InitialGameplayLoginContextState.State.INSTALLED + || !coordinates.equals(installed.orElseThrow().coordinates())) { + return cleanup(coordinates, null, credentials); + } + if (!credentials.isCurrent()) { + return cleanup( + coordinates, + new InitialGameplayLoginCredentialPresentation.CustodyLostException(), + credentials); + } + Outcome outcome = Outcome.installed(coordinates, verified, cleanup); + transferred = true; + return outcome; + } catch (RuntimeException failure) { + return cleanup(coordinates, failure, credentials); + } finally { + if (!transferred) verified.close(); + } + } catch (RuntimeException failure) { + return cleanup(coordinates, failure, credentials); + } + } + } + + private Outcome cleanup( + InitialGameplayLoginAttemptCoordinates coordinates, + RuntimeException failure, + InitialGameplayLoginCredentialPresentation credentials) { + boolean custodyCurrent = credentials.isCurrent(); + InitialGameplayLoginCleanupOwner.CleanupObservation observation; + try { + requireNoTransaction(); + // Any successful result has already had one witness-append/readback attempt. Cleanup freezes + // the exact resulting presence or absence; it never re-appends evidence after ambiguity. + observation = cleanup.abandonAndRetire(coordinates); + } catch (RuntimeException unavailable) { + return Outcome.cleanup( + coordinates, + Status.CLEANUP_HELD, + failureCode(failure, custodyCurrent), + InitialGameplayLoginCleanupOwner.Status.HELD, + cleanup); + } + Status status = + switch (observation.status()) { + case HELD -> Status.CLEANUP_HELD; + case ACCOUNT_PENDING -> Status.CLEANUP_ACCOUNT_PENDING; + case ACCOUNT_RETIRED -> Status.CLEANUP_ACCOUNT_RETIRED; + case ACCOUNT_NO_TOKEN -> Status.CLEANUP_ACCOUNT_NO_TOKEN; + }; + return Outcome.cleanup( + coordinates, status, failureCode(failure, custodyCurrent), observation.status(), cleanup); + } + + private static InitialGameplayLoginAttemptCoordinates newOriginalCoordinates() { + UUID requestId = UUID.randomUUID(); + UUID callerContextId; + do { + callerContextId = UUID.randomUUID(); + } while (requestId.equals(callerContextId)); + return new InitialGameplayLoginAttemptCoordinates( + requestId, callerContextId, INITIAL_ATTEMPT_FENCE); + } + + private static void requireExactRequest( + InitialGameplayLoginAttemptCoordinates coordinates, AuthenticateRequest request) { + CanonicalGameplayLoginResult.requireOriginalRequest(request); + if (!coordinates.requestId().toString().equals(request.getRequestId()) + || !coordinates + .callerContextId() + .toString() + .equals(request.getSourceContext().getCallerContextId())) { + throw unavailable(); + } + } + + private static void requireVerifiedWitness( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult verified, + InitialGameplayLoginJournalSnapshot snapshot) { + var evidence = verified.evidence(); + var expected = + InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + requireCoordinates(coordinates, snapshot); + if (snapshot.abandoned() || !snapshot.verifiedWitness().filter(expected::equals).isPresent()) + throw unavailable(); + } + + private static void requireCoordinates( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginJournalSnapshot snapshot) { + if (snapshot == null || !coordinates.equals(snapshot.coordinates())) throw unavailable(); + } + + private static void requireCurrent(InitialGameplayLoginCredentialPresentation credentials) { + if (!credentials.isCurrent()) { + throw new InitialGameplayLoginCredentialPresentation.CustodyLostException(); + } + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static Optional failureCode(RuntimeException failure, boolean custodyCurrent) { + if (failure instanceof CanonicalGameplayLoginResult.CredentialDecisionException decision) { + return Optional.of(decision.code()); + } + if (failure instanceof io.grpc.StatusRuntimeException transport) { + if (!custodyCurrent && transport.getStatus().getCode() == io.grpc.Status.Code.CANCELLED) { + return Optional.of("CUSTODY_LOST"); + } + return Optional.of(transport.getStatus().getCode().name()); + } + if (failure instanceof InitialGameplayLoginCredentialPresentation.CustodyLostException) { + return Optional.of("CUSTODY_LOST"); + } + return failure == null ? Optional.empty() : Optional.of("LOGIN_UNAVAILABLE"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Initial credential LOGIN owner is unavailable"); + } + + public enum Status { + INSTALLED_NON_ADMITTING, + CLEANUP_HELD, + CLEANUP_ACCOUNT_PENDING, + CLEANUP_ACCOUNT_RETIRED, + CLEANUP_ACCOUNT_NO_TOKEN + } + + /** + * Original identity and lifecycle classification, plus one transferable private result only on + * the non-admitting installed outcome. The receiver owns a transferred result and must invoke the + * exact-original cleanup callback only at actual pre-admission custody loss; closing an + * untransferred outcome wipes its retained result and attempts that cleanup immediately. + */ + public static final class Outcome implements AutoCloseable { + private final InitialGameplayLoginAttemptCoordinates coordinates; + private final Status status; + private final Optional failureCode; + private final InitialGameplayLoginCleanupOwner.Status cleanupStatus; + private final InitialGameplayLoginCleanupOwner cleanupOwner; + private CanonicalGameplayLoginResult privateResult; + private CanonicalGameplayLoginResult transferredResult; + private final Object lifecycleMutex = new Object(); + private boolean resultTransferred; + private boolean closed; + private Optional custodyLossCleanup = + Optional.empty(); + + private Outcome( + InitialGameplayLoginAttemptCoordinates coordinates, + Status status, + Optional failureCode, + InitialGameplayLoginCleanupOwner.Status cleanupStatus, + CanonicalGameplayLoginResult privateResult, + InitialGameplayLoginCleanupOwner cleanupOwner) { + this.coordinates = Objects.requireNonNull(coordinates, "Original coordinates required"); + this.status = Objects.requireNonNull(status, "Outcome status required"); + this.failureCode = Objects.requireNonNull(failureCode, "Failure code option required"); + this.cleanupStatus = cleanupStatus; + this.privateResult = privateResult; + this.cleanupOwner = Objects.requireNonNull(cleanupOwner, "Original cleanup owner required"); + if ((status == Status.INSTALLED_NON_ADMITTING) + != (cleanupStatus == null && privateResult != null)) { + throw new IllegalArgumentException("Initial LOGIN outcome classification is invalid"); + } + } + + private static Outcome installed( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult privateResult, + InitialGameplayLoginCleanupOwner cleanupOwner) { + return new Outcome( + coordinates, + Status.INSTALLED_NON_ADMITTING, + Optional.empty(), + null, + privateResult, + cleanupOwner); + } + + private static Outcome cleanup( + InitialGameplayLoginAttemptCoordinates coordinates, + Status status, + Optional failureCode, + InitialGameplayLoginCleanupOwner.Status cleanupStatus, + InitialGameplayLoginCleanupOwner cleanupOwner) { + return new Outcome(coordinates, status, failureCode, cleanupStatus, null, cleanupOwner); + } + + public InitialGameplayLoginAttemptCoordinates coordinates() { + return coordinates; + } + + public Status status() { + return status; + } + + public Optional failureCode() { + return failureCode; + } + + public InitialGameplayLoginCleanupOwner.Status cleanupStatus() { + return cleanupStatus; + } + + /** Transfers the verified private result exactly once to its receiving caller. */ + public Optional takePrivateResult() { + synchronized (lifecycleMutex) { + if (closed) throw new IllegalStateException("Initial LOGIN outcome is closed"); + if (status != Status.INSTALLED_NON_ADMITTING) return Optional.empty(); + if (resultTransferred) + throw new IllegalStateException("Initial LOGIN result was transferred"); + resultTransferred = true; + CanonicalGameplayLoginResult result = privateResult; + privateResult = null; + transferredResult = result; + return Optional.of(result); + } + } + + /** + * Called only when the original pre-admission LOGIN custody is actually lost. This is not a + * retained-edge rebind or post-admission disconnect signal. It wipes this owner's retained + * result, then asks the existing owner to clean the exact original coordinates. + */ + public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { + synchronized (lifecycleMutex) { + if (status != Status.INSTALLED_NON_ADMITTING) { + throw new IllegalStateException("Only an installed original LOGIN can be abandoned"); + } + if (privateResult != null) { + privateResult.close(); + privateResult = null; + } + if (transferredResult != null) { + transferredResult.close(); + transferredResult = null; + } + closed = true; + custodyLossCleanup = Optional.of(attemptOriginalCleanup()); + return custodyLossCleanup.orElseThrow(); + } + } + + public Optional custodyLossCleanup() { + synchronized (lifecycleMutex) { + return custodyLossCleanup; + } + } + + /** + * Wipes and cleans an untransferred installed result because abandoning this owner before + * transfer loses the original private custody. After transfer, cleanup belongs to the caller + * and requires its explicit pre-admission custody-loss callback. + */ + @Override + public void close() { + synchronized (lifecycleMutex) { + if (!closed) { + closed = true; + if (privateResult != null) { + privateResult.close(); + privateResult = null; + custodyLossCleanup = Optional.of(attemptOriginalCleanup()); + } + } + } + } + + private InitialGameplayLoginCleanupOwner.CleanupObservation attemptOriginalCleanup() { + try { + var observation = cleanupOwner.abandonAndRetire(coordinates); + if (observation != null && coordinates.equals(observation.coordinates())) { + return observation; + } + } catch (RuntimeException unavailable) { + // Preserve the exact original obligation as held; no cleanup failure becomes authority. + } + return new InitialGameplayLoginCleanupOwner.CleanupObservation( + coordinates, + InitialGameplayLoginCleanupOwner.Status.HELD, + Optional.empty(), + Optional.empty()); + } + + @Override + public String toString() { + return "InitialGameplayLoginOutcome[non-admitting,redacted]"; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java index 24fd115d32..6461415571 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java @@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; @@ -128,7 +129,15 @@ private void pushOutputs( .counter( "gamesession.output.delivery.failed", "kind", output.kind().name().toLowerCase()) .increment(); - activeTransportSessionRegistry.unregister(context.sessionId(), session); + try { + // Only the owned close callback removes registration and commits disconnect cleanup. + session.close(CloseStatus.SERVER_ERROR.withReason("internal_error")); + } catch (IOException closeFailure) { + LOG.warn( + "Failed to close transport after delivery failure for session {}", + context.sessionId(), + closeFailure); + } break; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index d2ca6ff738..dc064587b7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -24,10 +24,50 @@ public record SessionContext( long pointerVersion, String playableStateScope, String connectScopeId, - String connectRequestId) + String connectRequestId, + FirstPartyConnectContext firstPartyConnectContext) implements Serializable { private static final long serialVersionUID = 1L; + public SessionContext( + long sessionId, + long tenantId, + String accountId, + String loginName, + long characterId, + String characterName, + long gameInstanceId, + String roomInstanceId, + String jwt, + String localeTag, + long bootstrapGameInstanceId, + String worldSlug, + String realmSlug, + long pointerVersion, + String playableStateScope, + String connectScopeId, + String connectRequestId) { + this( + sessionId, + tenantId, + accountId, + loginName, + characterId, + characterName, + gameInstanceId, + roomInstanceId, + jwt, + localeTag, + bootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + playableStateScope, + connectScopeId, + connectRequestId, + null); + } + public SessionContext { loginName = loginName == null ? null : loginName.trim(); characterName = characterName == null ? null : characterName.trim(); @@ -316,31 +356,32 @@ public boolean sameGameplayIdentity(SessionContext that) { } public Optional persistedFirstPartyConnectContext() { - if (!hasAccountIdentity() || tenantId <= 0) { - return Optional.empty(); - } - FirstPartyConnectContext connectContext = - new FirstPartyConnectContext( - accountId, - tenantId, - worldSlug, - realmSlug, - bootstrapGameInstanceId, - pointerVersion, - connectScopeId, - null, - connectRequestId, - null); - return connectContext.hasCompleteRoutingScope() - ? Optional.of(connectContext) - : Optional.empty(); + return Optional.ofNullable(firstPartyConnectContext); } public boolean hasPartialPersistedFirstPartyConnectContext() { - if (!hasAccountIdentity() || tenantId <= 0) { - return false; - } - boolean hasAnyPersistedSelectorField = connectScopeId != null || connectRequestId != null; - return hasAnyPersistedSelectorField && persistedFirstPartyConnectContext().isEmpty(); + return firstPartyConnectContext == null && (connectScopeId != null || connectRequestId != null); + } + + public SessionContext withFirstPartyConnectContext(FirstPartyConnectContext context) { + return new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + characterId, + characterName, + gameInstanceId, + roomInstanceId, + jwt, + localeTag, + bootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + playableStateScope, + connectScopeId, + connectRequestId, + context); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContextUnavailableException.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContextUnavailableException.java new file mode 100644 index 0000000000..7320eab409 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContextUnavailableException.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.gamesession.service; + +/** Indicates retained session context could not be read safely from its backing store. */ +public final class SessionContextUnavailableException extends IllegalStateException { + public SessionContextUnavailableException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java index 894fe751af..4f21005a9d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java @@ -67,7 +67,8 @@ private SessionContext clearGameplayBinding(SessionContext context) { 0L, null, context.connectScopeId(), - context.connectRequestId()); + context.connectRequestId(), + context.firstPartyConnectContext()); } private boolean hasCanonicalGameplayRoomBinding(SessionContext context) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java index 1ead24bcfa..cab33981a0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java @@ -28,11 +28,14 @@ public void register(long sessionId, WebSocketSession session) { } @Override - public void unregister(long sessionId, WebSocketSession session) { - sessions.computeIfPresent( - sessionId, - (ignored, registered) -> - registered.websocketSessionId().equals(session.getId()) ? null : registered); + public boolean unregister(long sessionId, WebSocketSession session) { + RegisteredSession registered = sessions.get(sessionId); + if (registered == null + || registered.session() != session && registered.session().getDelegate() != session) { + return false; + } + // Conditional removal binds the result to this exact snapshot; a concurrent replacement wins. + return sessions.remove(sessionId, registered); } @Override diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index b8ded43bcc..61deba6f1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java @@ -6,6 +6,7 @@ import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextService; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.serializer.SerializationException; @@ -18,21 +19,32 @@ public final class RedisFirstPartyConnectContextRegistry private final RedisTemplate redisTemplate; private final Duration ttl; + private final FirstPartyConnectContextService contextService; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "RedisTemplate is injected and used internally only") public RedisFirstPartyConnectContextRegistry( - RedisTemplate redisTemplate, FirstPartyConnectContextProperties properties) { + RedisTemplate redisTemplate, + FirstPartyConnectContextProperties properties, + FirstPartyConnectContextService contextService) { this.redisTemplate = redisTemplate; + this.contextService = contextService; this.ttl = Duration.ofMillis(Math.max(properties.getTtlMs(), 1L)); } @Override public void register(long sessionId, FirstPartyConnectContext connectContext) { + connectContext = contextService.requireRetained(connectContext); String key = key(sessionId); try { Object retained = valueOperations().get(key); + if (retained instanceof FirstPartyConnectContext previous) { + FirstPartyConnectContext validated = contextService.requireRetained(previous); + if (!validated.equals(connectContext)) { + throw new IllegalStateException("Retained first-party context cannot be replaced"); + } + } if (retained != null && !(retained instanceof FirstPartyConnectContext)) { throw new IllegalStateException( "Retained first-party connect context is incompatible and cannot be replaced"); @@ -47,12 +59,24 @@ public void register(long sessionId, FirstPartyConnectContext connectContext) { @Override public Optional find(long sessionId) { try { - return Optional.ofNullable((FirstPartyConnectContext) valueOperations().get(key(sessionId))); + Object retained = valueOperations().get(key(sessionId)); + if (retained == null) { + return Optional.empty(); + } + if (!(retained instanceof FirstPartyConnectContext context)) { + throw new IllegalStateException("Retained first-party context is incompatible"); + } + return Optional.of(contextService.requireRetained(context)); } catch (SerializationException | ClassCastException ex) { - return Optional.empty(); + throw new IllegalStateException("Retained first-party context is unreadable", ex); } } + @Override + public FirstPartyConnectContext requireRetained(FirstPartyConnectContext context) { + return contextService.requireRetained(context); + } + @Override public void unregister(long sessionId) { String key = key(sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java index 96178b1c8e..2fdc1cc038 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java @@ -124,7 +124,8 @@ private SessionContext updateRoom(SessionContext current, String destinationRoom current.pointerVersion(), current.playableStateScope(), current.connectScopeId(), - current.connectRequestId()); + current.connectRequestId(), + current.firstPartyConnectContext()); } private boolean roomMatches(String currentRoomId, String expectedRoomId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index 742f1aeb5b..ffcfdb386f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -10,6 +10,7 @@ import java.util.Set; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; @@ -218,7 +219,7 @@ private Optional findContextForLookup(String key) { try { return Optional.ofNullable((SessionContext) redisTemplate.opsForValue().get(key)); } catch (SerializationException | ClassCastException ex) { - return Optional.empty(); + throw new SessionContextUnavailableException("Retained session context is unreadable", ex); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 205f6998f4..8b50ddf4e2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import net.firedevops.firemud.gamesession.service.SessionIdParsing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,6 +49,7 @@ import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; +import org.springframework.web.socket.handler.WebSocketSessionDecorator; /** Handles WebSocket text commands from clients that span both Telnet and browser connections. */ @Component @@ -158,9 +160,15 @@ public void afterConnectionEstablished(WebSocketSession session) { session.getId(), resolveTransportSessionId(session), resolveTenantIdText(session)); - bootstrapSessionContext(session); + if (!bootstrapSessionContext(session)) { + return; + } parseNumericSessionId(resolveTransportSessionId(session)) .ifPresent(sessionId -> activeTransportSessionRegistry.register(sessionId, session)); + } catch (SessionContextUnavailableException unavailable) { + logger.warn( + "Unable to read retained session context during WebSocket establishment", unavailable); + closeBackendUnavailable(session); } } @@ -169,7 +177,9 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) parseNumericSessionId(resolveTransportSessionId(session)) .ifPresent( sessionId -> { - activeTransportSessionRegistry.unregister(sessionId, session); + if (!activeTransportSessionRegistry.unregister(sessionId, session)) { + return; + } firstPartyConnectContextRegistry.unregister(sessionId); promptBurstCoordinator.evict(Long.toString(sessionId)); gameplayPresenceLifecycleService.recordDisconnected( @@ -180,6 +190,12 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { + // Check ownership before logging-context projection can read or normalize incumbent state. + if ("first_party_web".equals(resolveConnectionMode(session)) + && !ownsActiveTransport(resolveTransportSessionId(session), session)) { + closeInvalidFirstPartyContext(session); + return; + } try (CombinedLoggingContext ignored = openLoggingContext(session)) { String sessionId = resolveTransportSessionId(session); if (!StringUtils.hasText(sessionId)) { @@ -192,7 +208,9 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) if (command.type() == TextCommandType.NOOP) { return; } - ensureBootstrapSessionContextIfMissing(session, sessionId); + if (!ensureBootstrapSessionContextIfMissing(session, sessionId)) { + return; + } TextCommandInterpretationResult interpretation = interpreter.interpret(sessionId, command, requiresSoloTick); TextCommand resolvedCommand = @@ -232,6 +250,10 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) maybeReplayScreenBufferAndRefreshLook( session, sessionId, command, interpretation, maybeContext); maybeCloseAfterSuccessfulLogout(session, command, interpretation); + } catch (SessionContextUnavailableException unavailable) { + logger.warn( + "Unable to read retained session context while handling WebSocket message", unavailable); + closeBackendUnavailable(session); } } @@ -242,6 +264,21 @@ private boolean parseSoloTick(WebSocketSession session) { return value != null && value.equalsIgnoreCase("true"); } + private boolean ownsActiveTransport(String sessionId, WebSocketSession session) { + try { + return parseNumericSessionId(sessionId) + .flatMap(activeTransportSessionRegistry::find) + .map( + registered -> + registered == session + || registered instanceof WebSocketSessionDecorator decorator + && decorator.getDelegate() == session) + .orElse(false); + } catch (RuntimeException unavailable) { + return false; + } + } + private String resolveTransportSessionId(WebSocketSession session) { Object cached = session.getAttributes().get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR); @@ -571,38 +608,37 @@ private boolean shouldBuffer( return true; } - private void bootstrapSessionContext(WebSocketSession session) { + private boolean bootstrapSessionContext(WebSocketSession session) { String transportSessionId = resolveTransportSessionId(session); if (!StringUtils.hasText(transportSessionId)) { - return; + return false; } - parseNumericSessionId(transportSessionId) - .ifPresent( - sessionId -> { - if ("first_party_web".equals(resolveConnectionMode(session))) { - bootstrapFirstPartySessionContext(session, sessionId); - return; - } - bootstrapGenericSessionContext(session, sessionId); - }); + Optional sessionId = parseNumericSessionId(transportSessionId); + if (sessionId.isEmpty()) { + return false; + } + if ("first_party_web".equals(resolveConnectionMode(session))) { + return bootstrapFirstPartySessionContext(session, sessionId.orElseThrow()); + } + return bootstrapGenericSessionContext(session, sessionId.orElseThrow()); } - private void ensureBootstrapSessionContextIfMissing( + private boolean ensureBootstrapSessionContextIfMissing( WebSocketSession session, String transportSessionId) { if (!StringUtils.hasText(transportSessionId)) { - return; + return true; } Optional tenantScopedContext = resolveNormalizedSessionContext(session, transportSessionId); if (tenantScopedContext.isPresent() && resolveNormalizedSessionContext(transportSessionId).isPresent()) { - return; + return true; } if (tenantScopedContext.isPresent()) { sessionContextService.save(tenantScopedContext.orElseThrow()); - return; + return true; } - bootstrapSessionContext(session); + return bootstrapSessionContext(session); } private CombinedLoggingContext openLoggingContext(WebSocketSession session) { @@ -612,11 +648,16 @@ private CombinedLoggingContext openLoggingContext(WebSocketSession session) { } RuntimeLoggingContext runtimeContext = RuntimeLoggingContext.open(runtimeIdentity, correlationId); - GameplayLoggingContext gameplayContext = - resolveNormalizedSessionContext(session, correlationId) - .map(GameplayLoggingContext::from) - .orElseGet(GameplayLoggingContext::empty); - return new CombinedLoggingContext(runtimeContext, gameplayContext); + try { + GameplayLoggingContext gameplayContext = + resolveNormalizedSessionContext(session, correlationId) + .map(GameplayLoggingContext::from) + .orElseGet(GameplayLoggingContext::empty); + return new CombinedLoggingContext(runtimeContext, gameplayContext); + } catch (RuntimeException failure) { + runtimeContext.close(); + throw failure; + } } private record CombinedLoggingContext( @@ -659,7 +700,8 @@ private void maybePersistLocaleTag(Optional maybeContext, String context.pointerVersion(), context.playableStateScope(), context.connectScopeId(), - context.connectRequestId()))); + context.connectRequestId(), + context.firstPartyConnectContext()))); } private PlayerOutput renderReconnectLook(String sessionId) { @@ -670,11 +712,11 @@ private PlayerOutput renderReconnectLook(String sessionId) { .RECONNECT_REFRESH); } - private void bootstrapGenericSessionContext(WebSocketSession session, long sessionId) { + private boolean bootstrapGenericSessionContext(WebSocketSession session, long sessionId) { Optional tenantId = resolveTenantId(session); Optional bootstrapGameInstanceId = resolveBootstrapGameInstanceId(session); if (tenantId.isEmpty() || bootstrapGameInstanceId.isEmpty()) { - return; + return true; } List currentPointers; try { @@ -684,7 +726,7 @@ private void bootstrapGenericSessionContext(WebSocketSession session, long sessi } catch (RuntimeException ex) { logger.warn("Unable to resolve runtime pointer for generic bootstrap", ex); closeAdmissionPointerAuthorityUnavailable(session); - return; + return false; } Optional existing = sessionAuthenticationService.resolveUnverifiedSessionContext(tenantId.get(), sessionId); @@ -708,86 +750,61 @@ private void bootstrapGenericSessionContext(WebSocketSession session, long sessi currentPointers); if (existing.isPresent()) { maybeRefreshBootstrapShell(existing.orElseThrow(), incomingShell); - return; + return true; } sessionContextService.save(incomingShell); + return true; } - private void bootstrapFirstPartySessionContext(WebSocketSession session, long sessionId) { + private boolean bootstrapFirstPartySessionContext(WebSocketSession session, long sessionId) { Optional maybeContext = firstPartyConnectContextService.parse(resolveConnectContext(session)); if (maybeContext.isEmpty()) { closeInvalidFirstPartyContext(session); - return; + return false; } var connectContext = maybeContext.orElseThrow(); - List currentPointers; - try { - currentPointers = - gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( - connectContext.tenantId(), connectContext.gameInstanceId()); - } catch (RuntimeException ex) { - logger.warn("Unable to resolve runtime pointer for first-party bootstrap", ex); - closeAdmissionPointerAuthorityUnavailable(session); - return; - } - Optional currentPointer = - GameplayAdmissionPointerSnapshots.singularCompletePointer(currentPointers); - if (currentPointer.isEmpty()) { - closeAdmissionPointerAuthorityUnavailable(session); - return; - } - if (!GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( - currentPointers, - connectContext.tenantId(), - connectContext.gameInstanceId(), - connectContext.worldSlug(), - connectContext.realmSlug(), - connectContext.pointerVersion(), - currentPointer.orElseThrow().stateScope())) { - closeInvalidFirstPartyContext(session); - return; - } - String playableStateScope = currentPointer.orElseThrow().stateScope(); + // parse has already composed the unique catalog, OPEN proof and RUNNING launch association. + // The private handles below come from that owner result, never from headers or UUID parsing. try { + SessionContext shell = + bootstrapShell( + sessionId, + connectContext.gameSessionTenantId(), + connectContext.runtimeGameInstanceId(), + connectContext.worldSlug(), + connectContext.realmSlug(), + connectContext.pointerVersion(), + connectContext.resolvedTarget().playableStateScope(), + connectContext.connectScopeId(), + connectContext.connectRequestId(), + resolveLocaleTag(session)) + .withFirstPartyConnectContext(connectContext); + Optional existing = sessionContextService.findBySessionId(sessionId); + if (existing.isPresent() && !shell.equals(existing.orElseThrow())) { + closeInvalidFirstPartyContext(session); + return false; + } firstPartyConnectContextRegistry.register(sessionId, connectContext); - } catch (IllegalStateException ex) { - logger.warn( - "Unable to register first-party connect context because retained state is invalid"); + try { + sessionContextService.save(shell); + } catch (RuntimeException saveFailure) { + try { + firstPartyConnectContextRegistry.unregister(sessionId); + } catch (RuntimeException cleanupFailure) { + if (cleanupFailure != saveFailure) { + saveFailure.addSuppressed(cleanupFailure); + } + } + throw saveFailure; + } + return true; + } catch (SessionContextUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException invalidOrUnavailable) { closeInvalidFirstPartyContext(session); - return; - } - Optional existing = - sessionAuthenticationService.resolveUnverifiedSessionContext( - connectContext.tenantId(), sessionId); - if (existing.isPresent()) { - maybeRefreshBootstrapShell( - existing.orElseThrow(), - bootstrapShell( - sessionId, - connectContext.tenantId(), - connectContext.gameInstanceId(), - connectContext.worldSlug(), - connectContext.realmSlug(), - connectContext.pointerVersion(), - playableStateScope, - connectContext.connectScopeId(), - connectContext.connectRequestId(), - resolveLocaleTag(session))); - return; + return false; } - sessionContextService.save( - bootstrapShell( - sessionId, - connectContext.tenantId(), - connectContext.gameInstanceId(), - connectContext.worldSlug(), - connectContext.realmSlug(), - connectContext.pointerVersion(), - playableStateScope, - connectContext.connectScopeId(), - connectContext.connectRequestId(), - resolveLocaleTag(session))); } private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext incomingShell) { @@ -822,7 +839,8 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext existing.pointerVersion(), incomingShell.playableStateScope(), incomingShell.connectScopeId(), - incomingShell.connectRequestId())); + incomingShell.connectRequestId(), + existing.firstPartyConnectContext())); return; } if (localeChanged || selectorChanged) { @@ -844,7 +862,8 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext existing.pointerVersion(), existing.playableStateScope(), incomingShell.connectScopeId(), - incomingShell.connectRequestId())); + incomingShell.connectRequestId(), + existing.firstPartyConnectContext())); } return; } @@ -867,7 +886,8 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext incomingShell.pointerVersion(), incomingShell.playableStateScope(), incomingShell.connectScopeId(), - incomingShell.connectRequestId())); + incomingShell.connectRequestId(), + existing.firstPartyConnectContext())); } private boolean hasAuthenticatedOrGameplayBinding(SessionContext context) { @@ -926,6 +946,14 @@ private void closeAdmissionPointerAuthorityUnavailable(WebSocketSession session) } } + private void closeBackendUnavailable(WebSocketSession session) { + try { + session.close(new CloseStatus(1013, "backend_unavailable")); + } catch (IOException ex) { + logger.warn("Failed to close session while retained context was unavailable", ex); + } + } + private Optional parseNumericSessionId(String text) { return SessionIdParsing.parse(text).optionalValue(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java index 5c582de7b2..37404a76e8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java @@ -53,6 +53,19 @@ public boolean beforeHandshake( bootstrapGameInstanceId, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); attributes.put(SESSION_ID_ATTR, sessionId); + boolean firstParty = + "first_party_web".equals(request.getHeaders().getFirst(CONNECTION_MODE_HEADER)) + || StringUtils.hasText(request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); + if (firstParty) { + attributes.put(CONNECTION_MODE_ATTR, "first_party_web"); + attributes.put(CONNECT_CONTEXT_ATTR, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); + attributes.put( + LOCALE_ATTR, + resolveLocaleTag( + request.getHeaders().getFirst(LOCALE_HEADER), + request.getHeaders().getFirst(ACCEPT_LANGUAGE_HEADER))); + return true; + } attributes.put(BOOTSTRAP_GAME_INSTANCE_ATTR, bootstrapGameInstanceId); attributes.put(TENANT_ID_ATTR, request.getHeaders().getFirst(TENANT_HEADER)); attributes.put(WORLD_SLUG_ATTR, request.getHeaders().getFirst(WORLD_SLUG_HEADER)); 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 cc917e432a..c9a85edc25 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -48,7 +48,6 @@ error.equipment.invalid-command=Unsupported equipment command. error.help.unknown-topic=Unknown help topic: {topic} message.login.success=Logged in as {loginName} message.login.code-sent=If that account is allowed to log in, a code has been sent. Use LOGIN . -message.login.first-party-success=Logged in as first-party account {accountId} notice.world.entered=Entered world: {worldName}{characterSuffix} communication.say.actor=You say, "{message}" communication.whisper.actor=You whisper to {targetName}, "{message}" 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 7df38878ab..b6692bab00 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 @@ -48,7 +48,6 @@ error.equipment.invalid-command=Commande d’équipement non prise en charge. error.help.unknown-topic=Sujet d’aide inconnu : {topic} message.login.success=Connecte en tant que {loginName} message.login.code-sent=Si ce compte est autorise a se connecter, un code a ete envoye. Utilisez LOGIN . -message.login.first-party-success=Connecte en tant que compte first-party {accountId} notice.world.entered=Entree dans le monde : {worldName}{characterSuffix} label.room=Salle : label.short=Court : diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua index d1acdf6f27..0194acdebc 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua @@ -1,5 +1,5 @@ --- Owner-only compare mutation. No context creation, expiry, or authenticated gameplay admission. --- KEYS[1] exact tenantless original context. ARGV operation, exact prior bytes, exact desired bytes. +-- Owner-only original-context creation and exact compare mutation. No expiry or admission. +-- KEYS[1] exact tenantless original context. ARGV operation, prior bytes (empty for create), desired bytes. local prefix = 'session:game:initial-context:v1:' local maxBytes = 32768 local function uuid(value) @@ -46,10 +46,19 @@ local function envelope(bytes) end if #KEYS ~= 1 or #ARGV ~= 3 then return -2 end local operation = ARGV[1] -if operation ~= 'INSTALL' and operation ~= 'CLOSE' then return -2 end -local before = envelope(ARGV[2]) +if operation ~= 'CREATE_PENDING' and operation ~= 'INSTALL' and operation ~= 'CLOSE' then return -2 end local after = envelope(ARGV[3]) -if not before or not after or KEYS[1] ~= prefix .. before.callerContextId +if not after or KEYS[1] ~= prefix .. after.callerContextId then return -2 end +if operation == 'CREATE_PENDING' then + if ARGV[2] ~= '' or after.state ~= 'PENDING' then return -2 end + -- TYPE is atomic with the write in this script and rejects every existing physical value, + -- including malformed, expiring, replaced, or otherwise unqualified state. + if redis.call('TYPE', KEYS[1]).ok ~= 'none' then return -1 end + redis.call('SET', KEYS[1], ARGV[3]) + return 1 +end +local before = envelope(ARGV[2]) +if not before or KEYS[1] ~= prefix .. before.callerContextId or before.requestId ~= after.requestId or before.callerContextId ~= after.callerContextId or before.expectedAttemptFence ~= after.expectedAttemptFence then return -2 end if operation == 'INSTALL' then diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json index e7110d70e1..676fe2a07b 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.initial-context-cas.v1", "resourcePath": "redis/lua/game-session-initial-context-cas.lua", - "sha256": "d5cf30a901eb31d19934ed77cad41dc78c6b70d98afa735e651c2319585cea0b", + "sha256": "2843fae8ec73a57963d16ba840adab41613e6460858bd3f349fa012409b27c1f", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -17,7 +17,7 @@ "name": "operation" }, { - "name": "exactPriorContextUtf8" + "name": "exactPriorContextUtf8OrEmptyForCreate" }, { "name": "exactDesiredContextUtf8" @@ -43,7 +43,7 @@ ], "resetSensitivity": "CLUSTER", "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", - "tailLossBehavior": "All scoped resets invalidate this tenantless family with declared global impact. Missing, changed, lost ACK or reset/restore ambiguity remains held. External recovery qualification excludes restore and promotion through closure continuation; neither SQL receipts nor absence reconstruct context.", + "tailLossBehavior": "All scoped resets invalidate this tenantless family with declared global impact. CREATE_PENDING creates only the exact newly reserved original when its complete key is physically absent under current external qualification; it never adopts or overwrites existing, expiring, malformed, replaced, closed, or uncertain state. Install and closure never recreate missing state. Missing, changed, lost ACK or reset/restore ambiguity remains held. External recovery qualification excludes restore and promotion through closure continuation; neither SQL receipts nor absence reconstruct context.", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index d6f66337f3..d7f9453d34 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -2,7 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import com.fasterxml.jackson.databind.JsonNode; import java.net.URI; import java.time.Duration; import java.util.List; @@ -12,7 +11,6 @@ import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; import net.firedevops.firemud.gamesession.testsupport.GameplayEntityAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplaySocialAssertions; -import net.firedevops.firemud.gamesession.testsupport.GameplayStructuredCommandAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.socialgroups.v1.ChatType; @@ -22,6 +20,8 @@ import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.core.JdbcTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -38,7 +38,6 @@ class CommunicationWebSocketCrossServiceTest { private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; - private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; @Container static final PostgreSQLContainer POSTGRES = @@ -423,279 +422,6 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } - @Test - void websocketFirstPartySayUsesStructuredCommunicationMetadata() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("say-first-party")) { - int baseline = client.responses().size(); - client.send("SAY hello travelers"); - JsonNode say = awaitStructuredCommand(client, baseline, "SAY"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - say, "SAY", "say", "SOCIAL", "COMMUNICATION"); - assertThat(say.path("accepted").asBoolean()).isTrue(); - } - } - - @Test - void websocketFirstPartyConfiguredAuthoredAliasDoesNotBypassAdmittedDefinitions() - throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("authored-first-party")) { - int baseline = client.responses().size(); - client.send("SALUTE captain"); - JsonNode unknown = awaitStructuredCommand(client, baseline, "UNKNOWN"); - assertThat(unknown.path("accepted").asBoolean()).isFalse(); - assertThat(unknown.path("errorCode").asText()).isEqualTo("UNKNOWN_COMMAND"); - } - } - - @Test - void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("friends-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS"); - JsonNode friends = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode friendsPayload = requirePayload(friends, "friends_view"); - assertThat(friends.path("accepted").asBoolean()).isTrue(); - assertThat(friendsPayload.path("filter").asText()).isEqualTo("ALL"); - assertThat(friendsPayload.path("friends").get(0).path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - assertThat(friendsPayload.path("friends").get(0).path("playableStateScope").asText()) - .isEqualTo("SHARED"); - - baseline = client.responses().size(); - client.send("FRIENDS SHOW #1"); - JsonNode detail = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode detailPayload = requirePayload(detail, "friend_detail_view"); - assertThat(detailPayload.path("friend").path("ordinal").asInt()).isEqualTo(1); - assertThat(detailPayload.path("friend").path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - - baseline = client.responses().size(); - client.send("FRIENDS SUMMARY"); - JsonNode summary = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode summaryPayload = requirePayload(summary, "friend_roster_summary_view"); - assertThat(summaryPayload.path("totalCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("onlineCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("sharedCount").asInt()).isEqualTo(1); - } - } - - @Test - void websocketFirstPartyFriendsVisibilityUsesStructuredPolicyPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-visibility-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS VISIBILITY"); - JsonNode visibility = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode visibilityPayload = requirePayload(visibility, "friend_presence_policy_view"); - assertThat(visibilityPayload.path("currentPolicy").asText()).isEqualTo("FRIENDS_ONLY"); - - baseline = client.responses().size(); - client.send("FRIENDS VISIBILITY PRIVATE"); - JsonNode updated = awaitStructuredCommand(client, baseline, "FRIENDS"); - requirePayload(updated, "notice"); - JsonNode updatedPolicy = requirePayload(updated, "friend_presence_policy_view"); - assertThat(updatedPolicy.path("currentPolicy").asText()).isEqualTo("PRIVATE"); - } - - GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); - GameplaySocialAssertions.assertUpdateVisibilityRequest( - socialStub().lastUpdateVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); - } - - @Test - void websocketFirstPartyFriendsMutationsUseStructuredCanonicalPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("friends-add-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS ADD 77"); - JsonNode added = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode addPayload = requirePayload(added, "friend_mutation_result"); - assertThat(addPayload.path("action").asText()).isEqualTo("ADD"); - assertThat(addPayload.path("friendAccountId").asLong()).isEqualTo(77L); - assertThat(addPayload.path("displayName").asText()).isEqualTo("Friend #77"); - } - - prepareGameInstance(); - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-remove-name-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS REMOVE Sora"); - JsonNode removedByName = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode removeByNamePayload = requirePayload(removedByName, "friend_mutation_result"); - assertThat(removeByNamePayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByNamePayload.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); - assertThat(removeByNamePayload.path("displayName").asText()).isEqualTo("Sora"); - assertThat(removeByNamePayload.path("characterName").asText()).isEqualTo("Sora"); - } - - prepareGameInstance(); - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-remove-ordinal-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS REMOVE #1"); - JsonNode removedByOrdinal = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode removeByOrdinalPayload = requirePayload(removedByOrdinal, "friend_mutation_result"); - assertThat(removeByOrdinalPayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByOrdinalPayload.path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - assertThat(removeByOrdinalPayload.path("ordinal").asInt()).isEqualTo(1); - } - } - - @Test - void websocketFirstPartyInventoryViewsExposeTypedItemMetadata() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("inventory-first-party")) { - int baseline = client.responses().size(); - client.send("GET Torch"); - JsonNode pickup = awaitStructuredCommand(client, baseline, "GET"); - assertThat(pickup.path("accepted").asBoolean()) - .withFailMessage(pickup.toPrettyString()) - .isTrue(); - JsonNode pickupMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(pickupMutation.path("action").asText()).isEqualTo("GET"); - assertThat(pickupMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(pickupMutation.path("source").path("kind").asText()).isEqualTo("ROOM_GROUND"); - assertThat(pickupMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - List pickupViews = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayloads( - client, baseline, "inventory_view", 2); - assertThat(pickupViews).hasSize(2); - JsonNode carriedInventory = requireInventoryViewBySource(pickupViews, "INVENTORY"); - assertThat(carriedInventory.path("entries")).hasSize(3); - JsonNode pickedUpTorch = requireInventoryEntryByVisibleRef(carriedInventory, "torch#1"); - assertThat(pickedUpTorch.path("itemName").asText()).isEqualTo("Torch"); - JsonNode roomGroundInventory = requireInventoryViewBySource(pickupViews, "ROOM_GROUND"); - assertThat(roomGroundInventory.path("entries")).hasSize(1); - assertThat(roomGroundInventory.path("entries").get(0).path("visibleRef").asText()) - .isEqualTo("backpack#1"); - assertThat(roomGroundInventory.path("entries").get(0).path("itemName").asText()) - .isEqualTo("Backpack"); - - baseline = client.responses().size(); - client.send("CONTAINER Backpack"); - JsonNode container = awaitStructuredCommand(client, baseline, "CONTAINER"); - assertThat(container.path("accepted").asBoolean()) - .withFailMessage(container.toPrettyString()) - .isTrue(); - JsonNode containerPayload = requirePayload(container, "inventory_view"); - assertThat(containerPayload.path("source").asText()).isEqualTo("CONTAINER"); - assertThat(containerPayload.path("context").path("displayName").asText()) - .isEqualTo("Backpack"); - assertThat(containerPayload.path("context").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(containerPayload.path("entries")).hasSize(1); - assertThat(containerPayload.path("entries").get(0).path("itemName").asText()) - .isEqualTo("Ration"); - assertThat(containerPayload.path("entries").get(0).path("visibleRef").asText()) - .isEqualTo("ration#1"); - - baseline = client.responses().size(); - client.send("PUT Torch INTO Backpack"); - JsonNode put = awaitStructuredCommand(client, baseline, "PUT"); - assertThat(put.path("accepted").asBoolean()).withFailMessage(put.toPrettyString()).isTrue(); - JsonNode putMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(putMutation.path("action").asText()).isEqualTo("PUT"); - assertThat(putMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(putMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(putMutation.path("target").path("kind").asText()).isEqualTo("CONTAINER"); - assertThat(putMutation.path("target").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(putMutation.path("target").path("visibleRef").asText()).isEqualTo("backpack#1"); - - baseline = client.responses().size(); - client.send("TAKE Torch FROM Backpack"); - JsonNode take = awaitStructuredCommand(client, baseline, "TAKE"); - assertThat(take.path("accepted").asBoolean()).withFailMessage(take.toPrettyString()).isTrue(); - JsonNode takeMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(takeMutation.path("action").asText()).isEqualTo("TAKE"); - assertThat(takeMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(takeMutation.path("source").path("kind").asText()).isEqualTo("CONTAINER"); - assertThat(takeMutation.path("source").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(takeMutation.path("source").path("visibleRef").asText()).isEqualTo("backpack#1"); - assertThat(takeMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - - baseline = client.responses().size(); - client.send("DROP Torch"); - JsonNode drop = awaitStructuredCommand(client, baseline, "DROP"); - assertThat(drop.path("accepted").asBoolean()).withFailMessage(drop.toPrettyString()).isTrue(); - JsonNode dropMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(dropMutation.path("action").asText()).isEqualTo("DROP"); - assertThat(dropMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(dropMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(dropMutation.path("target").path("kind").asText()).isEqualTo("ROOM_GROUND"); - - baseline = client.responses().size(); - client.send("WEAR Leather Cap"); - JsonNode wear = awaitStructuredCommand(client, baseline, "WEAR"); - assertThat(wear.path("accepted").asBoolean()).withFailMessage(wear.toPrettyString()).isTrue(); - JsonNode wearMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(wearMutation.path("action").asText()).isEqualTo("WEAR"); - assertThat(wearMutation.path("item").path("visibleRef").asText()).isEqualTo("cap#1"); - assertThat(wearMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(wearMutation.path("target").path("kind").asText()).isEqualTo("EQUIPMENT"); - assertThat(wearMutation.path("target").path("slot").asText()).isEqualTo("HEAD"); - - baseline = client.responses().size(); - client.send("REMOVE HEAD"); - JsonNode remove = awaitStructuredCommand(client, baseline, "REMOVE"); - assertThat(remove.path("accepted").asBoolean()) - .withFailMessage(remove.toPrettyString()) - .isTrue(); - JsonNode removeMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(removeMutation.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeMutation.path("item").path("visibleRef").asText()).isEqualTo("cap#1"); - assertThat(removeMutation.path("source").path("kind").asText()).isEqualTo("EQUIPMENT"); - assertThat(removeMutation.path("source").path("slot").asText()).isEqualTo("HEAD"); - assertThat(removeMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - - baseline = client.responses().size(); - client.send("EQUIPMENT"); - JsonNode equipment = awaitStructuredCommand(client, baseline, "EQUIPMENT"); - assertThat(equipment.path("accepted").asBoolean()) - .withFailMessage(equipment.toPrettyString()) - .isTrue(); - JsonNode equipmentPayload = requirePayload(equipment, "inventory_view"); - assertThat(equipmentPayload.path("source").asText()).isEqualTo("EQUIPMENT"); - assertThat(equipmentPayload.path("entries")).isEmpty(); - } - } - @Test void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Exception { ensureTestServicesStarted(); @@ -881,8 +607,6 @@ private static synchronized void ensureTestServicesStarted() throws Exception { .mapAccountId("nyx@example.com", NYX_ACCOUNT_ID) .withInitialRoomEntities(ChatTestFixtures.sampleEntities()) .withSocialEnabled(true) - .withGameSessionProps( - Map.of("firemud.gateway.connect-context.jwt-secret", FIRST_PARTY_CONNECT_SECRET)) .withInitialFriendPresenceResponse( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( @@ -962,94 +686,10 @@ private GameplayWebSocketDriver openReadySessionClient(long sessionId, String pr READY_LOOK_TEXT); } - private GameplayWebSocketDriver openFirstPartyGameplayClient(String transportSessionId) - throws Exception { - GameplayWebSocketDriver client = openFirstPartyClient(transportSessionId); - client.send("LOGIN"); - JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - login, "LOGIN", "login", "META", "SESSION"); - assertThat(login.path("accepted").asBoolean()).withFailMessage(login.toPrettyString()).isTrue(); - client.send("PLAY demo"); - JsonNode play = awaitStructuredCommand(client, 1, "PLAY"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - play, "PLAY", "play", "META", "SESSION"); - assertThat(play.path("accepted").asBoolean()).withFailMessage(play.toPrettyString()).isTrue(); - int readinessBaseline = client.responses().size(); - client.send("LOOK"); - JsonNode look = awaitStructuredCommand(client, readinessBaseline, "LOOK"); - assertThat(look.path("accepted").asBoolean()).withFailMessage(look.toPrettyString()).isTrue(); - return client; - } - private URI gameSessionWebSocketUrl() { return URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); } - private GameplayWebSocketDriver openFirstPartyClient(String transportSessionId) { - return GameplayWebSocketDriver.connectFirstPartyWeb( - URI.create("ws://localhost:" + gameSession().port() + "/ws/game"), - COMMAND_WAIT, - transportSessionId, - FIRST_PARTY_CONNECT_SECRET, - Long.toString(ACCOUNT_ID), - Map.of( - "accountId", - Long.toString(ACCOUNT_ID), - "tenantId", - Long.toString(TENANT_ID), - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - Long.toString(DEMO_WORLD_INSTANCE_ID), - "pointerVersion", - "1", - "connectScopeId", - "scope-" + transportSessionId, - "connectTokenJti", - "connect-jti-" + transportSessionId, - "connectRequestId", - "connect-req-" + transportSessionId, - "gatewayRequestId", - "gateway-req-" + transportSessionId)); - } - - private JsonNode awaitStructuredCommand( - GameplayWebSocketDriver client, int responseBaseline, String commandType) throws Exception { - return GameplayStructuredCommandAssertions.awaitStructuredCommand( - client, responseBaseline, commandType); - } - - private JsonNode requirePayload(JsonNode envelope, String payloadType) { - return GameplayStructuredCommandAssertions.requirePayload(envelope, payloadType); - } - - private List requirePayloads(JsonNode envelope, String payloadType) { - return GameplayStructuredCommandAssertions.requirePayloads(envelope, payloadType); - } - - private JsonNode requireInventoryViewBySource(List payloads, String source) { - return payloads.stream() - .filter(payload -> source.equals(payload.path("source").asText())) - .findFirst() - .orElseThrow( - () -> - new AssertionError( - "Missing inventory_view source=" + source + " in payloads: " + payloads)); - } - - private JsonNode requireInventoryEntryByVisibleRef(JsonNode inventory, String visibleRef) { - for (JsonNode entry : inventory.path("entries")) { - if (visibleRef.equals(entry.path("visibleRef").asText())) { - return entry; - } - } - throw new AssertionError( - "Missing inventory entry visibleRef=" + visibleRef + " in view: " + inventory); - } - private static CrossServiceAppHarness.GameSessionHolder gameSession() { return STACK.gameSession(); } @@ -1062,4 +702,46 @@ private static net.firedevops.firemud.gamesession.test.stubs.SocialGroupsStubSer entityStub() { return STACK.entityStub(); } + + @ParameterizedTest + @ValueSource(strings = {"", "not-a-valid-context", "incomplete.context"}) + void unqualifiedFirstPartyTransportDeniesBeforeCommunicationFriendsOrInventoryEffects( + String context) throws Exception { + ensureTestServicesStarted(); + prepareGameInstance(); + var priorChat = socialStub().lastRequest(); + var priorFriends = socialStub().lastSummaryRequest(); + var priorFriendMutation = socialStub().lastRemoveFriendByOrdinalRequest(); + var priorVisibility = socialStub().lastUpdateVisibilityRequest(); + var priorPickup = entityStub().lastPickupRequest(); + var priorWear = entityStub().lastWearRequest(); + var priorRemove = entityStub().lastRemoveRequest(); + var sessions = + gameSession().bean(net.firedevops.firemud.gamesession.service.SessionContextService.class); + assertThat(sessions.findBySessionId(91001L)).isEmpty(); + try (GameplayWebSocketDriver client = + GameplayWebSocketDriver.connect( + gameSessionWebSocketUrl(), + COMMAND_WAIT, + Map.of( + "X-Firemud-Connection-Mode", + "first_party_web", + "X-Firemud-Transport-Session-Id", + "91001", + "X-Firemud-Connect-Context", + context))) { + var close = client.awaitClosed(); + assertThat(close.statusCode()).isEqualTo(1008); + assertThat(close.reason()).isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(client.responses()).isEmpty(); + } + assertThat(sessions.findBySessionId(91001L)).isEmpty(); + assertThat(socialStub().lastRequest()).isEqualTo(priorChat); + assertThat(socialStub().lastSummaryRequest()).isEqualTo(priorFriends); + assertThat(socialStub().lastRemoveFriendByOrdinalRequest()).isEqualTo(priorFriendMutation); + assertThat(socialStub().lastUpdateVisibilityRequest()).isEqualTo(priorVisibility); + assertThat(entityStub().lastPickupRequest()).isEqualTo(priorPickup); + assertThat(entityStub().lastWearRequest()).isEqualTo(priorWear); + assertThat(entityStub().lastRemoveRequest()).isEqualTo(priorRemove); + } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index ce3c40a7fa..626b7403db 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -28,8 +28,10 @@ import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryRetentionSweepJob; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.impl.TickScheduler; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.FiremudAuthTestProperties; import net.firedevops.firemud.test.HttpTestSupport; @@ -66,6 +68,7 @@ "firemud.auth.http.public-routes[0].method=GET", "firemud.auth.http.public-routes[0].path-pattern=/ping" }) +@MockitoBean(types = {TickScheduler.class, PlayerCommandHistoryRetentionSweepJob.class}) class GameSessionApplicationIntegrationTest { private static final String OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = "6bf9e6d0-7f6b-4c85-b75e-d65949694f13"; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRedisIntegrationTest.java new file mode 100644 index 0000000000..1430da35dc --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRedisIntegrationTest.java @@ -0,0 +1,353 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.RedisProperties; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.AuthorityTuple; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GatewaySigningKey; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.GatewayVerificationKeySource; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.TenantBillingCutoff; +import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.impl.RedisFirstPartyConnectContextRegistry; +import net.firedevops.firemud.gamesession.service.impl.RedisSessionContextService; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical retention proof with controlled keys/owner results, not producer or admission proof. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class FirstPartyConnectContextRedisIntegrationTest { + private static final long NOW = 1_800_000_000_000L; + private static final String REGISTRY_KEY = "sessionctx:first-party:91:connect-context"; + private static final UUID ACCOUNT = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID REALM = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID NAMESPACE = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID INSTANCE = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private LettuceConnectionFactory connectionFactory; + private RedisTemplate template; + private KeyPair keys; + private FirstPartyConnectContextProperties properties; + private GatewayVerificationKeySource keySource; + private FirstPartyConnectContextService producerView; + private FirstPartyConnectContext original; + + @BeforeEach + void setUp() throws Exception { + connectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(REDIS.getHost(), REDIS.getMappedPort(6379))); + connectionFactory.afterPropertiesSet(); + template = + new DatabaseAutoConfiguration(new PostgresProperties(), new RedisProperties()) + .redisTemplate(connectionFactory); + template.afterPropertiesSet(); + template.execute( + (RedisCallback) + connection -> { + connection.serverCommands().flushDb(); + return null; + }); + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keys = generator.generateKeyPair(); + properties = new FirstPartyConnectContextProperties(); + // Redis retention remains present after signed expiry so expiry denial needs no wall-clock + // sleep. + properties.setTtlMs(120_000L); + keySource = kid -> "gateway-test".equals(kid) ? (RSAPublicKey) keys.getPublic() : null; + producerView = reader(keySource, NOW, target(17L)); + original = producerView.parse(token()).orElseThrow(); + } + + @AfterEach + void tearDown() { + if (connectionFactory != null) { + connectionFactory.destroy(); + } + } + + @Test + void productionSerializerRetainsExactBytesAndFreshReaderRebuildsVerifiedView() { + registry(producerView).register(91L, original); + byte[] storedBytes = rawValue(REGISTRY_KEY); + assertThat(storedBytes).isNotEmpty(); + FirstPartyConnectContext deserialized = + (FirstPartyConnectContext) template.opsForValue().get(REGISTRY_KEY); + assertThat(deserialized).isEqualTo(original).isNotSameAs(original); + assertThatThrownBy(deserialized::claims).isInstanceOf(IllegalStateException.class); + + FirstPartyConnectContextService freshService = reader(keySource, NOW, target(17L)); + FirstPartyConnectContext rebuilt = registry(freshService).find(91L).orElseThrow(); + assertThat(rebuilt.compactJws()).isEqualTo(original.compactJws()); + assertThat(rebuilt.resolvedTarget()).isEqualTo(original.resolvedTarget()); + assertThat(rebuilt.claims()).isEqualTo(original.claims()); + assertThat(rebuilt.claims().authorityTuple()).isEqualTo(source().authorityTuple()); + assertThat(rebuilt.claims().membershipVersion()).isEqualTo(source().membershipVersion()); + assertThat(rawValue(REGISTRY_KEY)).containsExactly(storedBytes); + } + + @Test + void completeSessionStorageSurvivesRegistryExpiryWithoutReconstructingSelectorFragments() { + RedisSessionContextService sessions = new RedisSessionContextService(template, 120_000L); + SessionContext shell = + new SessionContext( + 91L, + 22L, + null, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 41L, + "demo", + "production", + 17L, + "SHARED", + "scope-1", + "request-1") + .withFirstPartyConnectContext(original); + sessions.save(shell); + RedisSessionContextService freshSessions = new RedisSessionContextService(template, 120_000L); + SessionContext retained = freshSessions.findBySessionId(91L).orElseThrow(); + assertThat(retained).isEqualTo(shell).isNotSameAs(shell); + assertThat(freshSessions.findByTenantAndSessionId(22L, 91L)).contains(retained); + assertThatThrownBy(() -> retained.firstPartyConnectContext().claims()) + .isInstanceOf(IllegalStateException.class); + var freshRegistry = registry(reader(keySource, NOW, target(17L))); + assertThat(freshRegistry.find(91L)).isEmpty(); + var resolution = FirstPartyConnectContextResolution.resolve(91L, retained, freshRegistry); + assertThat(resolution.invalid()).isFalse(); + assertThat(resolution.connectContext().orElseThrow().claims()).isEqualTo(original.claims()); + assertThat(resolution.connectContext().orElseThrow().compactJws()) + .isEqualTo(original.compactJws()); + } + + @Test + void malformedPhysicalBytesDenyReadAndReplacementWithoutDeletingEvidenceOrFallingBack() { + byte[] malformed = new byte[] {1, 2, 3, 4}; + putRaw(REGISTRY_KEY, malformed); + var registry = registry(reader(keySource, NOW, target(17L))); + assertThatThrownBy(() -> registry.find(91L)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> registry.register(91L, original)) + .isInstanceOf(IllegalStateException.class); + var retained = + new SessionContext(91L, 22L, null, 0L, 0L, (String) null) + .withFirstPartyConnectContext(original); + assertThat(FirstPartyConnectContextResolution.resolve(91L, retained, registry).invalid()) + .isTrue(); + assertThat(rawValue(REGISTRY_KEY)).containsExactly(malformed); + } + + @Test + void oldIncompleteRetainedShapeDeniesRatherThanBeingReplacedOrReconstructed() { + template + .opsForValue() + .set( + REGISTRY_KEY, + Map.of( + "accountId", ACCOUNT.toString(), "worldSlug", "demo", "connectScopeId", "scope-1")); + byte[] prior = rawValue(REGISTRY_KEY); + var registry = registry(reader(keySource, NOW, target(17L))); + assertThatThrownBy(() -> registry.find(91L)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> registry.register(91L, original)) + .isInstanceOf(IllegalStateException.class); + assertThat(FirstPartyConnectContextResolution.resolve(91L, null, registry).invalid()).isTrue(); + assertThat(rawValue(REGISTRY_KEY)).containsExactly(prior); + } + + @Test + void corruptedRetainedCompactIsNotTrustedBecauseItsObjectShapeLooksComplete() { + var priorVerified = + GatewayFirstPartyConnectContextEnvelope.verify(original.compactJws(), keySource, NOW, 0); + var corrupted = new FirstPartyConnectContext("incomplete.context", priorVerified, target(17L)); + template.opsForValue().set(REGISTRY_KEY, corrupted); + byte[] prior = rawValue(REGISTRY_KEY); + var registry = registry(reader(keySource, NOW, target(17L))); + assertThatThrownBy(() -> registry.find(91L)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> registry.register(91L, original)) + .isInstanceOf(IllegalStateException.class); + assertThat(FirstPartyConnectContextResolution.resolve(91L, null, registry).invalid()).isTrue(); + assertThat(rawValue(REGISTRY_KEY)).containsExactly(prior); + } + + @Test + void unavailableDedicatedKeysChangedCurrentTargetAndSignedExpiryDenyWithoutOverwrite() { + registry(producerView).register(91L, original); + byte[] prior = rawValue(REGISTRY_KEY); + List unavailableReaders = + List.of( + reader(kid -> null, NOW, target(17L)), + reader( + kid -> { + throw new GatewayFirstPartyConnectContextEnvelope.KeySourceUnavailableException(); + }, + NOW, + target(17L)), + reader(keySource, NOW, target(18L)), + reader(keySource, NOW + 31_000L, target(17L))); + for (FirstPartyConnectContextService service : unavailableReaders) { + var registry = registry(service); + assertThatThrownBy(() -> registry.find(91L)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> registry.register(91L, original)) + .isInstanceOf(IllegalStateException.class); + var resolution = FirstPartyConnectContextResolution.resolve(91L, null, registry); + assertThat(resolution.invalid()).isTrue(); + assertThat(resolution.connectContext()).isEmpty(); + assertThat(rawValue(REGISTRY_KEY)).containsExactly(prior); + } + } + + private RedisFirstPartyConnectContextRegistry registry(FirstPartyConnectContextService service) { + return new RedisFirstPartyConnectContextRegistry(template, properties, service); + } + + private FirstPartyConnectContextService reader( + GatewayVerificationKeySource verificationKeys, long now, CanonicalPlayableTarget target) { + CanonicalPlayerRouteReadService routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readCurrentTarget(TENANT)).thenReturn(target); + return new FirstPartyConnectContextService( + properties, + verificationKeys, + routes, + Clock.fixed(Instant.ofEpochMilli(now), ZoneOffset.UTC), + new io.micrometer.core.instrument.simple.SimpleMeterRegistry()); + } + + private byte[] rawValue(String key) { + byte[] serializedKey = serializedKey(key); + return template.execute( + (RedisCallback) connection -> connection.stringCommands().get(serializedKey)); + } + + private void putRaw(String key, byte[] bytes) { + byte[] serializedKey = serializedKey(key); + template.execute( + (RedisCallback) + connection -> connection.stringCommands().set(serializedKey, bytes)); + } + + @SuppressWarnings("unchecked") + private byte[] serializedKey(String key) { + return java.util.Objects.requireNonNull( + ((RedisSerializer) java.util.Objects.requireNonNull(template.getKeySerializer())) + .serialize(key)); + } + + private GameplayConnectSource source() { + AuthorityTuple tuple = + new AuthorityTuple( + "1", + "2", + Map.of(TENANT.toString(), "3"), + Map.of(TENANT.toString(), "4"), + List.of(), + new AccountSecurityCutoff("2", "account:auth-authority:v1:account/" + ACCOUNT, "6"), + Map.of( + TENANT.toString(), + new TenantBillingCutoff( + "3", "7", "account:auth-authority:v1:tenant/" + TENANT, "8"))); + return new GameplayConnectSource( + ACCOUNT, + TENANT, + REALM, + "demo", + "production", + NAMESPACE, + "SHARED", + INSTANCE, + "17", + "3", + "scope-1", + "request-1", + tuple, + Map.of(TENANT.toString(), "9"), + "a".repeat(64), + "5", + null, + null, + NOW / 1000L + 30L); + } + + private String token() { + return GatewayFirstPartyConnectContextEnvelope.sign( + source(), + new GatewayContextMetadata("203.0.113.8", "gateway-1", NOW, NOW, NOW + 30_000L), + new GatewaySigningKey("gateway-test", keys.getPrivate())); + } + + private CanonicalPlayableTarget target(long pointerVersion) { + return new CanonicalPlayableTarget( + "firemud-test", + "tenant", + TENANT, + "demo", + "Demo", + REALM, + "production", + "Production", + 22L, + 41L, + NAMESPACE, + "SHARED", + INSTANCE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + 7L, + 3L, + pointerVersion, + "d".repeat(64), + 1L, + "initial-request", + "a".repeat(64), + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .NO_PRIOR_POINTER, + null, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "sha256:" + "b".repeat(64), + 9L, + "sha256:" + "c".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.ofEpochMilli(NOW - 1000L), + "PRESEEDED"); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 114aff343c..c6d0b1961d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -1,6 +1,7 @@ -package integration.net.firedevops.firemud.gamesession.service; +package net.firedevops.firemud.gamesession.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -63,11 +64,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; @@ -79,14 +82,8 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClient; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisKeys; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisAttemptClosure; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; import net.firedevops.firemud.test.TestContainerImages; @@ -177,6 +174,7 @@ class InitialGameplayLoginContextRedisIntegrationTest { private StatefulRedisConnection adminConnection; private RedisCommands admin; private String schema; + private InitialGameplayLoginCoordinationJournalRepository journal; @BeforeAll static void startOwnedPhysicalFixtures() throws Exception { @@ -328,6 +326,46 @@ void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecr assertThat(qualification.active).isFalse(); } + @Test + void createPendingIsCreateOnlyAndUsesPhysicalAcknowledgementAndIndependentReadback() + throws Exception { + var original = coordinates(); + own(original); + var provider = new TracedProvider(writer); + var client = client(provider, new ControlledAuthority(), 1); + var expected = InitialGameplayLoginContextState.pending(original); + + assertThat(client.createPending(original).orElseThrow().encode()) + .containsExactly(expected.encode()); + byte[] created = admin.get(key(original)); + assertThat(created).containsExactly(expected.encode()); + assertThat(admin.pexpiretime(key(original))).isEqualTo(-1L); + + assertThat(client.createPending(original)).isEmpty(); + assertThat(admin.get(key(original))).containsExactly(created); + assertThat(provider.traces.get(0)) + .containsSubsequence("aclWhoami", "evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(1)).containsSubsequence("aclWhoami", "get", "close"); + } + + @Test + void createPendingNeverAdoptsOrOverwritesAnExistingExpiringPhysicalValue() throws Exception { + var original = coordinates(); + own(original); + byte[] malformed = ascii("{existing-unqualified-value}"); + admin.set(key(original), malformed); + admin.pexpire(key(original), 60_000); + long originalExpiry = admin.pexpiretime(key(original)); + + assertThat( + client(new TracedProvider(writer), new ControlledAuthority(), 1) + .createPending(original)) + .isEmpty(); + + assertThat(admin.get(key(original))).containsExactly(malformed); + assertThat(admin.pexpiretime(key(original))).isPositive().isEqualTo(originalExpiry); + } + @ParameterizedTest @ValueSource( strings = { @@ -554,6 +592,195 @@ void actualJournalCleanupRetiresOnlyInsideExactCurrentExclusionAndOldReceiptCann assertThat(admin.get(key(unrelated))).containsExactly(untouched); } + @Test + void ownerComposesDurableOriginalWithPhysicalPendingAndExactNonAdmittingInstall() + throws Exception { + var authority = new ControlledAuthority(); + var provider = new TracedProvider(writer); + var contexts = client(provider, authority, 1); + var account = mock(CanonicalGameplayLoginAccountClient.class); + var cleanup = cleanup(contexts, account); + var owner = new InitialGameplayLoginOwner(contexts, cleanup, account); + var secret = "fixture-transient-secret".toCharArray(); + var credentials = + new InitialGameplayLoginCredentialPresentation( + "player@example.test", "203.0.113.10", secret); + var resultRef = new AtomicReference(); + var requestRef = new AtomicReference(); + var reservationRef = new AtomicReference(); + var beforeFirstMutation = new AtomicBoolean(true); + provider.beforeEval = + () -> { + if (beforeFirstMutation.compareAndSet(true, false)) { + var reserved = journal.readRetainedPage(Optional.empty(), 5); + assertThat(reserved).hasSize(1); + var original = reserved.get(0).coordinates(); + reservationRef.set(original); + assertThat(original.expectedAttemptFence()).isEqualTo(1L); + assertThat(admin.get(key(original))).isNull(); + assertThat(reserved.get(0).abandoned()).isFalse(); + assertThat(reserved.get(0).verifiedWitness()).isEmpty(); + } + }; + when(account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + var request = invocation.getArgument(0, AuthenticateRequest.class); + var original = coordinates(request); + requestRef.set(request); + assertThat(original).isEqualTo(reservationRef.get()); + assertThat(original.expectedAttemptFence()).isEqualTo(1L); + assertThat(original.requestId().version()).isEqualTo(4); + assertThat(original.callerContextId().version()).isEqualTo(4); + assertThat(original.requestId()).isNotEqualTo(original.callerContextId()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(provider.traces).hasSize(2); + assertThat(provider.traces.get(0)).containsSubsequence("evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(1)).containsSubsequence("get", "close"); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); + var committed = journal.readCommitted(original).orElseThrow(); + assertThat(committed.abandoned()).isFalse(); + assertThat(committed.verifiedWitness()).isEmpty(); + assertThat(committed.frozenRetirementRequest()).isEmpty(); + var result = validatedResult(request, UUID.randomUUID()); + resultRef.set(result); + return result; + }); + + var outcome = owner.receive(credentials); + var original = outcome.coordinates(); + ownedKeys.add(InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId())); + + assertThat(outcome.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + assertThat(original.expectedAttemptFence()).isEqualTo(1L); + assertThat(original.requestId().version()).isEqualTo(4); + assertThat(original.callerContextId().version()).isEqualTo(4); + assertThat(original.requestId()).isNotEqualTo(original.callerContextId()); + assertThat(original).isEqualTo(reservationRef.get()); + assertThat(requestRef.get().getRequestId()).isEqualTo(original.requestId().toString()); + assertThat(requestRef.get().getSourceContext().getCallerContextId()) + .isEqualTo(original.callerContextId().toString()); + assertThat(secret).containsOnly('\0'); + + var privateResult = outcome.takePrivateResult().orElseThrow(); + try { + assertThat(privateResult).isSameAs(resultRef.get()); + byte[] installed = + InitialGameplayLoginContextState.installed(original, privateResult).encode(); + byte[] persisted = admin.get(key(original)); + assertThat(persisted).containsExactly(installed); + assertThat(containsSequence(persisted, privateResult.compactJwtBytes())).isFalse(); + assertThat(containsSequence(persisted, ascii("fixture-transient-secret"))).isFalse(); + assertThat(admin.pexpiretime(key(original))).isEqualTo(-1L); + assertThat(provider.traces).hasSize(4); + assertThat(provider.traces.get(2)).containsSubsequence("evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(3)).containsSubsequence("get", "close"); + var committed = journal.readCommitted(original).orElseThrow(); + assertThat(committed.abandoned()).isFalse(); + assertThat(committed.verifiedWitness()).contains(witness(privateResult)); + assertThat(committed.frozenRetirementRequest()).isEmpty(); + verify(account, never()).retireInitialGameplayLogin(any()); + assertThat(authority.active).isFalse(); + } finally { + outcome.close(); + privateResult.close(); + } + } + + @Test + void ownerClosesExactOriginalAndWipesResultWhenCredentialCustodyEndsAfterAccountResponse() + throws Exception { + var authority = new ControlledAuthority(); + var provider = new TracedProvider(writer); + var contexts = client(provider, authority, 1); + var account = mock(CanonicalGameplayLoginAccountClient.class); + var cleanup = cleanup(contexts, account); + var owner = new InitialGameplayLoginOwner(contexts, cleanup, account); + var secret = "fixture-transient-secret".toCharArray(); + var credentials = + new InitialGameplayLoginCredentialPresentation( + "player@example.test", "203.0.113.10", secret); + var resultRef = new AtomicReference(); + var retirementRef = + new AtomicReference(); + when(account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + var request = invocation.getArgument(0, AuthenticateRequest.class); + var original = coordinates(request); + assertThat(provider.traces).hasSize(2); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); + assertThat(journal.readCommitted(original).orElseThrow().verifiedWitness()).isEmpty(); + var result = validatedResult(request, UUID.randomUUID()); + resultRef.set(result); + credentials.close(); + return result; + }); + when(account.retireInitialGameplayLogin(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + var original = coordinates(request); + retirementRef.set(request); + assertThat(authority.active).isTrue(); + assertThat(authority.current).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.hasTokenWitness()).isTrue(); + assertThat(provider.traces).hasSize(4); + assertThat(provider.traces.get(2)).containsSubsequence("evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(3)).containsSubsequence("get", "close"); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + var beforeAccount = journal.readCommitted(original).orElseThrow(); + assertThat(beforeAccount.abandoned()).isTrue(); + assertThat(beforeAccount.frozenRetirementRequest()).contains(request); + return new InitialGameplayLoginDisposalResult( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getCallerContextId()), + UUID.randomUUID(), + Disposition.PENDING, + ProofKind.NONE); + }); + + var outcome = owner.receive(credentials); + var original = outcome.coordinates(); + ownedKeys.add(InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId())); + + assertThat(outcome.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_ACCOUNT_PENDING); + assertThat(outcome.failureCode()).contains("CUSTODY_LOST"); + assertThat(outcome.cleanupStatus()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.ACCOUNT_PENDING); + assertThat(secret).containsOnly('\0'); + assertThatThrownBy(() -> resultRef.get().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + var committed = journal.readCommitted(original).orElseThrow(); + assertThat(committed.abandoned()).isTrue(); + var verifiedWitness = witness(resultRef.get()); + assertThat(committed.verifiedWitness()).contains(verifiedWitness); + var exactRetirement = InitialGameplayLoginJournalSnapshot.request(original, verifiedWitness); + assertThat(committed.frozenRetirementRequest()).contains(exactRetirement); + assertThat(retirementRef.get()).isEqualTo(exactRetirement); + assertThat(committed.retainedReceipt()) + .hasValueSatisfying( + receipt -> { + assertThat(receipt.disposition()).isEqualTo(Disposition.PENDING); + assertThat(receipt.proofKind()).isEqualTo(ProofKind.NONE); + }); + assertThat(provider.traces).hasSize(4); + assertThat(outcome.takePrivateResult()).isEmpty(); + verify(account).authenticate(any(AuthenticateRequest.class), any()); + verify(account).retireInitialGameplayLogin(any()); + assertThat(authority.active).isFalse(); + } + @ParameterizedTest @ValueSource(strings = {"absent", "replaced", "newer-attempt"}) void originalClosureCannotCreateAbsentOrTouchReplacementAndNewContext(String condition) { @@ -605,7 +832,7 @@ private InitialGameplayLoginCleanupOwner cleanup( "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); - var journal = + journal = new InitialGameplayLoginCoordinationJournalRepository( DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES)); return new InitialGameplayLoginCleanupOwner( @@ -643,6 +870,29 @@ private static InitialGameplayLoginAttemptCoordinates coordinates() { return new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); } + private static InitialGameplayLoginAttemptCoordinates coordinates(AuthenticateRequest request) { + return new InitialGameplayLoginAttemptCoordinates( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getSourceContext().getCallerContextId()), + 1L); + } + + private static InitialGameplayLoginAttemptCoordinates coordinates( + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest request) { + return new InitialGameplayLoginAttemptCoordinates( + UUID.fromString(request.getRequestId()), UUID.fromString(request.getCallerContextId()), 1L); + } + + private static InitialGameplayLoginTokenWitness witness(CanonicalGameplayLoginResult result) { + var evidence = result.evidence(); + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + } + private void own(InitialGameplayLoginAttemptCoordinates original) { String key = InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId()); assertThat(admin.get(ascii(key))).isNull(); @@ -920,6 +1170,25 @@ private static Object invoke(Object target, Method method, Object[] args) throws private static CanonicalGameplayLoginResult validatedResult( InitialGameplayLoginAttemptCoordinates original, UUID jti) throws Exception { + var request = + AuthenticateRequest.newBuilder() + .setRequestId(original.requestId().toString()) + .setEmail("player@example.test") + .setPassword("fixture-transient-secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(original.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + return validatedResult(request, jti); + } + + private static CanonicalGameplayLoginResult validatedResult(AuthenticateRequest request, UUID jti) + throws Exception { + var original = coordinates(request); var claims = new LinkedHashMap( Map.ofEntries( @@ -947,19 +1216,6 @@ private static CanonicalGameplayLoginResult validatedResult( signature.initSign(keys.getPrivate()); signature.update(input.getBytes(StandardCharsets.US_ASCII)); String token = input + "." + encoder.encodeToString(signature.sign()); - var request = - AuthenticateRequest.newBuilder() - .setRequestId(original.requestId().toString()) - .setEmail("player@example.test") - .setPassword("fixture-transient-secret") - .setSourceContext( - GameplayLoginSourceContext.newBuilder() - .setCallerContextId(original.callerContextId().toString()) - .setCanonicalClientAddress("203.0.113.10") - .setTransportClass( - GameplayLoginTransportClass - .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) - .build(); var response = AuthenticateResponse.newBuilder() .setAuthToken(token) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 060a1b0b01..e0f9bb5632 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -10,7 +10,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.fasterxml.jackson.databind.JsonNode; import java.net.URI; import java.util.List; import java.util.Optional; @@ -46,7 +45,6 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; -import net.firedevops.firemud.gamesession.testsupport.GameplayStructuredCommandAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.gamesession.testsupport.InMemorySessionContextTestConfiguration; @@ -61,6 +59,8 @@ import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -97,7 +97,6 @@ "spring.application.name=game-session-service", "spring.grpc.server.port=0", "spring.flyway.enabled=true", - "firemud.gateway.connect-context.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.gameplay.catalog.worlds[0].slug=demo", "firemud.gameplay.catalog.worlds[0].display-name=Demo World", "firemud.gameplay.catalog.worlds[0].realms[0].slug=production", @@ -797,48 +796,6 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { .hasValueSatisfying(context -> assertThat(context.roomInstanceId()).isEqualTo("R-1021")); } - @Test - void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo Emberline"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - payloads = client.responses(); - } - - JsonNode loginSuccess = json(payloads.get(0)); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginSuccess, "LOGIN", "login", "META", "SESSION"); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "PLAY", "play", "META", "SESSION") - && json(payload).path("accepted").asBoolean()); - assertThat(payloads).anyMatch(payload -> json(payload).path("outputs").isArray()); - verify(accountClient) - .getTenantMembershipForRuntime( - eq("123"), eq("22"), org.mockito.ArgumentMatchers.anyString()); - verify(accountClient) - .getTenantEntitlementsForRuntime(eq("22"), org.mockito.ArgumentMatchers.anyString()); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) - .hasValueSatisfying( - context -> { - assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-1"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-1"); - }); - } - @Test void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { List payloads; @@ -871,273 +828,6 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } - @Test - void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("REALMS demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); - client.send("CHARS demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "CHARS"), "structured CHARS result"); - payloads = client.responses(); - } - - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "LOGIN", "login", "META", "SESSION")); - JsonNode realmsResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "REALMS", "realms", "META", "WORLD_BROWSE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - realmsResult, "REALMS", "realms", "META", "WORLD_BROWSE", "UI"); - assertThat(realmsResult.path("accepted").asBoolean()).isTrue(); - assertThat(realmsResult.path("outputs").get(0).path("payloadType").asText()) - .isEqualTo("realms_view"); - assertThat(realmsResult.path("outputs").get(0).path("payload").path("worldSlug").asText()) - .isEqualTo("demo"); - assertThat(realmsResult.path("outputs").get(0).path("payload").path("realms")).hasSize(1); - assertThat( - realmsResult - .path("outputs") - .get(0) - .path("payload") - .path("realms") - .get(0) - .path("stateScope") - .asText()) - .isEqualTo("SHARED"); - assertThat( - realmsResult - .path("outputs") - .get(0) - .path("payload") - .path("realms") - .get(0) - .path("characterCreationPolicy") - .asText()) - .isEqualTo("ALLOW_NEW"); - - JsonNode charsResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "CHARS", "chars", "META", "WORLD_BROWSE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - charsResult, "CHARS", "chars", "META", "WORLD_BROWSE", "UI"); - assertThat(charsResult.path("accepted").asBoolean()).isTrue(); - assertThat(charsResult.path("outputs").get(0).path("payloadType").asText()) - .isEqualTo("characters_view"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("realmSlug").asText()) - .isEqualTo("production"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("stateScope").asText()) - .isEqualTo("SHARED"); - assertThat( - charsResult - .path("outputs") - .get(0) - .path("payload") - .path("characterCreationPolicy") - .asText()) - .isEqualTo("ALLOW_NEW"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("characters")).hasSize(2); - verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - } - - @Test - void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "who-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo Emberline"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.send("AFK"); - GameplayAsyncAssertions.assertEventually( - "AFK gameplay presence update", - java.time.Duration.ofSeconds(5), - () -> - gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() - .filter(entry -> entry.sessionId() == 1L) - .findFirst() - .orElseThrow() - .explicitAfkSinceEpochMs() - != null); - client.send("WHO"); - client.awaitMatching(payload -> isStructuredCommand(payload, "WHO"), "structured WHO result"); - payloads = client.responses(); - } - - JsonNode whoResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "WHO", "who", "META", "SOCIAL_PRESENCE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - whoResult, "WHO", "who", "META", "SOCIAL_PRESENCE", "UI"); - assertThat(whoResult.path("accepted").asBoolean()).isTrue(); - assertThat(whoResult.path("outputs").get(0).path("payloadType").asText()).isEqualTo("who_view"); - assertThat(whoResult.path("outputs").get(0).path("payload").path("players")).hasSize(1); - assertThat( - whoResult - .path("outputs") - .get(0) - .path("payload") - .path("players") - .get(0) - .path("activityState") - .asText()) - .isEqualTo("EXPLICIT_AFK"); - } - - @Test - void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() throws Exception { - when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) - .thenReturn( - Optional.of( - new ScreenBufferService.BufferedScreen( - java.util.List.of( - ScreenBufferService.BufferedEntry.fromText("Recent combat line\n"), - ScreenBufferService.BufferedEntry.fromText("Second recent line\n")), - 2, - 2, - 32L))); - - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo Emberline"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line"), - "replayed transcript chunk"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW"), - "fresh view output"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT"), - "fresh prompt output"); - payloads = client.responses(); - } - - assertThat( - GameplayStructuredCommandAssertions.isStructuredCommand( - payloads.get(0), "LOGIN", "login", "META", "SESSION")) - .isTrue(); - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "PLAY", "play", "META", "SESSION")); - assertThat(payloads) - .anyMatch( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line")); - assertThat(payloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW")); - assertThat(payloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT")); - } - - @Test - void websocketFirstPartyUnexpectedDisconnectRetainsReplayStateForFreshReconnect() - throws Exception { - when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) - .thenReturn( - Optional.of( - new ScreenBufferService.BufferedScreen( - java.util.List.of( - ScreenBufferService.BufferedEntry.fromText("First-party replay\n")), - 1, - 1, - 44L))); - - GameplayWebSocketDriver firstClient = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "disconnect-1")); - firstClient.send("LOGIN"); - firstClient.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - firstClient.send("PLAY demo Emberline"); - firstClient.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - firstClient.abort(); - - GameplayAsyncAssertions.assertPresenceCountEventually( - gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) - .containsKey("123"); - - java.util.List secondPayloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "disconnect-2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo Emberline"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("First-party replay"), - "replayed first-party transcript chunk"); - secondPayloads = client.responses(); - } - - assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "LOGIN")); - assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "PLAY")); - assertThat(secondPayloads) - .anyMatch( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("First-party replay")); - verify(screenBufferService, never()).clear(22L, 1L, 123L); - } - @Test void websocketFreshPlayDoesNotReplayBufferedLookFromOldSession() throws Exception { when(screenBufferService.get(eq(22L), eq(41L), eq(123L))) @@ -1323,269 +1013,6 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); } - @Test - void websocketFirstPartyInvalidConnectContextClosesImmediately() throws Exception { - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - GameplayWebSocketDriver.connect( - websocketUri(), - java.time.Duration.ofSeconds(10), - java.util.Map.of( - "X-Firemud-Connection-Mode", "first_party_web", - "X-Firemud-Connect-Context", "not-a-valid-context"))) { - closeEvent = client.awaitClosed(); - } - - assertThat(closeEvent.statusCode()).isEqualTo(1008); - assertThat(closeEvent.reason()).isEqualTo("CONNECT_CONTEXT_INVALID"); - } - - @Test - void websocketFirstPartyLoginRejectsScopeMismatchAndClosesTransport() throws Exception { - List payloads; - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "mismatch"))) { - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - closeEvent = client.awaitClosed(); - payloads = client.responses(); - } - - JsonNode loginFailure = json(payloads.get(0)); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginFailure, "LOGIN", "login", "META", "SESSION"); - assertThat(loginFailure.path("accepted").asBoolean()).isFalse(); - assertThat(loginFailure.path("errorCode").asText()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - assertThat(closeEvent.statusCode()).isEqualTo(1008); - assertThat(closeEvent.reason()).isEqualTo("policy_violation"); - } - - @Test - void websocketFirstPartyLoginRejectsStalePointerAfterCutover() throws Exception { - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "stale-login"))) { - closeEvent = client.awaitClosed(); - } - - assertThat(closeEvent.statusCode()).isEqualTo(1013); - assertThat(closeEvent.reason()).isEqualTo("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE"); - } - - @Test - void websocketFirstPartyReconnectAfterCutoverFailsClosedWithoutLeakingOldGameplayBinding() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "resume-before-cutover"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo Emberline"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver reconnecting = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "resume-after-cutover"))) { - closeEvent = reconnecting.awaitClosed(); - } - - assertThat(closeEvent.statusCode()).isEqualTo(1013); - assertThat(closeEvent.reason()).isEqualTo("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE"); - } - - @Test - void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelogin() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "route-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo Emberline"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - List payloads; - try (GameplayWebSocketDriver second = - openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - second.send("LOOK"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - second.send("WORLDS"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "WORLDS"), "structured WORLDS result"); - second.send("REALMS sandbox"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); - payloads = second.responses(); - } - - JsonNode loginSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOGIN")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - JsonNode lookFailure = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOOK")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(lookFailure.path("accepted").asBoolean()).isFalse(); - assertThat(lookFailure.path("errorCode").asText()).isEqualTo("PLAY_REQUIRED"); - - JsonNode worldsSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "WORLDS")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(worldsSuccess.path("accepted").asBoolean()).isTrue(); - assertThat(worldsSuccess.toString()).doesNotContain("Builder Sandbox", "sandbox"); - - JsonNode realmsRejected = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "REALMS")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(realmsRejected.path("accepted").asBoolean()).isFalse(); - assertThat(realmsRejected.path("errorCode").asText()).isEqualTo("INVALID_ARGUMENT"); - - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isEqualTo("123"); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); - assertThat(context.worldSlug()).isEqualTo("sandbox"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-route-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-route-b"); - }); - } - - @Test - void websocketFirstPartyPlayRejectsCutoverAfterLogin() throws Exception { - List payloads; - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "stale-play"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - closeEvent = client.awaitClosed(); - payloads = client.responses(); - } - - JsonNode loginSuccess = json(payloads.getFirst()); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginSuccess, "LOGIN", "login", "META", "SESSION"); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - JsonNode playFailure = json(payloads.getLast()); - GameplayStructuredCommandAssertions.requireStructuredCommand( - playFailure, "PLAY", "play", "META", "SESSION"); - assertThat(playFailure.path("accepted").asBoolean()).isFalse(); - assertThat(playFailure.path("errorCode").asText()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - assertThat(closeEvent.statusCode()).isEqualTo(1008); - assertThat(closeEvent.reason()).isEqualTo("policy_violation"); - } - - @Test - void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRelogin() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo Emberline"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - List payloads; - try (GameplayWebSocketDriver second = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-b"))) { - second.send("LOOK"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - payloads = second.responses(); - } - - JsonNode lookFailure = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOOK")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(lookFailure.path("accepted").asBoolean()).isFalse(); - assertThat(lookFailure.path("errorCode").asText()).isEqualTo("LOGIN_REQUIRED"); - - JsonNode loginSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOGIN")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isEqualTo("123"); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-scope-selector-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-scope-selector-b"); - }); - assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEmpty(); - } - private GameplayWebSocketDriver openGameplayDriver(String sessionId) { return openGameplayDriver(sessionId, java.util.Map.of()); } @@ -1614,45 +1041,6 @@ private GameplayWebSocketDriver openGameplayDriver( websocketUri(), java.time.Duration.ofSeconds(10), headers); } - private GameplayWebSocketDriver openFirstPartyDriver( - String transportSessionId, java.util.Map connectClaims) { - return GameplayWebSocketDriver.connectFirstPartyWeb( - websocketUri(), - java.time.Duration.ofSeconds(10), - transportSessionId, - "testsecretkeytestsecretkeytest1234", - connectClaims); - } - - private java.util.Map firstPartyClaims( - String worldSlug, - String realmSlug, - String gameInstanceId, - String pointerVersion, - String suffix) { - return java.util.Map.of( - "accountId", - "123", - "tenantId", - "22", - "worldSlug", - worldSlug, - "realmSlug", - realmSlug, - "gameInstanceId", - gameInstanceId, - "pointerVersion", - pointerVersion, - "connectScopeId", - "scope-" + suffix, - "connectTokenJti", - "connect-jti-" + suffix, - "connectRequestId", - "connect-req-" + suffix, - "gatewayRequestId", - "gateway-req-" + suffix); - } - private WebSocketHttpHeaders gameplayHeaders(String sessionId) { WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); headers.add("X-Game-Instance-Id", "1"); @@ -1765,18 +1153,6 @@ private static void stubTransactionExecution(RedisTemplate redis when(redisTemplate.exec()).thenReturn(List.of("OK")); } - private static JsonNode json(String payload) { - return GameplayStructuredCommandAssertions.parseStructuredResponse(payload); - } - - private static boolean isStructuredCommand(String payload, String commandType) { - return GameplayStructuredCommandAssertions.isStructuredCommand(payload, commandType); - } - - private static boolean containsKind(JsonNode envelope, String kind) { - return GameplayStructuredCommandAssertions.containsKind(envelope, kind); - } - private static boolean matchesContext( net.firedevops.firemud.gamesession.service.SessionContext context, long tenantId, @@ -1791,4 +1167,74 @@ private static boolean matchesContext( && context.gameInstanceId() == gameInstanceId && roomInstanceId.equals(context.roomInstanceId()); } + + @ParameterizedTest + @ValueSource(strings = {"", "not-a-valid-context", "incomplete.context"}) + void firstPartyUnavailableBootstrapDeniesWithoutLoginLobbyGameplayOrReplayEffects(String context) + throws Exception { + try (GameplayWebSocketDriver client = openUnqualifiedFirstPartyDriver("1", context)) { + var close = client.awaitClosed(); + assertThat(close.statusCode()).isEqualTo(1008); + assertThat(close.reason()).isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(client.responses()).isEmpty(); + } + assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)).isEmpty(); + assertThat(firstPartyConnectStore).isEmpty(); + assertThat(gameplayPresenceService.findConnectedBySessionId(1L)).isEmpty(); + verify(accountClient, never()).authenticate(any(), any()); + verify(accountClient, never()).getTenantMembershipForRuntime(any(), any(), any()); + verify(entityManagementClient, never()).listCharactersByAccount(any(), any(), any(), any()); + } + + @Test + void unqualifiedFirstPartyReconnectDoesNotReplaceRetainedOrdinaryGameplayContext() + throws Exception { + try (GameplayWebSocketDriver ordinary = openAdmittedGameplayDriver("2")) { + var retained = sessionContextService.findByTenantAndSessionId(22L, 2L).orElseThrow(); + var retainedPresence = gameplayPresenceService.findConnectedBySessionId(2L); + assertThat(retainedPresence).isPresent(); + try (GameplayWebSocketDriver reconnecting = + openUnqualifiedFirstPartyDriver("2", "unqualified-context")) { + var close = reconnecting.awaitClosed(); + assertThat(close.statusCode()).isEqualTo(1008); + assertThat(reconnecting.responses()).isEmpty(); + } + assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)).contains(retained); + assertThat(firstPartyConnectStore) + .doesNotContainKey("sessionctx:first-party:2:connect-context"); + assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEqualTo(retainedPresence); + int responseBaseline = ordinary.responses().size(); + ordinary.send("LOOK"); + ordinary.awaitTranscriptContainingAllAfter(responseBaseline, "Room: Login Hall (ID: R-1021)"); + } + } + + @Test + void unqualifiedFirstPartyCutoverStillDeniesBeforeBootstrapOrGameplayWrites() throws Exception { + bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); + try (GameplayWebSocketDriver client = + openUnqualifiedFirstPartyDriver("2", "unqualified-context")) { + var close = client.awaitClosed(); + assertThat(close.statusCode()).isEqualTo(1008); + assertThat(close.reason()).isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(client.responses()).isEmpty(); + } + assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)).isEmpty(); + assertThat(firstPartyConnectStore).isEmpty(); + assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEmpty(); + } + + private GameplayWebSocketDriver openUnqualifiedFirstPartyDriver( + String sessionId, String context) { + return GameplayWebSocketDriver.connect( + websocketUri(), + java.time.Duration.ofSeconds(10), + java.util.Map.of( + "X-Firemud-Connection-Mode", + "first_party_web", + "X-Firemud-Transport-Session-Id", + sessionId, + "X-Firemud-Connect-Context", + context)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java index f08e188f3d..e97ac3d5e4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java @@ -35,6 +35,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -87,7 +88,7 @@ void realMutualTlsPeerReceivesOriginalRequestAndReturnsTokenFreeDecision() throw try (var client = client(server, Duration.ofSeconds(5), verifier)) { client.initialize(); var original = request(); - assertDecision(client, original); + assertDecision(client, original, () -> true); assertThat(starts.get()).isEqualTo(1); assertThat(requests).hasSize(1); assertThat(requests.getFirst().equals(original)).isTrue(); @@ -113,7 +114,7 @@ void wrongAuthenticatedAccountPeerReceivesNeitherHeadersNorCredential(String wro var verifier = mock(AccountAsymmetricJwtVerifier.class); try (var client = client(server, Duration.ofSeconds(5), verifier)) { client.initialize(); - assertThatThrownBy(() -> client.authenticate(request())) + assertThatThrownBy(() -> client.authenticate(request(), () -> true)) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -168,7 +169,7 @@ public io.grpc.ClientCall interceptCall( verifier)) { client.initialize(); var original = request(); - assertDecision(client, original); + assertDecision(client, original, () -> true); assertThat(starts.get()).isEqualTo(2); assertThat(requests).hasSize(2); assertThat(deadlines).hasSize(2); @@ -180,6 +181,53 @@ public io.grpc.ClientCall interceptCall( } } + @Test + void custodyLossAfterFirstAmbiguousDispatchPreventsThePermittedRetry() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = startServer(pki.accountServer(), starts, requests, 1, Status.UNAVAILABLE); + AtomicBoolean custodyCurrent = new AtomicBoolean(true); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + var customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withInterceptors( + new io.grpc.ClientInterceptor() { + @Override + public io.grpc.ClientCall interceptCall( + io.grpc.MethodDescriptor method, + io.grpc.CallOptions options, + io.grpc.Channel next) { + custodyCurrent.set(false); + return next.newCall(method, options); + } + }); + } + }; + try (var client = + new CanonicalGameplayLoginAccountClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + customizer, + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + assertThatThrownBy(() -> client.authenticate(request(), custodyCurrent::get)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.CANCELLED)); + assertThat(starts.get()).isEqualTo(1); + assertThat(requests).hasSize(1); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + @Test void terminalTransportOutcomeIsNotRetriedAndDiagnosticsAreBounded() throws Exception { AtomicInteger starts = new AtomicInteger(); @@ -188,7 +236,7 @@ void terminalTransportOutcomeIsNotRetriedAndDiagnosticsAreBounded() throws Excep try (var client = client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { client.initialize(); - assertThatThrownBy(() -> client.authenticate(request())) + assertThatThrownBy(() -> client.authenticate(request(), () -> true)) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> { @@ -209,7 +257,7 @@ void secondAmbiguousOutcomeEndsInvocationWithoutNewRetryAuthority() throws Excep try (var client = client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { client.initialize(); - assertThatThrownBy(() -> client.authenticate(request())) + assertThatThrownBy(() -> client.authenticate(request(), () -> true)) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); @@ -233,7 +281,7 @@ void expiredParentDeadlineAndInvalidSourceDenyBeforeTransportCall() throws Excep .withDeadline(Deadline.after(-1, TimeUnit.NANOSECONDS), scheduler)) { expired.run( () -> - assertThatThrownBy(() -> client.authenticate(request())) + assertThatThrownBy(() -> client.authenticate(request(), () -> true)) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -250,7 +298,7 @@ void expiredParentDeadlineAndInvalidSourceDenyBeforeTransportCall() throws Excep GameplayLoginTransportClass .GAMEPLAY_LOGIN_TRANSPORT_CLASS_FIRST_PARTY_WEB)) .build(); - assertThatThrownBy(() -> client.authenticate(invalid)) + assertThatThrownBy(() -> client.authenticate(invalid, () -> true)) .isInstanceOf(CanonicalGameplayLoginResult.InvalidResultException.class); assertThat(starts.get()).isZero(); assertThat(requests).isEmpty(); @@ -286,7 +334,7 @@ void constructorRequiresMutualTlsAndExplicitInitialization() throws Exception { Clock.systemUTC(), Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { - assertThatThrownBy(() -> uninitialized.authenticate(request())) + assertThatThrownBy(() -> uninitialized.authenticate(request(), () -> true)) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); @@ -577,8 +625,10 @@ public ServerCall.Listener interceptCall( } private static void assertDecision( - CanonicalGameplayLoginAccountClient client, AuthenticateRequest request) { - assertThatThrownBy(() -> client.authenticate(request)) + CanonicalGameplayLoginAccountClient client, + AuthenticateRequest request, + java.util.function.BooleanSupplier custodyCurrent) { + assertThatThrownBy(() -> client.authenticate(request, custodyCurrent)) .isInstanceOfSatisfying( CanonicalGameplayLoginResult.CredentialDecisionException.class, decision -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index d81046a54d..2eec93f6c6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -199,6 +200,45 @@ void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { assertThat(result.commandResult().errorMessage()).contains("Target is not available"); } + @Test + void tellReturnsUnavailableWithoutPublishingOrCallingGameLogicWhenTargetSessionIsUnreadable() { + when(entityManagementClient.findCharacterByName( + sessionContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) + .thenReturn( + Optional.of( + Character.newBuilder() + .setId("300") + .setTenantId("22") + .setAccountId("700") + .setName("Sora") + .build())); + when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) + .thenThrow(new SessionContextUnavailableException("retained session unavailable", null)); + + CommunicationCommandHandlingResult result = + handler.handle( + sessionContext, + new TextCommand( + TextCommandType.TELL, List.of("Sora", "Meet me later"), "TELL Sora Meet me later")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("COMMUNICATION_NOT_DELIVERED"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Recipient session unavailable"); + Mockito.verify(gameLogicClient, Mockito.never()) + .sendCommunication( + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.nullable(String.class)); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishCommandEvent(Mockito.any(), Mockito.any()); + Mockito.verifyNoInteractions(recipientDeliveryService); + } + @Test void underlyingFailurePropagates() { ErrorDetail error = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 4b3ae791f2..08e9fda08d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -16,7 +16,6 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; @@ -34,6 +33,7 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; @@ -41,6 +41,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; @SuppressWarnings("unchecked") class LoginCommandHandlerTest { @@ -132,7 +133,6 @@ void rejectsLegacyThreeArgumentLoginWithoutFallbackAuthentication() { "ERROR LOGIN_ARGUMENTS_INVALID Use LOGIN [secret].", joinedOutputText(result.outputs())); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(firstPartyConnectContextRegistry, never()).find(anyLong()); } @Test @@ -362,345 +362,49 @@ void missingCredentialsReturnsPromptError() { } @Test - void bareLoginWithUnavailableFirstPartyContextDoesNotAuthenticateOrChangeOwnership() { - when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.empty()); + void bareLoginWithTypedUnavailableSessionContextReturnsRetryableFailure() { + when(sessionContextService.findBySessionId(1L)) + .thenThrow(new SessionContextUnavailableException("session context unavailable", null)); TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); LoginCommandHandlingResult result = handler.handle("1", command, false); assertFalse(result.commandResult().accepted()); + assertEquals("UNAVAILABLE", result.commandResult().errorCode()); assertEquals( - LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, result.commandResult().errorCode()); + "error.login.unavailable", ((ErrorOutput) result.outputs().get(0).payload()).messageKey()); verify(accountClient, never()).authenticate(anyString(), anyString()); verify(firstPartyConnectContextRegistry, never()).unregister(1L); verify(gameInstanceRepository, never()).findById(anyLong()); - ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(saved.capture()); - assertNull(saved.getValue().accountId()); - } - - @Test - void credentialLoginCanReauthenticateAfterUnavailableFirstPartyContext() { - when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.empty()); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); - - LoginCommandHandlingResult bareLogin = - handler.handle("1", new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), false); - LoginCommandHandlingResult credentialLogin = - handler.handle( - "1", - new TextCommand( - TextCommandType.LOGIN, - List.of("demo@example.com", "swordfish"), - "LOGIN demo@example.com swordfish"), - false); - - assertFalse(bareLogin.commandResult().accepted()); - assertTrue(credentialLogin.commandResult().accepted()); - verify(accountClient).authenticate("demo@example.com", "swordfish"); - ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(2)).save(saved.capture()); - assertNull(saved.getAllValues().get(0).accountId()); - assertEquals("77", saved.getAllValues().get(1).accountId()); - assertEquals("demo@example.com", saved.getAllValues().get(1).loginName()); + verify(sessionContextService, never()).save(any()); } @Test - void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand() { + void bareLoginWithGenericUnavailableSessionStoreReturnsRetryableFailure() { + when(sessionContextService.findBySessionId(1L)) + .thenThrow(new IllegalStateException("retained context store unavailable")); TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); - stubSessionContext( - new SessionContext( - 1L, - 22L, - null, - null, - 0L, - null, - 0L, - null, - null, - "en-NZ", - 1L, - "demo", - "production", - 1L, - "SHARED", - "scope-1", - "req-1")); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "99", - 22L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); + assertFalse(result.commandResult().accepted()); + assertEquals("UNAVAILABLE", result.commandResult().errorCode()); verify(accountClient, never()).authenticate(anyString(), anyString()); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(captor.capture()); - SessionContext context = captor.getValue(); - assertEquals("99", context.accountId()); - assertEquals(1L, context.bootstrapGameInstanceId()); - assertEquals(0L, context.gameInstanceId()); - assertEquals(0L, context.characterId()); - assertEquals("en-NZ", context.localeTag()); - assertEquals("demo", context.worldSlug()); - assertEquals("production", context.realmSlug()); - assertEquals(1L, context.pointerVersion()); - assertEquals("SHARED", context.playableStateScope()); - assertEquals("scope-1", context.connectScopeId()); - assertEquals("req-1", context.connectRequestId()); - assertEquals(77L, instance.getOwnerAccountId()); - } - - @Test - void bareLoginRejectsUnsupportedFirstPartyAccountTextBeforeInstanceLookup() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - List unsupportedAccountIds = List.of("0", "-17", "account:opaque"); - for (int index = 0; index < unsupportedAccountIds.size(); index++) { - long sessionId = index + 1L; - stubSessionContext(bootstrapShell(sessionId, 1L)); - when(firstPartyConnectContextRegistry.find(sessionId)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - unsupportedAccountIds.get(index), - 22L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - - LoginCommandHandlingResult result = handler.handle(Long.toString(sessionId), command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - } - - verify(gameInstanceRepository, never()).findById(anyLong()); - verify(gameplayAdmissionPointerAuthorityService, never()) - .listByRuntimeTarget(anyLong(), anyLong()); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(unsupportedAccountIds.size())).save(captor.capture()); - assertTrue(captor.getAllValues().stream().allMatch(context -> context.accountId() == null)); - verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - } - - @Test - void bareLoginRejectsAbsentFirstPartyAccountBeforeInstanceLookup() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - String[] absentAccountIds = {null, " "}; - for (int index = 0; index < absentAccountIds.length; index++) { - long sessionId = index + 1L; - stubSessionContext(bootstrapShell(sessionId, 1L)); - when(firstPartyConnectContextRegistry.find(sessionId)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - absentAccountIds[index], - 22L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - - LoginCommandHandlingResult result = handler.handle(Long.toString(sessionId), command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - } - - verify(gameInstanceRepository, never()).findById(anyLong()); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(absentAccountIds.length)).save(captor.capture()); - assertTrue(captor.getAllValues().stream().allMatch(context -> context.accountId() == null)); - verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + verify(sessionContextService, never()).save(any()); } @Test - void bareLoginRejectsOpaqueFirstPartyAccountWithoutClearingExistingOwnerAlias() { + void bareLoginWithUnavailableSessionStoreReturnsRetryableFailure() { + when(sessionContextService.findBySessionId(1L)) + .thenThrow(new DataAccessResourceFailureException("session store unavailable")); TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - String accountId = "acct:opaque/legacy"; - stubSessionContext( - new SessionContext( - 1L, - 22L, - accountId, - null, - 0L, - null, - 0L, - null, - null, - "en-NZ", - 1L, - "demo", - "production", - 1L, - null, - "scope-1", - "req-1")); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - accountId, - 22L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); LoginCommandHandlingResult result = handler.handle("1", command, false); assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - verify(gameInstanceRepository, never()).findById(anyLong()); - verify(sessionContextService, never()).save(any(SessionContext.class)); - verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - } - - @Test - void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogin() { - TextCommand bareLogin = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - TextCommand credentialLogin = - new TextCommand( - TextCommandType.LOGIN, - List.of("demo@example.com", "swordfish"), - "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); - FirstPartyConnectContext accountAContext = - new FirstPartyConnectContext( - "99", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); - AtomicBoolean accountAContextRegistered = new AtomicBoolean(true); - List registryEvents = new java.util.ArrayList<>(); - Mockito.doAnswer( - invocation -> { - boolean registered = accountAContextRegistered.get(); - registryEvents.add(registered ? "find-account-a" : "find-empty"); - return registered ? Optional.of(accountAContext) : Optional.empty(); - }) - .when(firstPartyConnectContextRegistry) - .find(1L); - Mockito.doAnswer( - invocation -> { - registryEvents.add("unregister"); - accountAContextRegistered.set(false); - return null; - }) - .when(firstPartyConnectContextRegistry) - .unregister(1L); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - - LoginCommandHandlingResult firstPartyResult = handler.handle("1", bareLogin, false); - LoginCommandHandlingResult credentialResult = handler.handle("1", credentialLogin, false); - LoginCommandHandlingResult subsequentBareResult = handler.handle("1", bareLogin, false); - - assertTrue(firstPartyResult.commandResult().accepted()); - assertTrue(credentialResult.commandResult().accepted()); - assertFalse(subsequentBareResult.commandResult().accepted()); - assertEquals( - LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, - subsequentBareResult.commandResult().errorCode()); - verify(firstPartyConnectContextRegistry).unregister(1L); - assertEquals( - List.of("find-account-a", "find-account-a", "unregister", "find-empty"), registryEvents); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(3)).save(captor.capture()); - assertEquals("99", captor.getAllValues().get(0).accountId()); - assertEquals("77", captor.getAllValues().get(1).accountId()); - assertEquals("demo@example.com", captor.getAllValues().get(1).loginName()); - assertEquals(AUTH_TOKEN, captor.getAllValues().get(1).jwt()); - assertEquals(null, captor.getAllValues().get(2).accountId()); - } - - @Test - void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { - SessionContext credentialIdentity = - new SessionContext(1L, 22L, "77", "demo@example.com", 0L, null, 0L, "mock-jwt"); - stubSessionContext(credentialIdentity); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "99", - 22L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - - LoginCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - verify(firstPartyConnectContextRegistry).unregister(1L); - verify(sessionContextService, never()).save(any(SessionContext.class)); - verify(gameInstanceRepository, never()).findById(anyLong()); - } - - @Test - void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); - SessionContext persisted = - new SessionContext( - 1L, - 22L, - "77", - null, - 0L, - null, - 0L, - null, - null, - "en-NZ", - 1L, - "demo", - "production", - 1L, - null, - "scope-persisted", - "req-persisted"); - when(sessionContextService.findBySessionId(1L)).thenReturn(Optional.of(persisted)); - when(sessionContextService.findByTenantAndSessionId(22L, 1L)) - .thenReturn(Optional.of(persisted)); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); + assertEquals("UNAVAILABLE", result.commandResult().errorCode()); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(sessionContextService, never()).save(any()); } @Test @@ -767,134 +471,10 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess LoginCommandHandlingResult result = handler.handle("1", command, false); - assertFalse(result.commandResult().accepted()); - assertEquals( - LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, result.commandResult().errorCode()); - } - - @Test - void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "77", - 0L, - "demo", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 0L, 77L))); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - assertFalse(result.commandResult().accepted()); assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); } - @Test - void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "77", - 22L, - "demo", - "production", - 0L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn(List.of(pointer("demo", "production", 22L, 0L, 1L))); - when(gameInstanceRepository.findById(0L)).thenReturn(Optional.of(buildInstance(0L, 22L, 77L))); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - } - - @Test - void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "77", - 22L, - " ", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - } - - @Test - void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "77", 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - } - - @Test - void bareLoginRejectsStalePointerVersion() { - TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); - stubSessionContext(staleGameplayContext(1L)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "77", - 22L, - "demo", - "production", - 1L, - 0L, - "scope-1", - "jti-1", - "req-1", - "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - - LoginCommandHandlingResult result = handler.handle("1", command, false); - - assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(captor.capture()); - assertClearedSessionContext(captor.getValue(), 1L); - } - @Test void successfulLoginStoresSessionContext() { TextCommand command = @@ -992,8 +572,8 @@ void reloginPreservesExistingGameplayBindingForSameSession() { "production", 1L, "SHARED", - "scope-live", - "req-live"))); + null, + null))); when(sessionContextService.findBySessionId(1L)) .thenReturn( Optional.of( @@ -1013,8 +593,8 @@ void reloginPreservesExistingGameplayBindingForSameSession() { "production", 1L, "SHARED", - "scope-live", - "req-live"))); + null, + null))); handler.handle("1", command, false); @@ -1060,8 +640,8 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { "production", 1L, "SHARED", - "scope-live", - "req-live"); + null, + null); stubSessionContext(existing); handler.handle("1", command, false); @@ -1140,8 +720,8 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { "production", 1L, "SHARED", - "scope-live", - "req-live"); + null, + null); stubSessionContext(existing); handler.handle("1", command, false); @@ -1222,8 +802,8 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { "production", 1L, "SHARED", - "scope-live", - "req-live"); + null, + null); stubSessionContext(existing); handler.handle("1", command, false); @@ -1310,8 +890,8 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { assertNull(context.realmSlug()); assertEquals(0L, context.pointerVersion()); assertNull(context.playableStateScope()); - assertEquals("scope-stale", context.connectScopeId()); - assertEquals("req-stale", context.connectRequestId()); + assertNull(context.connectScopeId()); + assertNull(context.connectRequestId()); } @Test @@ -1381,8 +961,8 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup null, 3L, "LIVE", - "scope-stale", - "req-stale"); + null, + null); stubSessionContext(partialRoutingProjection); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1829,8 +1409,8 @@ private static SessionContext staleGameplayContext(long pointerVersion) { "production", pointerVersion, "LIVE", - "scope-stale", - "req-stale"); + null, + null); } private static SessionContext staleGameplayContextWithoutSelector(long pointerVersion) { @@ -1853,7 +1433,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe } private static void assertClearedSessionContext(SessionContext context, long pointerVersion) { - assertClearedSessionContext(context, pointerVersion, "scope-stale", "req-stale"); + assertClearedSessionContext(context, pointerVersion, null, null); } private static void assertClearedSessionContext( @@ -1896,4 +1476,40 @@ private void stubSessionContext(SessionContext context) { when(sessionContextService.findByTenantAndSessionId(context.tenantId(), context.sessionId())) .thenReturn(Optional.of(context)); } + + @Test + void retainedUuidLoginDeniesBeforeLegacyAccountLookupOrSessionWrites() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + FirstPartyConnectContext context = fixture.context(); + when(firstPartyConnectContextRegistry.find(1L)) + .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); + LoginCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), false); + assertFalse(result.commandResult().accepted()); + assertEquals("FIRST_PARTY_AUTHORITY_UNAVAILABLE", result.commandResult().errorCode()); + assertNull(((ErrorOutput) result.outputs().get(0).payload()).messageKey()); + verify(firstPartyConnectContextRegistry).find(1L); + verify(firstPartyConnectContextRegistry, never()).requireRetained(any()); + Mockito.verifyNoInteractions( + accountClient, gameInstanceRepository, gameplayPresenceLifecycleService); + verify(sessionContextService, never()).save(any()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + + @Test + void corruptFirstPartyLoginDeniesWithoutCredentialFallback() { + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(new IllegalStateException("corrupt")); + LoginCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "secret"), + "LOGIN demo@example.com secret"), + false); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + Mockito.verifyNoInteractions( + accountClient, gameInstanceRepository, gameplayPresenceLifecycleService); + verify(sessionContextService, never()).save(any()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java index f3ebe061c0..85f1e3701d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java @@ -63,6 +63,9 @@ void setUp() { @Test void moveSuccessResolvesDestinationLookWithDestinationContext() { + var retainedContext = + new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture().context(); + context = context.withFirstPartyConnectContext(retainedContext); LookResult destinationLook = LookResult.newBuilder() .setRoomInstance( @@ -111,6 +114,7 @@ void moveSuccessResolvesDestinationLookWithDestinationContext() { assertThat(result.responseOutput()).isEqualTo(destinationOutput); assertThat(result.updatedContext()).isNotNull(); assertThat(result.updatedContext().roomInstanceId()).isEqualTo("R-2045"); + assertThat(result.updatedContext().firstPartyConnectContext()).isSameAs(retainedContext); assertThat(result.updatedContext().loginName()).isEqualTo("emberline@example.com"); assertThat(result.updatedContext().characterName()).isEqualTo("Emberline"); verify(lookCommandHandler).resolveLook(result.updatedContext()); 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 87959b400f..c761b12f12 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 @@ -33,6 +33,7 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.BeforeEach; @@ -40,6 +41,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; @@ -887,149 +889,6 @@ void playIgnoresExistingBindingWithoutRoomRegion() { Mockito.verify(sessionContextService, never()).deleteBySessionId(22L, 9L); } - @Test - void firstPartyPlayRejectsMismatchedConnectScope() { - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", - 22L, - "demo", - "production", - 41L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle( - "1", - new TextCommand( - TextCommandType.PLAY, - List.of("sandbox", "preview", "Sora"), - "PLAY sandbox preview Sora")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - } - - @Test - void firstPartyPlayRejectsMismatchedWorldSlug() { - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", - 22L, - "sandbox", - "production", - 1L, - 1L, - "scope-1", - "jti-1", - "req-1", - "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - } - - @Test - void firstPartyPlayRejectsStalePointerVersion() { - gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", - 22L, - "demo", - "production", - 1L, - 8L, - "scope-1", - "jti-1", - "req-1", - "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - } - - @Test - void firstPartyPlayRejectsConnectContextMissingRealmSlug() { - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); - assertThat(joinedOutputText(result.outputs())) - .isEqualTo("ERROR CONNECT_CONTEXT_INVALID Connect context invalid"); - } - - @Test - void firstPartyPlayRejectsConnectContextMissingConnectScope() { - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); - } - - @Test - void firstPartyPlayRejectsConnectContextMissingConnectRequest() { - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); - } - @Test void playWithoutSessionReturnsLoginRequired() { when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.empty()); @@ -1115,11 +974,12 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + Mockito.verify(sessionContextService).findBySessionId(1L); + Mockito.verifyNoMoreInteractions(sessionContextService); Mockito.verifyNoInteractions( accountClient, entityManagementClient, moderationPolicyClient, - sessionContextService, gameplayPresenceLifecycleService, scriptEventPublisher); } @@ -1242,86 +1102,6 @@ void playRejectsIsolatedStateRealm() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); } - @Test - void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .get(1) - .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn( - Optional.of( - new FirstPartyConnectContext( - "123", 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", - "gw-1"))); - when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) - .thenReturn(Optional.empty()); - - PlayCommandHandlingResult result = - handler.handle( - "1", - new TextCommand( - TextCommandType.PLAY, - List.of("sandbox", "preview", "Sora"), - "PLAY sandbox preview Sora")); - - assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); - } - - @Test - void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .get(1) - .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - SessionContext context = - new SessionContext( - 1L, - 22L, - "123", - "first-party:123", - 0L, - null, - 0L, - null, - null, - null, - 41L, - "sandbox", - "preview", - 1L, - null, - "scope-persisted", - "req-persisted"); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) - .thenReturn(Optional.empty()); - - PlayCommandHandlingResult result = - handler.handle( - "1", - new TextCommand(TextCommandType.PLAY, List.of("sandbox", "Sora"), "PLAY sandbox Sora")); - - assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); - } - @Test void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing() { gameplayCatalogProperties @@ -1731,6 +1511,41 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWithUnavailableSessionContextReturnsRetryableAuthorityFailure() { + when(sessionContextService.findBySessionId(1L)) + .thenThrow(new SessionContextUnavailableException("session context unavailable", null)); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + sessionAuthenticationService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + + @Test + void playWithUnavailableSessionStoreReturnsRetryableAuthorityFailure() { + when(sessionContextService.findBySessionId(1L)) + .thenThrow(new DataAccessResourceFailureException("session store unavailable")); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verifyNoInteractions(sessionAuthenticationService, gameplayPresenceLifecycleService); + } + @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = @@ -2054,4 +1869,79 @@ private static GameplayCommand command(String commandId, String commandName, Str gameplayCommand.setCommandText(commandText); return gameplayCommand; } + + @Test + void firstPartyPlayRereadsCanonicalOwnerThenDeniesBeforeLegacyAdmissionEffects() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + FirstPartyConnectContext context = fixture.context(); + when(firstPartyConnectContextRegistry.find(1L)) + .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "hero"), "PLAY demo hero")); + assertThat(result.commandResult().errorCode()).isEqualTo("FIRST_PARTY_AUTHORITY_UNAVAILABLE"); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()).isNull(); + Mockito.verify(firstPartyConnectContextRegistry).find(1L); + Mockito.verify(firstPartyConnectContextRegistry, never()).requireRetained(Mockito.any()); + Mockito.verify(fixture.routes, Mockito.atLeast(2)) + .readCurrentTarget( + net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture.TENANT); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + sessionAuthenticationService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + + @Test + void playDefensivelyDeniesFirstPartyContextAddedAfterTopLevelCheck() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + FirstPartyConnectContext context = fixture.context(); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn(Optional.empty()) + .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); + SessionContext legacyContext = + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(legacyContext)); + + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "hero"), "PLAY demo hero")); + + assertThat(result.commandResult().errorCode()).isEqualTo("FIRST_PARTY_AUTHORITY_UNAVAILABLE"); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()).isNull(); + Mockito.verify(firstPartyConnectContextRegistry, Mockito.times(2)).find(1L); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); + } + + @Test + void changedFirstPartyOwnerDeniesPlayBeforeLegacyAdmissionEffects() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + FirstPartyConnectContext context = fixture.context(); + when(firstPartyConnectContextRegistry.find(1L)) + .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); + when(fixture.routes.readCurrentTarget( + net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture.TENANT)) + .thenReturn(null); + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "hero"), "PLAY demo hero")); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + sessionAuthenticationService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java index b80bb2ac03..3048066146 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java @@ -97,6 +97,26 @@ void preservesCompleteAggregateAndSeparatesNonSecretEvidence() throws Exception .doesNotContain("authToken", "compactJwt", "credential", "password"); } + @Test + void closeOverwritesOwnedCompactTokenAndRefusesFurtherSecretAccess() throws Exception { + var wire = response(claims()); + var result = decode(wire); + var ownedBytes = CanonicalGameplayLoginResult.class.getDeclaredField("compactJwt"); + ownedBytes.setAccessible(true); + byte[] privateBytes = (byte[]) ownedBytes.get(result); + assertThat(privateBytes) + .containsExactly(wire.getAuthToken().getBytes(StandardCharsets.US_ASCII)); + + result.close(); + result.close(); + + assertThat(privateBytes).containsOnly((byte) 0); + assertThatThrownBy(result::compactJwtBytes) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical LOGIN private result is closed"); + assertThat(result.evidence().accountId()).isEqualTo(ACCOUNT); + } + @ParameterizedTest @ValueSource( strings = { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java index 73a376a5e1..b4ed47b4df 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java @@ -23,6 +23,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -93,6 +95,58 @@ void deliverDropsStaleRecipientResolvedByGameplayIdentity() { verify(activeTransportSessionRegistry, never()).find(any(Long.class)); } + @Test + void unreadableRecipientDoesNotAbortDeliveryToLaterRecipients() { + SessionContext actor = + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + SessionContext healthyRecipient = + new SessionContext( + 43L, 22L, "789", "friend@example.com", 789L, "Sora", 1L, "R-1", "jwt", "en-NZ", 1L); + CommunicationRecipientView unreadableView = + CommunicationRecipientView.newBuilder() + .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) + .setRecipientId("456") + .build(); + CommunicationRecipientView healthyView = + CommunicationRecipientView.newBuilder() + .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) + .setRecipientId("789") + .build(); + SendCommunicationResponse response = + SendCommunicationResponse.newBuilder() + .setType(CommunicationType.TELL) + .setMessage("hello") + .addRecipientViews(unreadableView) + .addRecipientViews(healthyView) + .build(); + PlayerOutput output = PlayerOutput.notice("hello"); + PresentationProperties presentation = new PresentationProperties(); + + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 456L)) + .thenThrow(new SessionContextUnavailableException("retained context unreadable", null)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 789L)) + .thenReturn(Optional.of(healthyRecipient)); + when(communicationOutputMapper.recipientOutput(CommunicationType.TELL, healthyView, "hello")) + .thenReturn(output); + when(settingsResolver.presentation(healthyRecipient)).thenReturn(presentation); + when(outputRenderer.render(output, "en-NZ", presentation)).thenReturn("hello"); + when(activeTransportSessionRegistry.find(43L)).thenReturn(Optional.empty()); + + service.deliver(actor, response); + + verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 789L); + verify(settingsResolver).presentation(healthyRecipient); + assertThat( + meterRegistry + .counter( + "gamesession.communication.delivery.failed", + "role", + "communication_recipient_role_target") + .count()) + .isEqualTo(1.0); + } + @Test void deliverDropsStaleRecipientResolvedByGameplayName() { SessionContext actor = @@ -290,4 +344,56 @@ void deliverDoesNotBufferNonReplayableRecipientOutput() { verify(screenBufferService, never()) .append(any(Long.class), any(Long.class), any(Long.class), any()); } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void sendFailureRequestsOwnedCloseAndRetainsRegistrationUntilCallback(boolean closeFails) + throws Exception { + SessionContext actor = new SessionContext(41L, 22L, "123", 123L, 1L, "R-1", "jwt"); + SessionContext recipient = + new SessionContext( + 42L, 22L, "456", "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + var view = + CommunicationRecipientView.newBuilder() + .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) + .setRecipientId("456") + .build(); + var response = + SendCommunicationResponse.newBuilder() + .setType(CommunicationType.TELL) + .setMessage("hello") + .addRecipientViews(view) + .build(); + var output = PlayerOutput.notice("hello"); + var presentation = new PresentationProperties(); + var session = Mockito.mock(org.springframework.web.socket.WebSocketSession.class); + when(session.isOpen()).thenReturn(true); + when(session.getAttributes()).thenReturn(java.util.Map.of()); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 456L)) + .thenReturn(Optional.of(recipient)); + when(communicationOutputMapper.recipientOutput(CommunicationType.TELL, view, "hello")) + .thenReturn(output); + when(settingsResolver.presentation(recipient)).thenReturn(presentation); + when(outputRenderer.render(output, "en-NZ", presentation)).thenReturn("hello"); + when(activeTransportSessionRegistry.find(42L)).thenReturn(Optional.of(session)); + Mockito.doThrow(new java.io.IOException("send failed")).when(session).sendMessage(any()); + if (closeFails) { + Mockito.doThrow(new java.io.IOException("close failed")) + .when(session) + .close(any(org.springframework.web.socket.CloseStatus.class)); + } + service.deliver(actor, response); + verify(session) + .close( + org.springframework.web.socket.CloseStatus.SERVER_ERROR.withReason("internal_error")); + verify(activeTransportSessionRegistry, never()).unregister(anyLong(), any()); + assertThat( + meterRegistry + .counter( + "gamesession.communication.delivery.failed", + "role", + "communication_recipient_role_target") + .count()) + .isEqualTo(1.0); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java new file mode 100644 index 0000000000..d8e69dfc26 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; +import org.junit.jupiter.api.Test; + +class FirstPartyConnectContextResolutionTest { + @Test + void completeSessionRetainedBytesAreVerifiedWhenShortRegistryEntryExpires() { + var fixture = new FirstPartyReceivingFixture(); + var context = fixture.context(); + var session = + new SessionContext(1L, 22L, null, 0L, 0L, (String) null) + .withFirstPartyConnectContext(context); + var registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(1L)).thenReturn(Optional.empty()); + when(registry.requireRetained(context)) + .thenAnswer(invocation -> fixture.service.requireRetained(invocation.getArgument(0))); + var resolution = FirstPartyConnectContextResolution.resolve(1L, session, registry); + assertThat(resolution.invalid()).isFalse(); + assertThat(resolution.connectContext()).contains(context); + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(null); + assertThat(FirstPartyConnectContextResolution.resolve(1L, session, registry).invalid()) + .isTrue(); + } + + @Test + void registryLossDoesNotExtendPersistedConnectContextExpiry() { + var fixture = new FirstPartyReceivingFixture(); + var context = fixture.context(); + var session = + new SessionContext(1L, 22L, null, 0L, 0L, (String) null) + .withFirstPartyConnectContext(context); + var registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(1L)).thenReturn(Optional.empty()); + var expiredService = + new FirstPartyConnectContextService( + fixture.properties, + fixture.keySource, + fixture.routes, + Clock.fixed( + Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 31_000L), ZoneOffset.UTC), + fixture.meterRegistry); + when(registry.requireRetained(context)) + .thenAnswer(invocation -> expiredService.requireRetained(invocation.getArgument(0))); + + var resolution = FirstPartyConnectContextResolution.resolve(1L, session, registry); + + assertThat(resolution.invalid()).isTrue(); + assertThat(resolution.connectContext()).isEmpty(); + } + + @Test + void registryCorruptionOrUnavailabilityNeverBecomesAbsence() { + var registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(1L)).thenThrow(new IllegalStateException("corrupt")); + var resolution = FirstPartyConnectContextResolution.resolve(1L, null, registry); + assertThat(resolution.invalid()).isTrue(); + assertThat(resolution.connectContext()).isEmpty(); + } + + @Test + void validatedRegistryResultIsNotImmediatelyRevalidated() { + var fixture = new FirstPartyReceivingFixture(); + var context = fixture.context(); + var registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(1L)) + .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); + + var resolution = FirstPartyConnectContextResolution.resolve(1L, null, registry); + + assertThat(resolution.invalid()).isFalse(); + assertThat(resolution.connectContext()).contains(context); + verify(registry).find(1L); + verify(registry, never()).requireRetained(any()); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 100177c024..36cf229553 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -1,361 +1,180 @@ package net.firedevops.firemud.gamesession.service; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.*; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; +import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; import org.junit.jupiter.api.Test; class FirstPartyConnectContextServiceTest { - - @Test - void parseReadsJwtClaimsThroughInjectedUtil() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isPresent()); - FirstPartyConnectContext context = service.parse("token").orElseThrow(); - assertEquals("42", context.accountId()); - assertEquals(7L, context.tenantId()); - assertEquals("demo", context.worldSlug()); - assertEquals("production", context.realmSlug()); - assertEquals(9L, context.gameInstanceId()); - assertEquals(17L, context.pointerVersion()); - assertEquals("scope-1", context.connectScopeId()); - assertEquals("jti", context.connectTokenJti()); - assertEquals("request-connect-1", context.connectRequestId()); - assertEquals("request-1", context.gatewayRequestId()); - } - - @Test - void parseRejectsMalformedAccountSubjectClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("bad-number"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsZeroAccountClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("0"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsAccountSubjectMismatch() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("41"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsMalformedTenantClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn("not-a-number"); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - @Test - void parseRejectsMissingTenantClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(null); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void completeContextPreservesExactTupleMapsTimesAndSignedAbuseMetadata() { + var fixture = new FirstPartyReceivingFixture(); + var context = fixture.context(); + assertThat(context.claims().accountId()).isEqualTo(FirstPartyReceivingFixture.ACCOUNT); + assertThat(context.claims().authorityTuple()).isEqualTo(fixture.source().authorityTuple()); + assertThat(context.claims().membershipVersion()) + .isEqualTo(fixture.source().membershipVersion()); + assertThat(context.claims().connectTokenJti()).isEqualTo(fixture.source().connectTokenJti()); + assertThat(context.claims().replayAdmissionFence()).isEqualTo("5"); + assertThat(context.claims().issuedAtMillis()).isEqualTo(FirstPartyReceivingFixture.NOW); + assertThat(context.claims().verifiedAtMillis()).isEqualTo(FirstPartyReceivingFixture.NOW); + assertThat(context.claims().expiresAtMillis()) + .isEqualTo(FirstPartyReceivingFixture.NOW + 30_000L); + assertThat(context.claims().canonicalClientAddress()).isEqualTo("203.0.113.8"); + assertThat(context.claims().gatewayRequestId()).isEqualTo("gateway-1"); + assertThat(context.gameSessionTenantId()).isEqualTo(22L); + assertThat(context.runtimeGameInstanceId()).isEqualTo(41L); + assertThat(context.toString()).doesNotContain(context.compactJws(), context.accountId()); } @Test - void parseRejectsMissingWorldSlugClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn(""); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void rejectsOldHmacAndIncompleteTokensBeforeOwnerReads() { + var fixture = new FirstPartyReceivingFixture(); + clearInvocations(fixture.routes); + String hmac = + new JwtUtil("old-connect-context-secret-32-bytes-long", 30_000L) + .generateToken("77", java.util.Map.of()); + assertThat(fixture.service.parse(hmac)).isEmpty(); + assertThat(fixture.service.parse("incomplete.context")).isEmpty(); + assertThat( + fixture + .meterRegistry + .get("gamesession.first_party_connect_context.parse.failures") + .tag("reason", "invalid_envelope") + .counter() + .count()) + .isEqualTo(2.0); + assertOnlyFixedFailureMetricTags(fixture.meterRegistry); + verifyNoInteractions(fixture.routes); } @Test - void parseRejectsMissingRealmSlugClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn(""); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void missingDedicatedKeysAndMissingCurrentTargetDeny() { + var fixture = new FirstPartyReceivingFixture(); + var unavailable = + new FirstPartyConnectContextService( + fixture.properties, + kid -> { + throw new net.firedevops.firemud.common.security + .GatewayFirstPartyConnectContextEnvelope.KeySourceUnavailableException(); + }, + fixture.routes, + Clock.fixed(Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW), ZoneOffset.UTC), + fixture.meterRegistry); + assertThat(unavailable.parse(fixture.token())).isEmpty(); + assertThat( + fixture + .meterRegistry + .get("gamesession.first_party_connect_context.parse.failures") + .tag("reason", "key_unavailable") + .counter() + .count()) + .isEqualTo(1.0); + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)) + .thenThrow(new CanonicalPlayerRouteReadService.ReadUnavailableException("missing owner")); + assertThat(fixture.service.parse(fixture.token())).isEmpty(); + assertThat( + fixture + .meterRegistry + .get("gamesession.first_party_connect_context.parse.failures") + .tag("reason", "owner_unavailable") + .counter() + .count()) + .isEqualTo(1.0); + assertOnlyFixedFailureMetricTags(fixture.meterRegistry); } @Test - void parseRejectsMissingConnectScopeIdClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn(" "); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void completeRetainedBytesMustBeReverifiedAndExpiredOrChangedTargetsDeny() throws Exception { + var fixture = new FirstPartyReceivingFixture(); + var context = fixture.context(); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(context); + } + FirstPartyConnectContext retained; + try (ObjectInputStream input = + new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + retained = (FirstPartyConnectContext) input.readObject(); + } + assertThatThrownBy(retained::claims).isInstanceOf(IllegalStateException.class); + assertThat(fixture.service.requireRetained(retained).claims()).isEqualTo(context.claims()); + var expired = + new FirstPartyConnectContextService( + fixture.properties, + fixture.keySource, + fixture.routes, + Clock.fixed( + Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 31_000L), ZoneOffset.UTC), + fixture.meterRegistry); + assertThatThrownBy(() -> expired.requireRetained(retained)) + .isInstanceOf(IllegalStateException.class); + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(null); + assertThatThrownBy(() -> fixture.service.requireRetained(retained)) + .isInstanceOf(IllegalStateException.class); } @Test - void parseRejectsMissingConnectRequestIdClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn(""); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void rejectsEachChangedCanonicalScopeBeforeReturningAContext() { + var fixture = new FirstPartyReceivingFixture(); + var original = fixture.target(); + for (int index = 0; index < 9; index++) { + var changed = org.mockito.Mockito.spy(original); + switch (index) { + case 0 -> doReturn(java.util.UUID.randomUUID()).when(changed).canonicalTenantId(); + case 1 -> doReturn(java.util.UUID.randomUUID()).when(changed).realmId(); + case 2 -> doReturn("other-world").when(changed).worldSlug(); + case 3 -> doReturn("other-realm").when(changed).realmSlug(); + case 4 -> doReturn(java.util.UUID.randomUUID()).when(changed).playableStateNamespaceId(); + case 5 -> doReturn("ISOLATED").when(changed).playableStateScope(); + case 6 -> doReturn(java.util.UUID.randomUUID()).when(changed).canonicalGameInstanceId(); + case 7 -> doReturn(4L).when(changed).catalogRevision(); + case 8 -> doReturn(18L).when(changed).pointerVersion(); + default -> throw new AssertionError(); + } + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(changed); + assertThat(fixture.service.parse(fixture.token())).as("scope index %d", index).isEmpty(); + } + assertThat( + fixture + .meterRegistry + .get("gamesession.first_party_connect_context.parse.failures") + .tag("reason", "target_mismatch") + .counter() + .count()) + .isEqualTo(9.0); + assertOnlyFixedFailureMetricTags(fixture.meterRegistry); } @Test - void parseRejectsMissingPointerVersionClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(0L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); + void successfulParseDoesNotIncrementFailureCounter() { + var fixture = new FirstPartyReceivingFixture(); - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); + assertThat(fixture.service.parse(fixture.token())).isPresent(); - assertTrue(service.parse("token").isEmpty()); + assertThat(fixture.meterRegistry.getMeters()).isEmpty(); } - @Test - void parseRejectsMissingPointerVersionClaimWhenNotPresent() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(null); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + private static void assertOnlyFixedFailureMetricTags(SimpleMeterRegistry registry) { + assertThat(registry.getMeters()) + .allSatisfy( + meter -> { + assertThat(meter.getId().getName()) + .isEqualTo("gamesession.first_party_connect_context.parse.failures"); + assertThat(meter.getId().getTags()).hasSize(1); + assertThat(meter.getId().getTag("reason")) + .isIn( + "key_unavailable", + "invalid_envelope", + "owner_unavailable", + "target_mismatch"); + }); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 2413e52a29..528fe70337 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -450,18 +449,6 @@ void sameBootstrapRouteRejectsPlayableStateScopeChanges() { assertThat(GameplayAdmissionPointerSnapshots.sameBootstrapRoute(existing, incoming)).isFalse(); } - @Test - void sameBootstrapRouteRejectsFirstPartyConnectContextWhenRoutingIdentityChanges() { - FirstPartyConnectContext existing = - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); - - assertThat( - GameplayAdmissionPointerSnapshots.sameBootstrapRoute( - existing, 22L, 1L, "sandbox", "production", 7L)) - .isFalse(); - } - @Test void sameBootstrapRouteFailsClosedForScopeOnlyContext() { SessionContext existing = bootstrapShell(22L, 1L, null, null, 0L, "SHARED"); @@ -478,18 +465,6 @@ void sameBootstrapRouteAcceptsTwoContextsWithNoRoutingValues() { assertThat(GameplayAdmissionPointerSnapshots.sameBootstrapRoute(existing, incoming)).isTrue(); } - @Test - void sameBootstrapRouteAcceptsFirstPartyConnectContextWithCaseInsensitiveRoutingIdentity() { - FirstPartyConnectContext existing = - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); - - assertThat( - GameplayAdmissionPointerSnapshots.sameBootstrapRoute( - existing, 22L, 1L, "DEMO", "PRODUCTION", 7L)) - .isTrue(); - } - private static SessionContext bootstrapShell( long tenantId, long bootstrapGameInstanceId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java index d8acfee169..928e529417 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java @@ -20,7 +20,9 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.function.BooleanSupplier; import java.util.function.Function; +import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; @@ -106,7 +108,8 @@ void commitsAbandonmentBeforeQualifiedClosureAndFrozenRequestBeforeAccountOutsid assertThat(fixture.snapshot.frozenRetirementRequest().orElseThrow().hasTokenWitness()) .isFalse(); assertThat(fixture.snapshot.retainedReceipt()).contains(fixture.response); - verify(fixture.account, never()).authenticate(any()); + verify(fixture.account, never()) + .authenticate(any(AuthenticateRequest.class), any(BooleanSupplier.class)); } @ParameterizedTest @@ -213,7 +216,8 @@ void secretLossUsesOnlyOriginalCoordinatesAndKeepsAccountPendingAcrossRedrives() assertThat(fixture.snapshot.verifiedWitness()).isEmpty(); verify(fixture.account, times(2)) .retireInitialGameplayLogin(InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null)); - verify(fixture.account, never()).authenticate(any()); + verify(fixture.account, never()) + .authenticate(any(AuthenticateRequest.class), any(BooleanSupplier.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java new file mode 100644 index 0000000000..aa3b50cc4e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java @@ -0,0 +1,409 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +/** Source ordering and owned-buffer proof; no Account, Redis, wire, or admission claim. */ +class InitialGameplayLoginOwnerTest { + private static final UUID ACCOUNT = UUID.fromString("2bba6eb7-4874-47e1-af9d-caa9e2d5ef72"); + private static final UUID JTI = UUID.fromString("85c3976c-ef18-4e0d-9f7d-0466854973c4"); + + @Test + void commitsCoordinatesCreatesPendingAuthenticatesRecordsWitnessThenInstallsExactResult() { + var success = successfulOutcome(); + var fixture = success.fixture(); + var outcome = success.outcome(); + var result = success.result(); + var secret = success.secret(); + var coordinates = outcome.coordinates(); + AuthenticateRequest request = fixture.accountRequest; + + assertThat(outcome.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + assertThat(outcome.failureCode()).isEmpty(); + assertThat(outcome.toString()).doesNotContain("private-secret"); + assertThat(coordinates.requestId()).isNotEqualTo(coordinates.callerContextId()); + assertThat(coordinates.requestId().version()).isEqualTo(4); + assertThat(coordinates.callerContextId().version()).isEqualTo(4); + assertThat(coordinates.expectedAttemptFence()).isEqualTo(1); + assertThat(request.getRequestId()).isEqualTo(coordinates.requestId().toString()); + assertThat(request.getSourceContext().getCallerContextId()) + .isEqualTo(coordinates.callerContextId().toString()); + assertThat(request.getSourceContext().getTransportClassValue()).isEqualTo(1); + assertThat(request.getPassword()).isEqualTo("original-private-secret"); + assertThat(secret).containsOnly('\0'); + verify(result, never()).close(); + var transferredResult = outcome.takePrivateResult().orElseThrow(); + assertThat(transferredResult).isSameAs(result); + outcome.close(); + verify(result, never()).close(); + transferredResult.close(); + verify(result).close(); + InOrder order = inOrder(fixture.cleanup, fixture.contexts, fixture.account); + order.verify(fixture.cleanup).reserve(coordinates); + order.verify(fixture.contexts).createPending(coordinates); + order.verify(fixture.account).authenticate(any(AuthenticateRequest.class), any()); + order.verify(fixture.cleanup).recordVerifiedResult(coordinates, result); + order.verify(fixture.contexts).install(coordinates, result); + verify(fixture.cleanup, never()).abandonAndRetire(coordinates); + } + + @Test + void closingInstalledOutcomeBeforeTransferWipesAndCleansTheExactOriginal() { + var success = successfulOutcome(); + var outcome = success.outcome(); + var result = success.result(); + + outcome.close(); + + verify(result).close(); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + assertThat(outcome.custodyLossCleanup().orElseThrow().status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + org.assertj.core.api.Assertions.assertThatThrownBy(outcome::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThat(success.secret()).containsOnly('\0'); + } + + @Test + void transferredResultAndOutcomeCloseLeaveCleanupOwnershipToExplicitLossCallback() { + var success = successfulOutcome(); + var outcome = success.outcome(); + var result = success.result(); + var coordinates = outcome.coordinates(); + var transferred = outcome.takePrivateResult().orElseThrow(); + + outcome.close(); + + assertThat(transferred).isSameAs(result); + verify(result, never()).close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + + doThrow(new IllegalStateException("qualified cleanup unavailable")) + .when(success.fixture().cleanup) + .abandonAndRetire(coordinates); + var cleanup = outcome.abandonOriginalAfterCustodyLoss(); + + assertThat(cleanup.coordinates()).isEqualTo(coordinates); + assertThat(cleanup.status()).isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + verify(result).close(); + verify(success.fixture().cleanup).abandonAndRetire(coordinates); + } + + private static SuccessfulOutcome successfulOutcome() { + var fixture = new Fixture(); + var secret = "original-private-secret".toCharArray(); + var credentials = presentation(secret); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + fixture.accountRequest = invocation.getArgument(0); + return result; + }); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.cleanup.recordVerifiedResult(any(), any())) + .thenAnswer( + invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + when(fixture.contexts.install(any(), any())) + .thenAnswer(invocation -> Optional.of(installed(invocation.getArgument(0)))); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + return new SuccessfulOutcome(fixture, fixture.owner.receive(credentials), result, secret); + } + + @Test + void uncertainPendingCreationSelectsOriginalCleanupWithoutAccountDispatch() { + var fixture = new Fixture(); + var secret = "still-private".toCharArray(); + var credentials = presentation(secret); + when(fixture.contexts.createPending(any())).thenReturn(Optional.empty()); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(credentials); + + assertThat(outcome.status()).isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + assertThat(outcome.cleanupStatus()).isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + assertThat(secret).containsOnly('\0'); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + verifyNoInteractions(fixture.account); + verify(fixture.contexts, never()).install(any(), any()); + } + + @Test + void ambiguousAuthenticateFailureSelectsCleanupAndNeverInstalls() { + var fixture = new Fixture(); + var secret = "transient-secret".toCharArray(); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(presentation(secret)); + + assertThat(outcome.status()).isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + assertThat(outcome.failureCode()).contains("UNAVAILABLE"); + assertThat(secret).containsOnly('\0'); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + verify(fixture.contexts, never()).install(any(), any()); + } + + @Test + void callerCancellationWhileCredentialCustodyIsCurrentRemainsCancelled() { + var fixture = new Fixture(); + var credentials = presentation("transient-secret".toCharArray()); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) + .thenThrow(Status.CANCELLED.asRuntimeException()); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(credentials); + + assertThat(outcome.failureCode()).contains("CANCELLED"); + assertThat(credentials.isCurrent()).isFalse(); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + } + + @Test + void cancelledAccountCallAfterCredentialCustodyLossReportsCustodyLost() { + var fixture = new Fixture(); + var credentials = presentation("transient-secret".toCharArray()); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + credentials.close(); + throw Status.CANCELLED.asRuntimeException(); + }); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(credentials); + + assertThat(outcome.failureCode()).contains("CUSTODY_LOST"); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + } + + @Test + void lostCustodyAfterVerifiedAccountResponseRecordsWitnessThenCleansWithoutInstall() { + var fixture = new Fixture(); + var secret = "transient-secret".toCharArray(); + var credentials = presentation(secret); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + credentials.close(); + return result; + }); + when(fixture.cleanup.recordVerifiedResult(any(), any())) + .thenAnswer( + invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(credentials); + + assertThat(outcome.status()).isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + assertThat(outcome.failureCode()).contains("CUSTODY_LOST"); + assertThat(secret).containsOnly('\0'); + verify(fixture.cleanup).recordVerifiedResult(any(), any()); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + verify(fixture.contexts, never()).install(any(), any()); + verify(result).close(); + } + + @Test + void unavailableWitnessReadbackStillUsesExactOriginalCleanupFreeze() { + var fixture = new Fixture(); + var secret = "transient-secret".toCharArray(); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())).thenReturn(result); + when(fixture.cleanup.recordVerifiedResult(any(), any())) + .thenThrow(new IllegalStateException("journal readback unavailable")); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(presentation(secret)); + + assertThat(outcome.status()).isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + assertThat(secret).containsOnly('\0'); + verify(fixture.cleanup).recordVerifiedResult(outcome.coordinates(), result); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + verify(fixture.contexts, never()).install(any(), any()); + verify(result).close(); + } + + @Test + void failedExactInstallClosesOriginalAndRetiresFromTheSameInvocationResult() { + var fixture = new Fixture(); + var secret = "transient-secret".toCharArray(); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); + when(fixture.contexts.createPending(any())) + .thenAnswer( + invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + when(fixture.account.authenticate(any(AuthenticateRequest.class), any())).thenReturn(result); + when(fixture.cleanup.recordVerifiedResult(any(), any())) + .thenAnswer( + invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + when(fixture.contexts.install(any(), any())).thenReturn(Optional.empty()); + when(fixture.cleanup.abandonAndRetire(any())) + .thenAnswer(invocation -> held(invocation.getArgument(0))); + + var outcome = fixture.owner.receive(presentation(secret)); + + assertThat(outcome.status()).isEqualTo(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + assertThat(secret).containsOnly('\0'); + verify(fixture.cleanup).recordVerifiedResult(any(), any()); + verify(fixture.cleanup).abandonAndRetire(outcome.coordinates()); + verify(result).close(); + } + + private static InitialGameplayLoginCredentialPresentation presentation(char[] secret) { + return new InitialGameplayLoginCredentialPresentation( + "player@example.test", "203.0.113.10", secret); + } + + private static InitialGameplayLoginJournalSnapshot snapshot( + InitialGameplayLoginAttemptCoordinates coordinates) { + return new InitialGameplayLoginJournalSnapshot( + coordinates, false, Optional.empty(), Optional.empty(), Optional.empty()); + } + + private static InitialGameplayLoginJournalSnapshot snapshotWithWitness( + InitialGameplayLoginAttemptCoordinates coordinates, CanonicalGameplayLoginResult result) { + var evidence = result.evidence(); + var witness = + InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + return new InitialGameplayLoginJournalSnapshot( + coordinates, false, Optional.of(witness), Optional.empty(), Optional.empty()); + } + + private static NonSecretEvidence evidence(InitialGameplayLoginAttemptCoordinates coordinates) { + return new NonSecretEvidence( + ACCOUNT, + coordinates.requestId(), + coordinates.callerContextId(), + JTI, + "a".repeat(64), + "game-session-account-delegation/v1", + 1000, + 1000, + 1200, + "1", + "3", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY); + } + + private static InitialGameplayLoginContextState installed( + InitialGameplayLoginAttemptCoordinates coordinates) { + var state = mock(InitialGameplayLoginContextState.class); + when(state.state()).thenReturn(InitialGameplayLoginContextState.State.INSTALLED); + when(state.coordinates()).thenReturn(coordinates); + return state; + } + + private static InitialGameplayLoginCleanupOwner.CleanupObservation held( + InitialGameplayLoginAttemptCoordinates coordinates) { + return new InitialGameplayLoginCleanupOwner.CleanupObservation( + coordinates, + InitialGameplayLoginCleanupOwner.Status.HELD, + Optional.empty(), + Optional.empty()); + } + + private static final class Fixture { + private final InitialGameplayLoginContextRedisClient contexts = + mock(InitialGameplayLoginContextRedisClient.class); + private final InitialGameplayLoginCleanupOwner cleanup = + mock(InitialGameplayLoginCleanupOwner.class); + private final CanonicalGameplayLoginAccountClient account = + mock(CanonicalGameplayLoginAccountClient.class); + private final InitialGameplayLoginOwner owner = + new InitialGameplayLoginOwner(contexts, cleanup, account); + private InitialGameplayLoginAttemptCoordinates coordinates; + private AuthenticateRequest accountRequest; + + private Fixture() { + when(cleanup.reserve(any())) + .thenAnswer( + invocation -> { + coordinates = invocation.getArgument(0); + return snapshot(coordinates); + }); + when(account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + invocation -> { + accountRequest = invocation.getArgument(0); + return null; + }); + } + } + + private record SuccessfulOutcome( + Fixture fixture, + InitialGameplayLoginOwner.Outcome outcome, + CanonicalGameplayLoginResult result, + char[] secret) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java new file mode 100644 index 0000000000..4556a8d7a5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +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 io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.cache.ScreenBufferService; +import net.firedevops.firemud.gamesession.config.EffectiveSettingsResolver; +import net.firedevops.firemud.gamesession.config.PresentationProperties; +import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.presentation.PromptBurstCoordinator; +import net.firedevops.firemud.gamesession.presentation.PromptComposer; +import net.firedevops.firemud.gamesession.websocket.WebSocketOutputProjector; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketSession; + +class PlayerOutputDeliveryServiceTest { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void sendFailureRequestsOwnedCloseAndRetainsRegistrationUntilCallback(boolean closeFails) + throws Exception { + var registry = mock(ActiveTransportSessionRegistry.class); + var settings = mock(EffectiveSettingsResolver.class); + var projector = mock(WebSocketOutputProjector.class); + var bursts = mock(PromptBurstCoordinator.class); + var session = mock(WebSocketSession.class); + var context = new SessionContext(41L, 22L, "123", 123L, 1L, "R-1", "jwt"); + var output = PlayerOutput.notice("hello"); + var presentation = new PresentationProperties(); + when(registry.find(41L)).thenReturn(Optional.of(session)); + when(session.isOpen()).thenReturn(true); + when(settings.presentation(context)).thenReturn(presentation); + when(bursts.applyPromptWindow( + anyString(), any(), any(), org.mockito.ArgumentMatchers.eq(false))) + .thenAnswer(invocation -> invocation.getArgument(2)); + when(projector.projectPlayerOutput(session, output, null, presentation)).thenReturn("hello"); + doThrow(new IOException("send failed")).when(session).sendMessage(any()); + if (closeFails) { + doThrow(new IOException("close failed")).when(session).close(any(CloseStatus.class)); + } + var metrics = new SimpleMeterRegistry(); + try { + var service = + new PlayerOutputDeliveryService( + registry, + mock(ScreenBufferService.class), + settings, + projector, + mock(PromptComposer.class), + bursts, + metrics); + service.deliver(context, List.of(output), false); + verify(session).close(CloseStatus.SERVER_ERROR.withReason("internal_error")); + verify(registry, never()).unregister(anyLong(), any()); + assertThat(metrics.counter("gamesession.output.delivery.failed", "kind", "notice").count()) + .isEqualTo(1.0); + } finally { + metrics.close(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index b9bc2b7024..0b6d52ee7f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -106,7 +106,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { } @Test - void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity() { + void oldSelectorFragmentsFailClosedEvenWithoutAccountIdentity() { SessionContext context = new SessionContext( 1L, @@ -127,7 +127,7 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( "scope-persisted", "request-123"); - assertFalse(context.hasPartialPersistedFirstPartyConnectContext()); + assertTrue(context.hasPartialPersistedFirstPartyConnectContext()); assertTrue(context.persistedFirstPartyConnectContext().isEmpty()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java new file mode 100644 index 0000000000..fdf9ea431e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.springframework.web.socket.WebSocketSession; + +class InMemoryActiveTransportSessionRegistryTest { + @Test + void currentRawTransportIsRemovedAndReportsOwnershipOnce() { + var registry = new InMemoryActiveTransportSessionRegistry(); + WebSocketSession session = session("current"); + registry.register(41L, session); + assertThat(registry.unregister(41L, session)).isTrue(); + assertThat(registry.find(41L)).isEmpty(); + assertThat(registry.unregister(41L, session)).isFalse(); + } + + @Test + void registeredDecoratorIsAlsoAnExactOwnerForDeliveryCallers() { + var registry = new InMemoryActiveTransportSessionRegistry(); + registry.register(41L, session("current")); + WebSocketSession decorated = registry.find(41L).orElseThrow(); + assertThat(registry.unregister(41L, decorated)).isTrue(); + assertThat(registry.find(41L)).isEmpty(); + } + + @Test + void rejectedAndReplacedTransportsCannotRemoveTheIncumbent() { + var registry = new InMemoryActiveTransportSessionRegistry(); + WebSocketSession old = session("old"); + WebSocketSession current = session("current"); + registry.register(41L, old); + registry.register(41L, current); + WebSocketSession incumbent = registry.find(41L).orElseThrow(); + assertThat(registry.unregister(41L, old)).isFalse(); + assertThat(registry.unregister(41L, session("rejected"))).isFalse(); + assertThat(registry.unregister(41L, session("current"))).isFalse(); + assertThat(registry.find(41L)).contains(incumbent); + assertThat(registry.unregister(41L, current)).isTrue(); + } + + private WebSocketSession session(String id) { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getId()).thenReturn(id); + return session; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 8656e71570..08f44e47c1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -29,6 +29,8 @@ class RedisFirstPartyConnectContextRegistryTest { private final RedisTemplate redisTemplate = mock(RedisTemplate.class); private final ValueOperations valueOperations = mock(ValueOperations.class); private RedisFirstPartyConnectContextRegistry registry; + private final net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture fixture = + new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); @BeforeEach void setUp() { @@ -52,14 +54,13 @@ void setUp() { FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); properties.setTtlMs(1500L); - registry = new RedisFirstPartyConnectContextRegistry(redisTemplate, properties); + registry = + new RedisFirstPartyConnectContextRegistry(redisTemplate, properties, fixture.service); } @Test void registerStoresContextWithShortTtl() { - FirstPartyConnectContext context = - new FirstPartyConnectContext( - "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + FirstPartyConnectContext context = fixture.context(); registry.register(91L, context); @@ -74,9 +75,7 @@ void registerStoresContextWithShortTtl() { @Test void unregisterRemovesStoredContext() { - FirstPartyConnectContext context = - new FirstPartyConnectContext( - "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + FirstPartyConnectContext context = fixture.context(); registry.register(91L, context); registry.unregister(91L); @@ -90,24 +89,9 @@ void unreadableRetainedContextFailsClosedWithoutDeletingOrOverwritingEvidence() String key = "sessionctx:first-party:91:connect-context"; when(valueOperations.get(key)).thenThrow(new SerializationException("old record shape")); - assertEquals(Optional.empty(), registry.find(91L)); + assertThrows(IllegalStateException.class, () -> registry.find(91L)); - assertThrows( - IllegalStateException.class, - () -> - registry.register( - 91L, - new FirstPartyConnectContext( - "77", - 22L, - "demo", - "production", - 41L, - 17L, - "scope-1", - "jti-2", - "req-2", - "gateway-1"))); + assertThrows(IllegalStateException.class, () -> registry.register(91L, fixture.context())); registry.unregister(91L); verify(redisTemplate, never()).delete(key); @@ -120,24 +104,9 @@ void wrongRetainedValueFailsClosedWithoutOverwritingEvidence() { Object retainedEvidence = "serialized record from an incompatible shape"; store.put(key, retainedEvidence); - assertEquals(Optional.empty(), registry.find(91L)); + assertThrows(IllegalStateException.class, () -> registry.find(91L)); - assertThrows( - IllegalStateException.class, - () -> - registry.register( - 91L, - new FirstPartyConnectContext( - "77", - 22L, - "demo", - "production", - 41L, - 17L, - "scope-1", - "jti-2", - "req-2", - "gateway-1"))); + assertThrows(IllegalStateException.class, () -> registry.register(91L, fixture.context())); registry.unregister(91L); assertEquals(retainedEvidence, store.get(key)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index f5757a4a1f..6a39fb10fa 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -45,23 +45,26 @@ void setUp() { @Test void applyPreservesRoutingBundleWhenUpdatingRoom() { + var retainedContext = + new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture().context(); SessionContext current = new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 7001L, - "demo", - 1L, - "R-1021", - "jwt-token", - "en-NZ", - 1L, - "demo", - "production", - 7L, - "SHARED"); + 41L, + 22L, + "123", + "demo@example.com", + 7001L, + "demo", + 1L, + "R-1021", + "jwt-token", + "en-NZ", + 1L, + "demo", + "production", + 7L, + "SHARED") + .withFirstPartyConnectContext(retainedContext); when(valueOperations.get("sessionctx:22:41:context")).thenReturn(current); when(valueOperations.get("sessionctx:22:41:movement-effect:tfx-1")).thenReturn(null); @@ -71,6 +74,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { SessionContext updated = result.context(); assertNotNull(updated); assertEquals("R-2045", updated.roomInstanceId()); + assertEquals(retainedContext, updated.firstPartyConnectContext()); assertEquals("demo", updated.worldSlug()); assertEquals("production", updated.realmSlug()); assertEquals(7L, updated.pointerVersion()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 18517fb38e..381ea957b9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -156,12 +157,13 @@ void findByGameplayIdentityReturnsPersistedContext() { } @Test - void unreadableRetainedContextFailsClosedAndDoesNotBlockFreshReauthentication() { + void unreadableRetainedContextFailsClosedWithoutTreatingItAsAbsence() { String retainedKey = "sessionctx:10:1:context"; when(valueOperations.get(retainedKey)) .thenThrow(new SerializationException("old SessionContext record shape")); - assertEquals(Optional.empty(), service.findByTenantAndSessionId(10L, 1L)); + assertThrows( + SessionContextUnavailableException.class, () -> service.findByTenantAndSessionId(10L, 1L)); assertThrows( SerializationException.class, () -> service.deleteBySessionId(10L, 1L), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/FirstPartyReceivingFixture.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/FirstPartyReceivingFixture.java new file mode 100644 index 0000000000..fe9cd074c5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/FirstPartyReceivingFixture.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.gamesession.support; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.*; +import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextService; +import org.mockito.Mockito; + +/** Controlled RSA and owner results; never producer or deployed runtime qualification. */ +public final class FirstPartyReceivingFixture { + public static final long NOW = 1_800_000_000_000L; + public static final UUID ACCOUNT = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + public static final UUID TENANT = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + public static final UUID REALM = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + public static final UUID NAMESPACE = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + public static final UUID INSTANCE = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + private static final class KeyPairHolder { + private static final KeyPair KEY_PAIR = generateKeyPair(); + + private static KeyPair generateKeyPair() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + } + + public final KeyPair keys; + public final CanonicalPlayerRouteReadService routes = + Mockito.mock(CanonicalPlayerRouteReadService.class); + public final FirstPartyConnectContextProperties properties = + new FirstPartyConnectContextProperties(); + public final SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + public final GatewayVerificationKeySource keySource; + public final FirstPartyConnectContextService service; + + public FirstPartyReceivingFixture() { + keys = KeyPairHolder.KEY_PAIR; + keySource = kid -> "gateway-test".equals(kid) ? (RSAPublicKey) keys.getPublic() : null; + Mockito.when(routes.readCurrentTarget(TENANT)).thenReturn(target()); + service = + new FirstPartyConnectContextService( + properties, + keySource, + routes, + Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC), + meterRegistry); + } + + public CanonicalPlayableTarget target() { + return new CanonicalPlayableTarget( + "firemud-test", + "tenant", + TENANT, + "demo", + "Demo", + REALM, + "production", + "Production", + 22L, + 41L, + NAMESPACE, + "SHARED", + INSTANCE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + 7L, + 3L, + 17L, + "d".repeat(64), + 1L, + "initial-request", + "a".repeat(64), + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .NO_PRIOR_POINTER, + null, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "sha256:" + "b".repeat(64), + 9L, + "sha256:" + "c".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.ofEpochMilli(NOW - 1000L), + "PRESEEDED"); + } + + public GameplayConnectSource source() { + return new GameplayConnectSource( + ACCOUNT, + TENANT, + REALM, + "demo", + "production", + NAMESPACE, + "SHARED", + INSTANCE, + "17", + "3", + "scope-1", + "request-1", + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "3"), + List.of(), + null, + Map.of()), + Map.of(TENANT.toString(), "4"), + "a".repeat(64), + "5", + null, + null, + NOW / 1000L + 30L); + } + + public String token() { + return GatewayFirstPartyConnectContextEnvelope.sign( + source(), + new GatewayContextMetadata("203.0.113.8", "gateway-1", NOW, NOW, NOW + 30_000L), + new GatewaySigningKey("gateway-test", keys.getPrivate())); + } + + public FirstPartyConnectContext context() { + return service.parse(token()).orElseThrow(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 15fd6594b9..1b7861d0de 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.websocket; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; @@ -29,7 +30,6 @@ import net.firedevops.firemud.gamesession.presentation.PromptBurstCoordinator; import net.firedevops.firemud.gamesession.presentation.PromptComposer; import net.firedevops.firemud.gamesession.service.ActiveTransportSessionRegistry; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -38,8 +38,10 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; @@ -124,7 +126,8 @@ private GameSessionWebSocketHandler handlerWithMetadata( } @Test - void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { + void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected() + throws Exception { when(session.getAttributes()) .thenReturn( Map.of( @@ -134,48 +137,24 @@ void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { "first_party_web", GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, "token")); - FirstPartyConnectContext connectContext = - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); - when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - List.of( - pointer( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.empty()); handler.afterConnectionEstablished(session); - verify(firstPartyConnectContextRegistry).register(41L, connectContext); - verify(sessionContextService) - .save( + verify(session) + .close( argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && "demo".equals(context.worldSlug()) - && "production".equals(context.realmSlug()) - && context.pointerVersion() == 3L - && "SHARED".equals(context.playableStateScope()) - && "scope-1".equals(context.connectScopeId()) - && "req-1".equals(context.connectRequestId()))); + status -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + verify(firstPartyConnectContextRegistry, never()).register(Mockito.anyLong(), Mockito.any()); + verify(sessionContextService, never()).save(Mockito.any()); } @Test - void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected() - throws Exception { + void messageStopsWhenFirstPartyBootstrapContextCannotBeRestored() throws Exception { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + String token = fixture.token(); when(session.getAttributes()) .thenReturn( Map.of( @@ -184,10 +163,20 @@ void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected( GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web", GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, - "token")); - when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.empty()); + token)); + when(firstPartyConnectContextService.parse(token)) + .thenAnswer(invocation -> fixture.service.parse(invocation.getArgument(0))) + .thenReturn(Optional.empty()); + when(firstPartyConnectContextService.requireRetained(any())) + .thenAnswer(invocation -> fixture.service.requireRetained(invocation.getArgument(0))); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(session)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) + .thenReturn(Optional.empty()); + TextCommand command = new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"); + when(parser.parse("LOOK")).thenReturn(command); handler.afterConnectionEstablished(session); + handler.handleMessage(session, new TextMessage("LOOK")); verify(session) .close( @@ -195,45 +184,29 @@ void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected( status -> status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); - verify(firstPartyConnectContextRegistry, never()).register(Mockito.anyLong(), Mockito.any()); - verify(sessionContextService, never()).save(Mockito.any()); + verify(interpreter, never()) + .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); + verify(session, never()).sendMessage(any()); } @Test - void afterConnectionEstablishedRejectsFirstPartyContextWhenRetainedStateCannotBeRegistered() + void establishmentClosesGenericTransportWithoutReplacingIncumbentWhenPointerReadFails() throws Exception { + WebSocketSession incumbent = Mockito.mock(WebSocketSession.class); when(session.getAttributes()) .thenReturn( Map.of( GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", - GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, - "first_party_web", - GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, - "token")); - FirstPartyConnectContext connectContext = - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); - when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); + GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, + "22", + GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR, + "7")); + when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) + .thenReturn(Optional.empty()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - List.of( - pointer( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); - Mockito.doThrow(new IllegalStateException("retained context is unreadable")) - .when(firstPartyConnectContextRegistry) - .register(41L, connectContext); + .thenThrow(new IllegalStateException("pointer store unavailable")); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(incumbent)); handler.afterConnectionEstablished(session); @@ -241,33 +214,31 @@ void afterConnectionEstablishedRejectsFirstPartyContextWhenRetainedStateCannotBe .close( argThat( status -> - status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() - && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); - verify(sessionAuthenticationService, never()).resolveUnverifiedSessionContext(22L, 41L); - verify(sessionContextService, never()).save(Mockito.any()); - verify(firstPartyConnectContextRegistry).register(41L, connectContext); + status.getCode() == 1013 + && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); + verify(activeTransportSessionRegistry, never()).register(41L, session); + verify(activeTransportSessionRegistry, never()).unregister(Mockito.anyLong(), Mockito.any()); } @Test - void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityFails() - throws Exception { + void messageStopsWhenGenericBootstrapPointerReadFails() throws Exception { when(session.getAttributes()) .thenReturn( Map.of( GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", - GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, - "first_party_web", - GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, - "token")); - FirstPartyConnectContext connectContext = - new FirstPartyConnectContext( - "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); - when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); + GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, + "22", + GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR, + "7")); + when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) + .thenReturn(Optional.empty()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenThrow(new IllegalStateException("database unavailable")); + .thenThrow(new IllegalStateException("pointer store unavailable")); + TextCommand command = new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"); + when(parser.parse("LOOK")).thenReturn(command); - handler.afterConnectionEstablished(session); + handler.handleMessage(session, new TextMessage("LOOK")); verify(session) .close( @@ -275,8 +246,102 @@ void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityF status -> status.getCode() == 1013 && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); - verify(firstPartyConnectContextRegistry, never()).register(Mockito.anyLong(), Mockito.any()); - verify(sessionContextService, never()).save(Mockito.any()); + verify(interpreter, never()) + .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); + verify(session, never()).sendMessage(any()); + } + + @Test + void establishmentClosesUnavailableTransportAndCleansMdcBeforeLaterHealthyConnection() + throws Exception { + when(runtimeIdentity.service()).thenReturn("game-session-service"); + when(runtimeIdentity.serviceInstanceId()).thenReturn("instance-1"); + Map originalMdc = org.slf4j.MDC.getCopyOfContextMap(); + org.slf4j.MDC.put("requestMarker", "prior-value"); + Map priorMdc = org.slf4j.MDC.getCopyOfContextMap(); + when(session.getAttributes()) + .thenReturn(Map.of(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41")); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenThrow(new SessionContextUnavailableException("retained context unreadable", null)) + .thenReturn(Optional.empty()); + + try { + handler.afterConnectionEstablished(session); + + verify(session) + .close( + argThat( + status -> + status.getCode() == 1013 + && "backend_unavailable".equals(status.getReason()))); + verify(activeTransportSessionRegistry, never()).register(41L, session); + verify(activeTransportSessionRegistry, never()).unregister(Mockito.anyLong(), Mockito.any()); + verify(sessionContextService, never()).save(Mockito.any()); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("service")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("serviceInstanceId")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("correlationId")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.getCopyOfContextMap()) + .isEqualTo(priorMdc); + + WebSocketSession healthySession = Mockito.mock(WebSocketSession.class); + when(healthySession.getAttributes()) + .thenReturn(Map.of(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "42")); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("42")) + .thenReturn(Optional.empty()); + handler.afterConnectionEstablished(healthySession); + + verify(activeTransportSessionRegistry).register(42L, healthySession); + verify(healthySession, never()).close(Mockito.any(CloseStatus.class)); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.getCopyOfContextMap()) + .isEqualTo(priorMdc); + } finally { + restoreMdc(originalMdc); + } + } + + @Test + void messageClosesTransportWhenRetainedContextCannotBeRead() throws Exception { + when(runtimeIdentity.service()).thenReturn("game-session-service"); + when(runtimeIdentity.serviceInstanceId()).thenReturn("instance-1"); + Map originalMdc = org.slf4j.MDC.getCopyOfContextMap(); + org.slf4j.MDC.put("requestMarker", "prior-value"); + Map priorMdc = org.slf4j.MDC.getCopyOfContextMap(); + when(session.getAttributes()) + .thenReturn(Map.of(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41")); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenThrow(new SessionContextUnavailableException("retained context unreadable", null)); + + try { + handler.handleMessage(session, new TextMessage("LOOK")); + + verify(session) + .close( + argThat( + status -> + status.getCode() == 1013 + && "backend_unavailable".equals(status.getReason()))); + verify(parser, never()).parse(Mockito.anyString()); + verify(interpreter, never()) + .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); + verify(sessionContextService, never()).save(Mockito.any()); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), Mockito.any()); + verify(activeTransportSessionRegistry, never()).unregister(Mockito.anyLong(), Mockito.any()); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("service")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("serviceInstanceId")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.get("correlationId")).isNull(); + org.assertj.core.api.Assertions.assertThat(org.slf4j.MDC.getCopyOfContextMap()) + .isEqualTo(priorMdc); + } finally { + restoreMdc(originalMdc); + } + } + + private static void restoreMdc(Map contextMap) { + if (contextMap == null) { + org.slf4j.MDC.clear(); + } else { + org.slf4j.MDC.setContextMap(contextMap); + } } @Test @@ -1450,4 +1515,304 @@ private static GameplayAdmissionPointerSnapshot pointer( private static UUID stableUuid(String value) { return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } + + @Test + void firstPartyBootstrapRetainsFullSignedContextAndOnlyCanonicalOwnerHandles() throws Exception { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + var context = fixture.context(); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, context.compactJws(), + GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, "999", + GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR, "888")); + when(firstPartyConnectContextService.parse(context.compactJws())) + .thenAnswer(invocation -> fixture.service.parse(invocation.getArgument(0))); + when(firstPartyConnectContextService.requireRetained(any())) + .thenAnswer(invocation -> fixture.service.requireRetained(invocation.getArgument(0))); + handler.afterConnectionEstablished(session); + var captor = org.mockito.ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + org.assertj.core.api.Assertions.assertThat(captor.getValue().tenantId()).isEqualTo(22L); + org.assertj.core.api.Assertions.assertThat(captor.getValue().bootstrapGameInstanceId()) + .isEqualTo(41L); + org.assertj.core.api.Assertions.assertThat(captor.getValue().firstPartyConnectContext()) + .isEqualTo(context); + org.assertj.core.api.Assertions.assertThat(captor.getValue().hasAccountIdentity()).isFalse(); + verify(gameplayAdmissionPointerAuthorityService, never()) + .listByRuntimeTarget(Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void failedFirstPartyBootstrapSaveUnregistersContextBeforeClosingUnavailableTransport() + throws Exception { + configureFirstPartyBootstrap(); + var saveFailure = + new SessionContextUnavailableException( + "session save unavailable", new IllegalStateException()); + Mockito.doThrow(saveFailure).when(sessionContextService).save(any(SessionContext.class)); + + handler.afterConnectionEstablished(session); + + InOrder order = Mockito.inOrder(firstPartyConnectContextRegistry, session); + order.verify(firstPartyConnectContextRegistry).register(Mockito.eq(41L), any()); + order.verify(firstPartyConnectContextRegistry).unregister(41L); + order + .verify(session) + .close( + Mockito.argThat( + (CloseStatus status) -> + status.getCode() == 1013 && "backend_unavailable".equals(status.getReason()))); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); + assertThat(saveFailure.getSuppressed()).isEmpty(); + } + + @Test + void failedFirstPartyBootstrapSaveUnregistersContextBeforeClosingInvalidTransport() + throws Exception { + configureFirstPartyBootstrap(); + var saveFailure = new IllegalStateException("session save rejected"); + Mockito.doThrow(saveFailure).when(sessionContextService).save(any(SessionContext.class)); + + handler.afterConnectionEstablished(session); + + InOrder order = Mockito.inOrder(firstPartyConnectContextRegistry, session); + order.verify(firstPartyConnectContextRegistry).register(Mockito.eq(41L), any()); + order.verify(firstPartyConnectContextRegistry).unregister(41L); + order + .verify(session) + .close( + Mockito.argThat( + (CloseStatus status) -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); + assertThat(saveFailure.getSuppressed()).isEmpty(); + } + + @Test + void failedFirstPartyBootstrapSavePreservesPrimaryFailureWhenUnregisterAlsoFails() + throws Exception { + configureFirstPartyBootstrap(); + var saveFailure = + new SessionContextUnavailableException( + "session save unavailable", new IllegalStateException()); + var cleanupFailure = new IllegalStateException("context unregister unavailable"); + Mockito.doThrow(saveFailure).when(sessionContextService).save(any(SessionContext.class)); + Mockito.doThrow(cleanupFailure).when(firstPartyConnectContextRegistry).unregister(41L); + + handler.afterConnectionEstablished(session); + + assertThat(saveFailure.getSuppressed()).containsExactly(cleanupFailure); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); + verify(session).close(Mockito.argThat(status -> status.getCode() == 1013)); + } + + @Test + void failedFirstPartyBootstrapSaveDoesNotSelfSuppressWhenUnregisterThrowsSameFailure() + throws Exception { + configureFirstPartyBootstrap(); + var saveFailure = + new SessionContextUnavailableException( + "session save unavailable", new IllegalStateException()); + Mockito.doThrow(saveFailure).when(sessionContextService).save(any(SessionContext.class)); + Mockito.doThrow(saveFailure).when(firstPartyConnectContextRegistry).unregister(41L); + + handler.afterConnectionEstablished(session); + + assertThat(saveFailure.getSuppressed()).isEmpty(); + verify(firstPartyConnectContextRegistry).unregister(41L); + verify(session).close(Mockito.argThat(status -> status.getCode() == 1013)); + } + + @Test + void failedFirstPartyContextRegistrationDoesNotAttemptUnregisterOrSave() throws Exception { + configureFirstPartyBootstrap(); + Mockito.doThrow(new IllegalStateException("context registration rejected")) + .when(firstPartyConnectContextRegistry) + .register(Mockito.eq(41L), any()); + + handler.afterConnectionEstablished(session); + + verify(firstPartyConnectContextRegistry, never()).unregister(Mockito.anyLong()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); + verify(session) + .close( + Mockito.argThat(status -> status.getCode() == CloseStatus.POLICY_VIOLATION.getCode())); + } + + private void configureFirstPartyBootstrap() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + var context = fixture.context(); + String token = context.compactJws(); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, token)); + when(firstPartyConnectContextService.parse(token)) + .thenAnswer(invocation -> fixture.service.parse(invocation.getArgument(0))); + } + + @Test + void missingCanonicalTargetRejectsBeforeRegistryBootstrapAndTransportWrites() throws Exception { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + String token = fixture.token(); + when(fixture.routes.readCurrentTarget( + net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture.TENANT)) + .thenReturn(null); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, token)); + when(firstPartyConnectContextService.parse(token)) + .thenAnswer(invocation -> fixture.service.parse(invocation.getArgument(0))); + handler.afterConnectionEstablished(session); + verify(sessionContextService, never()).save(any()); + verify(firstPartyConnectContextRegistry, never()).register(Mockito.anyLong(), any()); + verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); + verify(session).close(any(CloseStatus.class)); + } + + @Test + void ownedRegisteredClosePerformsContextPromptAndPresenceCleanup() { + when(activeTransportSessionRegistry.unregister(41L, session)).thenReturn(true); + handler.afterConnectionClosed(session, CloseStatus.NORMAL); + verify(firstPartyConnectContextRegistry).unregister(41L); + verify(promptBurstCoordinator).evict("41"); + verify(gameplayPresenceLifecycleService) + .recordDisconnected( + 41L, + net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition + .TRANSPORT_LOSS); + } + + @Test + void rejectedOrReplacedCloseDoesNotCleanUpIncumbentState() { + when(activeTransportSessionRegistry.unregister(41L, session)).thenReturn(false); + handler.afterConnectionClosed(session, CloseStatus.POLICY_VIOLATION); + verify(firstPartyConnectContextRegistry, never()).unregister(Mockito.anyLong()); + verify(promptBurstCoordinator, never()).evict(any()); + verify(gameplayPresenceLifecycleService, never()).recordDisconnected(Mockito.anyLong(), any()); + } + + @Test + void queuedFirstPartyFrameFromRejectedBootstrapCannotUseIncumbentOrdinarySession() + throws Exception { + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + WebSocketSession incumbent = Mockito.mock(WebSocketSession.class); + when(activeTransportSessionRegistry.find(41L)) + .thenReturn( + Optional.of( + new org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator( + incumbent, 10_000, 64 * 1024))); + handler.handleMessage(session, new TextMessage("LOGIN demo@example.com swordfish")); + handler.afterConnectionClosed(session, CloseStatus.POLICY_VIOLATION); + verify(session).close(any(CloseStatus.class)); + Mockito.verifyNoInteractions( + parser, + interpreter, + sessionAuthenticationService, + sessionContextService, + gameplayPresenceLifecycleService, + screenBufferService, + promptBurstCoordinator, + firstPartyConnectContextRegistry); + } + + @Test + void queuedFirstPartyFrameWithoutRegistrationCannotBootstrapOrInterpret() throws Exception { + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.empty()); + handler.handleMessage(session, new TextMessage("PLAY demo hero")); + verify(session).close(any(CloseStatus.class)); + Mockito.verifyNoInteractions( + parser, + interpreter, + sessionAuthenticationService, + sessionContextService, + gameplayPresenceLifecycleService, + screenBufferService, + promptBurstCoordinator, + firstPartyConnectContextRegistry); + } + + @Test + void sendFailureCloseCallbackOwnsCleanup() throws Exception { + SessionContext context = new SessionContext(41L, 22L, "123", 123L, 1L, "R-1", "jwt"); + PlayerOutput output = PlayerOutput.notice("hello"); + PresentationProperties presentation = new PresentationProperties(); + when(settingsResolver.presentation(context)).thenReturn(presentation); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(session)); + when(activeTransportSessionRegistry.unregister(41L, session)).thenReturn(true); + when(session.isOpen()).thenReturn(true); + when(promptBurstCoordinator.applyPromptWindow(any(), any(), any(), Mockito.eq(false))) + .thenAnswer(invocation -> invocation.getArgument(2)); + when(outputProjector.projectPlayerOutput(session, output, null, presentation)) + .thenReturn("hello"); + Mockito.doThrow(new java.io.IOException("send failed")).when(session).sendMessage(any()); + Mockito.doAnswer( + invocation -> { + handler.afterConnectionClosed(session, invocation.getArgument(0)); + return null; + }) + .when(session) + .close(any(CloseStatus.class)); + var metrics = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); + try { + var delivery = + new net.firedevops.firemud.gamesession.service.PlayerOutputDeliveryService( + activeTransportSessionRegistry, + screenBufferService, + settingsResolver, + outputProjector, + promptComposer, + promptBurstCoordinator, + metrics); + delivery.deliver(context, List.of(output), false); + } finally { + metrics.close(); + } + verify(activeTransportSessionRegistry).unregister(41L, session); + verify(firstPartyConnectContextRegistry).unregister(41L); + verify(promptBurstCoordinator).evict("41"); + verify(gameplayPresenceLifecycleService) + .recordDisconnected( + 41L, + net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition + .TRANSPORT_LOSS); + } + + @Test + void exactRegisteredDecoratorDelegateAllowsFirstPartyFrameParsing() throws Exception { + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + when(activeTransportSessionRegistry.find(41L)) + .thenReturn( + Optional.of( + new org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator( + session, 10_000, 64 * 1024))); + when(parser.parse(" ")).thenReturn(new TextCommand(TextCommandType.NOOP, List.of(), " ")); + handler.handleMessage(session, new TextMessage(" ")); + verify(parser).parse(" "); + verify(session, never()).close(any(CloseStatus.class)); + Mockito.verifyNoInteractions(interpreter); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java index e0f723ec0f..b321bf58ef 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java @@ -49,4 +49,33 @@ private Map handshakeAttributes(String transportSessionId) { interceptor.beforeHandshake(request, response, null, attributes); return attributes; } + + @Test + void firstPartyHandoffDoesNotTreatRawRoutingHeadersAsLogicalAuthority() { + MockHttpServletRequest servlet = new MockHttpServletRequest("GET", "/ws/game"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, "12345"); + servlet.addHeader( + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_HEADER, "signed-context"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.TENANT_HEADER, "999"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.GAME_INSTANCE_HEADER, "888"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.WORLD_SLUG_HEADER, "untrusted"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.REALM_SLUG_HEADER, "untrusted"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.POINTER_VERSION_HEADER, "777"); + Map attributes = new HashMap<>(); + interceptor.beforeHandshake( + new ServletServerHttpRequest(servlet), + new ServletServerHttpResponse(new MockHttpServletResponse()), + null, + attributes); + assertThat(attributes) + .containsEntry( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web"); + assertThat(attributes) + .doesNotContainKeys( + GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, + GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR, + GameSessionWebSocketHandshakeInterceptor.WORLD_SLUG_ATTR, + GameSessionWebSocketHandshakeInterceptor.REALM_SLUG_ATTR, + GameSessionWebSocketHandshakeInterceptor.POINTER_VERSION_ATTR); + } } diff --git a/services/spring-cloud-gateway/README.md b/services/spring-cloud-gateway/README.md index 749be634e8..4e1e0a827b 100644 --- a/services/spring-cloud-gateway/README.md +++ b/services/spring-cloud-gateway/README.md @@ -3,4 +3,8 @@ The gateway's design documentation lives at: [📄 Spring Cloud Gateway Design](../../design/architecture/microservices/spring-cloud-gateway/README.md) -This README is a stub. **Do not add design details here.** +This README links to the Gateway's canonical design. **Do not duplicate design details here.** + +## Current first-party gameplay availability + +Public first-party `/ws/game/**` cookie admission and gameplay-route readiness remain unavailable. The filter returns `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` for a presented first-party cookie and does not mint or replay the legacy HMAC context. The canonical Account producer, shared replay readiness, and dedicated Gateway signing-key qualification remain open. The trusted TCP Proxy certificate/listener boundary remains separate. See [Gateway Architecture](../../design/architecture/system-architecture-gateway.md#implementation-status), [Authentication and authorization](../../design/architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative), and the [Player Access and Session tracker](../../design/project-management/implementation-tracking/player-access-and-session.md#canonical-first-party-receiving-preparation). diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java index 3a5946fdf7..dde6ae9af8 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java @@ -1,32 +1,15 @@ package net.firedevops.firemud.springcloudgateway.filter; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.ExpiredJwtException; -import io.jsonwebtoken.Jws; -import io.jsonwebtoken.JwtException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; import java.util.List; -import java.util.Map; import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.runtime.RuntimeLoggingContext; import net.firedevops.firemud.common.security.JwtClaims; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; -import org.springframework.core.env.Environment; -import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -39,7 +22,10 @@ import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; -/** Enforces gameplay handshakes for /ws/game/** and classifies first-party gateway admissions. */ +/** + * Preserves trusted TCP Proxy handshakes and denies first-party admission until canonical authority + * is ready. + */ @Component public final class GameplayHandshakeFilter implements WebFilter, Ordered { private static final Logger logger = LoggerFactory.getLogger(GameplayHandshakeFilter.class); @@ -55,65 +41,28 @@ public final class GameplayHandshakeFilter implements WebFilter, Ordered { static final String POINTER_VERSION_HEADER = "X-Pointer-Version"; static final String GAME_INSTANCE_ID_HEADER = "X-Game-Instance-Id"; static final String TENANT_ID_HEADER = "X-Tenant-Id"; - static final String PROXY_GAME_INSTANCE_ID_HEADER = "X-Proxy-Game-Instance-Id"; - static final String PROXY_TENANT_ID_HEADER = "X-Proxy-Tenant-Id"; static final String PROXY_CONNECTION_ID_HEADER = "X-Proxy-Connection-Id"; - static final String CONNECTION_MODE_FIRST_PARTY_WEB = "first_party_web"; static final String CONNECTION_MODE_TRUSTED_TCP_PROXY = "trusted_tcp_proxy"; static final String CONNECT_TOKEN_REJECTED = "CONNECT_TOKEN_REJECTED"; static final String HANDSHAKE_ERROR_REASON_HEADER = "X-Firemud-Handshake-Error-Reason"; static final String CONNECT_TOKEN_UNSUPPORTED_CARRIER_OR_ROUTE = "unsupported_carrier_or_route"; - static final String CONNECT_TOKEN_INVALID_CONTENT = "invalid_token_content"; static final String CONNECT_TOKEN_MISSING = "CONNECT_TOKEN_MISSING"; - static final String CONNECT_TOKEN_EXPIRED = "CONNECT_TOKEN_EXPIRED"; - static final String CONNECT_TOKEN_REPLAYED = "CONNECT_TOKEN_REPLAYED"; static final String CONNECT_SCOPE_MISMATCH = "CONNECT_SCOPE_MISMATCH"; static final String CONNECT_REPLAY_PROTECTION_UNAVAILABLE = "CONNECT_REPLAY_PROTECTION_UNAVAILABLE"; - private static final String REPLAY_CACHE_KEY_PREFIX = "gateway:connect-token:jti:"; - private static final Duration REPLAY_SKEW = Duration.ofSeconds(5); - private final JwtUtil jwtUtil; private final RuntimeIdentity runtimeIdentity; - @Nullable private final ReactiveStringRedisTemplate replayRedisTemplate; private final GameplayWebSocketObservability gameplayWebSocketObservability; - private final boolean allowLocalReplayFallback; - private final ConcurrentHashMap replayCache = new ConcurrentHashMap<>(); - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators remain internal filter dependencies.") @Autowired public GameplayHandshakeFilter( - JwtUtil jwtUtil, RuntimeIdentity runtimeIdentity, - @Nullable ReactiveStringRedisTemplate replayRedisTemplate, - Environment environment, GameplayWebSocketObservability gameplayWebSocketObservability) { - this.jwtUtil = Objects.requireNonNull(jwtUtil, "jwtUtil must not be null"); this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity must not be null"); - this.replayRedisTemplate = replayRedisTemplate; this.gameplayWebSocketObservability = Objects.requireNonNull( gameplayWebSocketObservability, "gameplayWebSocketObservability must not be null"); - this.allowLocalReplayFallback = - Arrays.stream(environment.getActiveProfiles()) - .map(String::toLowerCase) - .anyMatch(profile -> profile.equals("test")); - } - - GameplayHandshakeFilter( - JwtUtil jwtUtil, - RuntimeIdentity runtimeIdentity, - @Nullable ReactiveStringRedisTemplate replayRedisTemplate, - Environment environment) { - this( - jwtUtil, - runtimeIdentity, - replayRedisTemplate, - environment, - GameplayWebSocketObservability.disabled()); } @Override @@ -165,113 +114,8 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { return reject(exchange, CONNECT_TOKEN_MISSING, "connect token required"); } - try { - Jws claims = jwtUtil.parseToken(connectToken); - Claims payload = claims.getPayload(); - String audience = - payload.getAudience().stream() - .findFirst() - .filter(StringUtils::hasText) - .orElseGet(() -> requiredClaim(payload, "aud")); - if (!"gameplay-connect".equals(audience)) { - throw new IllegalArgumentException("Invalid audience"); - } - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - payload, "Connect token account subject mismatch"); - String accountId = Long.toString(routingClaims.accountId()); - RoutingBundle routingBundle = parseRuntimeRoutingBundleFromClaims(routingClaims); - String tenantId = Long.toString(routingClaims.tenantId()); - String gameInstanceId = Long.toString(routingClaims.gameInstanceId()); - String connectScopeId = requiredClaim(payload, "connectScopeId"); - String requestId = requiredClaim(payload, "requestId"); - String jti = requiredClaim(payload, "jti"); - return recordReplayOrReject(jti, payload.getExpiration().getTime()) - .then( - Mono.defer( - () -> { - if (mismatched(exchange, "X-Tenant-Id", tenantId) - || mismatched(exchange, "X-Game-Instance-Id", gameInstanceId) - || mismatchedRoutingBundle(exchange, routingBundle)) { - return reject(exchange, CONNECT_SCOPE_MISMATCH, "connect scope mismatch"); - } - - Instant verifiedAt = Instant.now(); - String connectContext = - jwtUtil.generateToken( - accountId, - Map.ofEntries( - Map.entry("accountId", accountId), - Map.entry("tenantId", tenantId), - Map.entry("worldSlug", routingBundle.worldSlug()), - Map.entry("realmSlug", routingBundle.realmSlug()), - Map.entry("gameInstanceId", gameInstanceId), - Map.entry("pointerVersion", routingBundle.pointerVersion()), - Map.entry("connectScopeId", connectScopeId), - Map.entry("connectTokenJti", jti), - Map.entry("connectRequestId", requestId), - Map.entry("verifiedAt", verifiedAt.toEpochMilli()), - Map.entry("expiresAt", payload.getExpiration().getTime()), - Map.entry("gatewayRequestId", exchange.getRequest().getId()))); - - return chain.filter( - mutate( - exchange, - headers -> { - headers.remove(CONNECT_TOKEN_HEADER); - removeConnectTokenCookie(headers); - headers.remove(HANDSHAKE_ERROR_CLASS_HEADER); - headers.remove(HANDSHAKE_ERROR_REASON_HEADER); - headers.set(CONNECT_CONTEXT_HEADER, connectContext); - headers.set(CONNECTION_MODE_HEADER, CONNECTION_MODE_FIRST_PARTY_WEB); - headers.set( - TRANSPORT_SESSION_HEADER, - Long.toUnsignedString( - stablePositiveLong(exchange.getRequest().getId()))); - headers.set("X-Tenant-Id", tenantId); - headers.set("X-Game-Instance-Id", gameInstanceId); - headers.set(WORLD_SLUG_HEADER, routingBundle.worldSlug()); - headers.set(REALM_SLUG_HEADER, routingBundle.realmSlug()); - headers.set(POINTER_VERSION_HEADER, routingBundle.pointerVersion()); - })); - })) - .onErrorResume( - ReplayRejectedException.class, - ex -> { - return reject(exchange, CONNECT_TOKEN_REPLAYED, "connect token replayed"); - }) - .onErrorResume( - ReplayProtectionUnavailableException.class, - ex -> { - return reject( - exchange, - CONNECT_REPLAY_PROTECTION_UNAVAILABLE, - "connect replay protection unavailable"); - }) - .onErrorResume( - IllegalArgumentException.class, - ex -> { - return reject( - exchange, - CONNECT_TOKEN_REJECTED, - CONNECT_TOKEN_INVALID_CONTENT, - "connect token rejected"); - }); - } catch (ExpiredJwtException ex) { - return reject(exchange, CONNECT_TOKEN_EXPIRED, "connect token expired"); - } catch (JwtException ex) { - return reject( - exchange, - CONNECT_TOKEN_REJECTED, - CONNECT_TOKEN_INVALID_CONTENT, - "connect token rejected"); - } catch (IllegalArgumentException ex) { - return reject( - exchange, - CONNECT_TOKEN_REJECTED, - CONNECT_TOKEN_INVALID_CONTENT, - "connect token rejected"); - } + return reject( + exchange, CONNECT_REPLAY_PROTECTION_UNAVAILABLE, "connect replay protection unavailable"); } private boolean isTrustedTcpProxy(ServerWebExchange exchange) { @@ -279,22 +123,9 @@ private boolean isTrustedTcpProxy(ServerWebExchange exchange) { exchange.getRequest().getHeaders().getFirst(PROXY_CONNECTION_ID_HEADER)); } - private static boolean mismatched( - ServerWebExchange exchange, String headerName, String expected) { - String actual = exchange.getRequest().getHeaders().getFirst(headerName); - return StringUtils.hasText(actual) && !Objects.equals(actual, expected); - } - - private static boolean mismatchedRoutingBundle( - ServerWebExchange exchange, RoutingBundle routingBundle) { - return mismatched(exchange, WORLD_SLUG_HEADER, routingBundle.worldSlug()) - || mismatched(exchange, REALM_SLUG_HEADER, routingBundle.realmSlug()) - || mismatched(exchange, POINTER_VERSION_HEADER, routingBundle.pointerVersion()); - } - private boolean trustedProxyRoutingBundleIsCoherent(ServerWebExchange exchange) { try { - parseRuntimeRoutingBundleFromHeaders(exchange); + validateRuntimeRoutingBundleFromHeaders(exchange); parseTrustedTcpProxyIdentityFromHeaders(exchange); return true; } catch (RuntimeException ex) { @@ -302,16 +133,8 @@ private boolean trustedProxyRoutingBundleIsCoherent(ServerWebExchange exchange) } } - private static RoutingBundle parseRuntimeRoutingBundleFromClaims( - JwtClaims.SignedGameplayRoutingClaims routingClaims) { - return new RoutingBundle( - routingClaims.worldSlug(), - routingClaims.realmSlug(), - Long.toString(routingClaims.pointerVersion())); - } - - private static RoutingBundle parseRuntimeRoutingBundleFromHeaders(ServerWebExchange exchange) { - return parseRuntimeRoutingBundle( + private static void validateRuntimeRoutingBundleFromHeaders(ServerWebExchange exchange) { + validateRuntimeRoutingBundle( exchange.getRequest().getHeaders().getFirst(WORLD_SLUG_HEADER), exchange.getRequest().getHeaders().getFirst(REALM_SLUG_HEADER), exchange.getRequest().getHeaders().getFirst(POINTER_VERSION_HEADER), @@ -324,7 +147,7 @@ private static void parseTrustedTcpProxyIdentityFromHeaders(ServerWebExchange ex exchange.getRequest().getHeaders().getFirst(GAME_INSTANCE_ID_HEADER)); } - private static RoutingBundle parseRuntimeRoutingBundle( + private static void validateRuntimeRoutingBundle( String worldSlug, String realmSlug, String pointerVersion, boolean allowMissing) { boolean hasWorld = StringUtils.hasText(worldSlug); boolean hasRealm = StringUtils.hasText(realmSlug); @@ -332,37 +155,11 @@ private static RoutingBundle parseRuntimeRoutingBundle( boolean hasFullBundle = hasWorld && hasRealm && hasPointer; if (!hasFullBundle) { if (allowMissing && !hasWorld && !hasRealm && !hasPointer) { - return null; + return; } throw new IllegalArgumentException("Malformed gameplay routing bundle"); } - long normalizedPointerVersion = - JwtClaims.requireLong(pointerVersion, POINTER_VERSION_HEADER, false); - return new RoutingBundle(worldSlug, realmSlug, Long.toString(normalizedPointerVersion)); - } - - private static final class RoutingBundle { - private final String worldSlug; - private final String realmSlug; - private final String pointerVersion; - - private RoutingBundle(String worldSlug, String realmSlug, String pointerVersion) { - this.worldSlug = worldSlug; - this.realmSlug = realmSlug; - this.pointerVersion = pointerVersion; - } - - private String worldSlug() { - return worldSlug; - } - - private String realmSlug() { - return realmSlug; - } - - private String pointerVersion() { - return pointerVersion; - } + JwtClaims.requireLong(pointerVersion, POINTER_VERSION_HEADER, false); } private ServerWebExchange mutate( @@ -458,55 +255,6 @@ private Mono reject( return exchange.getResponse().setComplete(); } - private String requiredClaim(Claims claims, String name) { - return JwtClaims.requireClaim(claims, name); - } - - private Mono recordReplayOrReject(String jti, long expiryMillis) { - if (replayRedisTemplate != null) { - long now = System.currentTimeMillis(); - long replayExpiry = expiryMillis + REPLAY_SKEW.toMillis(); - Duration ttl = Duration.ofMillis(Math.max(1L, replayExpiry - now)); - return replayRedisTemplate - .opsForValue() - .setIfAbsent(replayKey(jti), "1", ttl) - .flatMap( - accepted -> { - if (Boolean.TRUE.equals(accepted)) { - return Mono.empty(); - } - return Mono.error(new ReplayRejectedException("connect token replayed")); - }); - } - if (!allowLocalReplayFallback) { - return Mono.error( - new ReplayProtectionUnavailableException( - "cluster replay protection requires redis-backed storage")); - } - return Mono.fromRunnable(() -> recordReplayLocally(jti, expiryMillis)); - } - - private void recordReplayLocally(String jti, long expiryMillis) { - long now = System.currentTimeMillis(); - replayCache.entrySet().removeIf(entry -> entry.getValue() <= now); - long replayExpiry = expiryMillis + REPLAY_SKEW.toMillis(); - Long existing = replayCache.putIfAbsent(jti, replayExpiry); - if (existing != null && existing > now) { - throw new ReplayRejectedException("connect token replayed"); - } - } - - private long stablePositiveLong(String value) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); - long candidate = ByteBuffer.wrap(digest, 0, Long.BYTES).getLong(); - return candidate == Long.MIN_VALUE ? 0L : Math.abs(candidate); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 unavailable", ex); - } - } - @Override public int getOrder() { return -3; @@ -515,20 +263,4 @@ public int getOrder() { private static String firstNonBlank(String primary, String fallback) { return StringUtils.hasText(primary) ? primary : fallback; } - - private String replayKey(String jti) { - return REPLAY_CACHE_KEY_PREFIX + jti; - } - - private static final class ReplayRejectedException extends RuntimeException { - private ReplayRejectedException(String message) { - super(message); - } - } - - private static final class ReplayProtectionUnavailableException extends RuntimeException { - private ReplayProtectionUnavailableException(String message) { - super(message); - } - } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java index 4fbce0db0d..8719ba15f2 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java @@ -1,137 +1,37 @@ package net.firedevops.firemud.springcloudgateway.health; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.WebSocket; -import java.time.Duration; import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.health.DependencyReadinessSupport; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; -import net.firedevops.firemud.common.security.JwtUtil; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.health.contributor.HealthIndicator; import org.springframework.stereotype.Component; -/** Readiness indicator that verifies the gameplay WebSocket route can be upgraded locally. */ +/** Readiness contribution for first-party gameplay admission through the Gateway. */ @Component("gameplayRouteReadiness") public class GameplayRouteReadinessHealthIndicator implements HealthIndicator { private static final String COMPONENT = "spring-cloud-gateway"; - private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(1); private static final String CONTRACT = "Gateway /ws/game upgrade"; - private static final String COOKIE_HEADER = "Cookie"; - private static final String CONNECT_TOKEN_COOKIE = "Firemud-Connect-Token"; - private static final String PROXY_CONNECTION_ID_HEADER = "X-Proxy-Connection-Id"; - private static final String GAME_INSTANCE_ID_HEADER = "X-Game-Instance-Id"; - private static final String TENANT_ID_HEADER = "X-Tenant-Id"; - private static final String SYNTHETIC_PROXY_CONNECTION_ID = "gateway-readiness-probe"; - // Probe identifiers intentionally use non-zero ids to satisfy strict identity claims. - private static final String PROBE_ACCOUNT_ID = "1"; - private static final String PROBE_TENANT_ID = "1"; - private static final String PROBE_GAME_INSTANCE_ID = "1"; + private static final String UNAVAILABLE_REASON = + "Canonical Account connect-context production, shared replay fencing, and dedicated Gateway " + + "signing keys are not qualified"; - private final int serverPort; private final ReadinessTransitionTracker readinessTransitionTracker; - private final JwtUtil jwtUtil; - private final HttpClient client; - @SuppressFBWarnings( - value = "CT_CONSTRUCTOR_THROW", - justification = - "Dependency lookup is framework-owned; construction failure should fail startup loudly.") - @Autowired public GameplayRouteReadinessHealthIndicator( - @Value("${local.server.port:${server.port:8080}}") int serverPort, - ReadinessTransitionTracker readinessTransitionTracker, - ObjectProvider jwtUtilProvider) { - this( - serverPort, - readinessTransitionTracker, - jwtUtilProvider, - HttpClient.newBuilder().connectTimeout(CONNECT_TIMEOUT).build()); - } - - @SuppressFBWarnings( - value = "CT_CONSTRUCTOR_THROW", - justification = - "Rejecting a null test client should fail construction before the indicator is used.") - GameplayRouteReadinessHealthIndicator( - int serverPort, - ReadinessTransitionTracker readinessTransitionTracker, - ObjectProvider jwtUtilProvider, - HttpClient client) { - this.serverPort = serverPort; + ReadinessTransitionTracker readinessTransitionTracker) { this.readinessTransitionTracker = readinessTransitionTracker; - this.jwtUtil = jwtUtilProvider.getIfAvailable(); - this.client = Objects.requireNonNull(client, "client must not be null"); } @Override public org.springframework.boot.health.contributor.Health health() { - URI uri = URI.create("ws://127.0.0.1:" + serverPort + "/ws/game"); - try { - WebSocket socket = buildClient().buildAsync(uri, new NoopListener()).get(2, TimeUnit.SECONDS); - socket.abort(); - return DependencyReadinessSupport.recordUp( - readinessTransitionTracker, - COMPONENT, - CONTRACT, - Map.of( - "gameplayRoute", - DependencyReadinessSupport.upDependency( - "websocketUpgrade", uri.toString(), "UPGRADED"))); - } catch (Exception ex) { - return DependencyReadinessSupport.recordOutOfService( - readinessTransitionTracker, - COMPONENT, - CONTRACT, - "gameplayRoute", - Map.of( - "gameplayRoute", - DependencyReadinessSupport.downDependency( - "websocketUpgrade", uri.toString(), DependencyReadinessSupport.message(ex)))); - } - } - - private WebSocket.Builder buildClient() { - WebSocket.Builder builder = client.newWebSocketBuilder(); - if (jwtUtil != null) { - String connectToken = - jwtUtil.generateToken( - PROBE_ACCOUNT_ID, - Map.of( - "aud", - "gameplay-connect", - "accountId", - PROBE_ACCOUNT_ID, - "tenantId", - PROBE_TENANT_ID, - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - PROBE_GAME_INSTANCE_ID, - "pointerVersion", - "1", - "connectScopeId", - "readiness-scope", - "requestId", - "readiness-request", - "jti", - "gateway-readiness-" + UUID.randomUUID())); - return builder.header(COOKIE_HEADER, CONNECT_TOKEN_COOKIE + "=" + connectToken); - } - return builder - .header(GAME_INSTANCE_ID_HEADER, "1") - .header(TENANT_ID_HEADER, "1") - .header(PROXY_CONNECTION_ID_HEADER, SYNTHETIC_PROXY_CONNECTION_ID); + return DependencyReadinessSupport.recordOutOfService( + readinessTransitionTracker, + COMPONENT, + CONTRACT, + "gameplayRoute", + Map.of( + "gameplayRoute", + DependencyReadinessSupport.downDependency( + "websocketUpgrade", "first-party admission", UNAVAILABLE_REASON))); } - - private static final class NoopListener implements WebSocket.Listener {} } diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java index 011a847abd..fb499af3a2 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java @@ -21,7 +21,6 @@ import java.util.function.Function; import java.util.stream.Stream; import net.firedevops.firemud.common.runtime.RuntimeIdentity; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.springcloudgateway.SpringCloudGatewayApplication; import net.firedevops.firemud.springcloudgateway.config.GatewayHeaderTrustProperties; import net.firedevops.firemud.springcloudgateway.config.GatewayTcpProxyListenerProperties; @@ -40,7 +39,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.mock.env.MockEnvironment; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.DispatcherHandler; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; @@ -309,11 +307,7 @@ private static ListenerFixture listenerFixture( HeaderTrustFilter headerTrustFilter = new HeaderTrustFilter(headerProperties, trustPolicy); GameplayHandshakeFilter handshakeFilter = new GameplayHandshakeFilter( - mock(JwtUtil.class), - mock(RuntimeIdentity.class), - null, - new MockEnvironment().withProperty("spring.profiles.active", "test"), - GameplayWebSocketObservability.disabled()); + mock(RuntimeIdentity.class), GameplayWebSocketObservability.disabled()); WebSocketHandler gameplayHandler = responseBehavior::apply; GenericApplicationContext context = new GenericApplicationContext(); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterLoggingContextTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterLoggingContextTest.java index 737af093d1..954aee6cf8 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterLoggingContextTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterLoggingContextTest.java @@ -4,17 +4,14 @@ import java.time.Instant; import net.firedevops.firemud.common.runtime.RuntimeIdentity; -import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.slf4j.MDC; -import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; class GameplayHandshakeFilterLoggingContextTest { - private static final String SECRET = "testsecretkeytestsecretkeytest1234"; - @AfterEach void clearMdc() { MDC.clear(); @@ -24,11 +21,9 @@ void clearMdc() { void openLoggingContextUsesTransportSessionHeaderAsCorrelationId() { GameplayHandshakeFilter filter = new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), new RuntimeIdentity( "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), - null, - new MockEnvironment()); + GameplayWebSocketObservability.disabled()); MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("/ws/game/test") diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index 71abccd271..a6c8e6db94 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -1,67 +1,76 @@ package net.firedevops.firemud.springcloudgateway.filter; 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.when; -import io.jsonwebtoken.Claims; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.net.InetSocketAddress; import java.time.Instant; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.springcloudgateway.config.GatewayHeaderTrustProperties; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.junit.jupiter.api.Test; -import org.springframework.data.redis.core.ReactiveStringRedisTemplate; -import org.springframework.data.redis.core.ReactiveValueOperations; import org.springframework.http.HttpCookie; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; class GameplayHandshakeFilterTest { - private static final String SECRET = "testsecretkeytestsecretkeytest1234"; private static final RuntimeIdentity TEST_RUNTIME_IDENTITY = new RuntimeIdentity( "spring-cloud-gateway", "gateway-test", "localhost", Instant.EPOCH, null, null, null); - private static MockEnvironment environmentWithProfiles(String... profiles) { - MockEnvironment environment = new MockEnvironment(); - environment.setActiveProfiles(profiles); - return environment; + @Test + void nonGameplayRoutePassesWithoutHandshakeProcessing() { + GameplayHandshakeFilter filter = filter(); + AtomicBoolean delegated = new AtomicBoolean(); + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.get("/api/session/ping").build()); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); } @Test - void rejectsFirstPartyHandshakeWithoutConnectToken() { - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + void missingFirstPartyCookieIsRejectedAsMissing() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); GameplayHandshakeFilter filter = new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test"), - new GameplayWebSocketObservability(meterRegistry)); - + TEST_RUNTIME_IDENTITY, new GameplayWebSocketObservability(registry)); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/ws/game/test").build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_MISSING); assertThat( - meterRegistry + registry .get("gateway.websocket.handshake.rejected") .tags( "route", @@ -76,461 +85,97 @@ void rejectsFirstPartyHandshakeWithoutConnectToken() { } @Test - void rejectsMatrixParameterGameplayRoutesEvenWithCookieCarrier() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-matrix", - "requestId", "req-matrix", - "jti", "jti-matrix")); - - for (String path : new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { - AtomicBoolean delegated = new AtomicBoolean(); - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get(path) - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - - filter - .filter( - exchange, - e -> { - delegated.set(true); - return Mono.empty(); - }) - .block(); - - assertThat(delegated).as("path=%s", path).isFalse(); - assertThat(exchange.getResponse().getStatusCode()) - .as("path=%s", path) - .isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .as("path=%s", path) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .as("path=%s", path) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_UNSUPPORTED_CARRIER_OR_ROUTE); - } - } - - @Test - void rejectsMatrixParameterGameplayRoutesBeforeTrustedProxyBypass() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - for (String path : new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { - AtomicBoolean delegated = new AtomicBoolean(); - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get(path) - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-matrix") - .header(GameplayHandshakeFilter.GAME_INSTANCE_ID_HEADER, "42") - .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "1") - .build()); - - filter - .filter( - exchange, - e -> { - delegated.set(true); - return Mono.empty(); - }) - .block(); - - assertThat(delegated).as("path=%s", path).isFalse(); - assertThat(exchange.getResponse().getStatusCode()) - .as("path=%s", path) - .isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .as("path=%s", path) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .as("path=%s", path) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_UNSUPPORTED_CARRIER_OR_ROUTE); - } - } - - @Test - void rejectsFirstPartyHandshakeWithMalformedNumericClaim() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "not-a-number", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_INVALID_CONTENT); - } - - @Test - void rejectsFirstPartyHandshakeWithZeroAccountIdClaim() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "0", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - + void firstPartyCookieFailsClosedBeforeParsingMutationOrForwarding() { + GameplayHandshakeFilter filter = filter(); MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) + .cookie( + new HttpCookie( + GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, "legacy-hmac-token")) .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); + .isEqualTo(GameplayHandshakeFilter.CONNECT_REPLAY_PROTECTION_UNAVAILABLE); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_INVALID_CONTENT); + .isNull(); + assertThat( + exchange + .getRequest() + .getHeaders() + .getFirst(GameplayHandshakeFilter.CONNECT_CONTEXT_HEADER)) + .isNull(); + assertThat( + exchange + .getRequest() + .getHeaders() + .getFirst(GameplayHandshakeFilter.CONNECTION_MODE_HEADER)) + .isNull(); } @Test - void rejectsFirstPartyHandshakeWhenSubjectDoesNotMatchAccountIdClaim() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "8", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - + void publicHeaderCarrierRemainsUnsupportedEvenWhenCookieIsPresent() { + GameplayHandshakeFilter filter = filter(); MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) + .header(GameplayHandshakeFilter.CONNECT_TOKEN_HEADER, "header-token") + .cookie( + new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, "cookie-token")) .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_INVALID_CONTENT); - } - - @Test - void rejectsFirstPartyHandshakeWithZeroPointerVersion() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "0", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); + .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_UNSUPPORTED_CARRIER_OR_ROUTE); } @Test - void rejectsFirstPartyHandshakeWithMissingRequiredClaim() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - + void matrixParameterRouteIsRejectedBeforeTrustedProxyBypass() { + GameplayHandshakeFilter filter = filter(); MockServerWebExchange exchange = MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) + MockServerHttpRequest.get("/ws/game;probe") + .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-matrix") + .header(GameplayHandshakeFilter.GAME_INSTANCE_ID_HEADER, "42") + .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "1") .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - } - - @Test - void firstPartyHandshakeDoesNotMaskUnexpectedJwtParserRuntimeFailure() { - JwtUtil jwtUtil = mock(JwtUtil.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalStateException("boom")); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - jwtUtil, TEST_RUNTIME_IDENTITY, null, environmentWithProfiles("test")); - - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, "boom-token")) - .build()); - - IllegalStateException ex = - org.junit.jupiter.api.Assertions.assertThrows( - IllegalStateException.class, () -> filter.filter(exchange, e -> Mono.empty()).block()); - - assertThat(ex).hasMessage("boom"); - } - - @Test - void rejectsScopeMismatchWhenRequestHeadersDisagreeWithTokenClaims() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-1", - "requestId", "req-1", - "jti", "jti-1")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .header("X-Tenant-Id", "2") - .build(); - - MockServerWebExchange exchange = MockServerWebExchange.from(request); - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_SCOPE_MISMATCH); - } - - @Test - void promotesFirstPartyHandshakeWithCookieCarrier() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "18", - "connectScopeId", "scope-cookie", - "requestId", "req-cookie", - "jti", "jti-cookie")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .header("Cookie", "session=\"quoted%20value\"; duplicate=first") - .header("Cookie", "duplicate=second") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); - - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_FIRST_PARTY_WEB); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Tenant-Id")).isEqualTo("1"); - assertThat(mutatedExchange.getRequest().getHeaders().get("Cookie")) - .containsExactly("session=\"quoted%20value\"; duplicate=first", "duplicate=second"); - } - - @Test - void removesConnectTokenFromMalformedQuotedCookiePair() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "18", - "connectScopeId", "scope-malformed-cookie", - "requestId", "req-malformed-cookie", - "jti", "jti-malformed-cookie")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .header("Cookie", "unmatched=\"unterminated; Firemud-Connect-Token=shadow") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); - - assertThat(mutatedExchange.getRequest().getHeaders().get("Cookie")) - .containsExactly("unmatched=\"unterminated"); - } - - @Test - void rejectsPublicHeaderCarrierEvenWhenCookieCarrierIsAlsoPresent() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "18", - "connectScopeId", "scope-both", - "requestId", "req-both", - "jti", "jti-both")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .header(GameplayHandshakeFilter.CONNECT_TOKEN_HEADER, token) - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build(); - - MockServerWebExchange exchange = MockServerWebExchange.from(request); - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); @@ -539,296 +184,113 @@ void rejectsPublicHeaderCarrierEvenWhenCookieCarrierIsAlsoPresent() { } @Test - void rejectsPublicHeaderCarrierOnExactGameplayRouteAsUnsupported() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - + void trustedTcpProxyHandshakeRemainsForwardableAndRemovesConnectCookie() { + GatewayHeaderTrustProperties properties = new GatewayHeaderTrustProperties(); + properties.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); + properties.getTcpProxy().setInsecureTrustedCidrs(List.of("10.0.0.0/8")); + HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(properties); + GameplayHandshakeFilter filter = filter(); MockServerWebExchange exchange = MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game") - .header(GameplayHandshakeFilter.CONNECT_TOKEN_HEADER, "header-token") + MockServerHttpRequest.get("/ws/game/test") + .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) + .header("X-Proxy-Client-IP", "203.0.113.99") + .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Game-Instance-Id", "42") + .header("X-Proxy-Tenant-Id", "1") + .header(HttpHeaders.COOKIE, "Firemud-Connect-Token=legacy-token; session=abc") .build()); + AtomicReference forwarded = new AtomicReference<>(); + + headerTrustFilter + .filter( + exchange, + trustedExchange -> + filter.filter( + trustedExchange, + forwardedExchange -> { + forwarded.set(forwardedExchange); + return Mono.empty(); + })) + .block(); - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_UNSUPPORTED_CARRIER_OR_ROUTE); - } - - @Test - void promotesFirstPartyHandshakeWithValidToken() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "18", - "connectScopeId", "scope-2", - "requestId", "req-2", - "jti", "jti-2")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .header(GameplayHandshakeFilter.HANDSHAKE_ERROR_CLASS_HEADER, "POLICY_DENY") - .header(GameplayHandshakeFilter.HANDSHAKE_ERROR_REASON_HEADER, "stale-reason") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); - - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_FIRST_PARTY_WEB); + assertThat(forwarded.get()).isNotNull(); assertThat( - mutatedExchange + forwarded + .get() .getRequest() .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_CLASS_HEADER)) - .isNull(); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_REASON_HEADER)) - .isNull(); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Tenant-Id")).isEqualTo("1"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Game-Instance-Id")) - .isEqualTo("42"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.WORLD_SLUG_HEADER)) - .isEqualTo("demo"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.REALM_SLUG_HEADER)) - .isEqualTo("production"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.POINTER_VERSION_HEADER)) - .isEqualTo("18"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) - .isNotBlank(); - Claims connectContextClaims = - new JwtUtil(SECRET, 30_000L) - .parseToken( - mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) - .getPayload(); - assertThat(connectContextClaims.get("worldSlug")).isEqualTo("demo"); - assertThat(connectContextClaims.get("realmSlug")).isEqualTo("production"); - assertThat(connectContextClaims.get("pointerVersion")).isEqualTo("18"); - assertThat(connectContextClaims.get("connectScopeId")).isEqualTo("scope-2"); - assertThat(connectContextClaims.get("connectRequestId")).isEqualTo("req-2"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.TRANSPORT_SESSION_HEADER)) - .matches("\\d+"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("Cookie")).isNull(); - } - - @Test - void trustedTcpProxyHandshakeBypassesConnectTokenRequirement() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header("X-Firemud-Connection-Mode", "first_party_web") - .header("X-Firemud-Connect-Context", "spoofed-context") - .header("X-Firemud-Transport-Session-Id", "spoofed-session") - .header("X-Firemud-Handshake-Error-Class", "POLICY_DENY") - .header("X-Firemud-Handshake-Error-Reason", "stale-reason") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain( - filter, filterThroughChain(headerTrustFilter, MockServerWebExchange.from(request))); - - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) + .getFirst(GameplayHandshakeFilter.CONNECTION_MODE_HEADER)) .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_TRUSTED_TCP_PROXY); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) - .isNull(); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.TRANSPORT_SESSION_HEADER)) - .isNull(); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_CLASS_HEADER)) - .isNull(); + assertThat(forwarded.get().getRequest().getHeaders().get(HttpHeaders.COOKIE)) + .containsExactly("session=abc"); assertThat( - mutatedExchange + forwarded + .get() .getRequest() .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_REASON_HEADER)) + .getFirst(GameplayHandshakeFilter.CONNECT_CONTEXT_HEADER)) .isNull(); - assertThat(mutatedExchange.getResponse().getStatusCode()).isNull(); - } - - @Test - void trustedTcpProxyHandshakeRemovesConnectTokenCookieAndPreservesOtherCookies() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header("Cookie", "Firemud-Connect-Token=token; session=abc") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain( - filter, filterThroughChain(headerTrustFilter, MockServerWebExchange.from(request))); - - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_TRUSTED_TCP_PROXY); - assertThat(mutatedExchange.getRequest().getHeaders().get("Cookie")) - .containsExactly("session=abc"); - assertThat(mutatedExchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); } @Test void trustedTcpProxyHandshakePreservesCompleteRoutingBundle() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); - - ServerWebExchange mutatedExchange = - filterThroughChain( - filter, filterThroughChain(headerTrustFilter, MockServerWebExchange.from(request))); + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/ws/game/test") + .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) + .header("X-Proxy-Client-IP", "203.0.113.99") + .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Game-Instance-Id", "42") + .header("X-Proxy-Tenant-Id", "1") + .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") + .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") + .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") + .build()); + ServerWebExchange trusted = filterThroughChain(trustedHeaderFilter(), exchange); + ServerWebExchange forwarded = filterThroughChain(filter(), trusted); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_TRUSTED_TCP_PROXY); assertThat( - mutatedExchange + forwarded .getRequest() .getHeaders() - .getFirst(GameplayHandshakeFilter.WORLD_SLUG_HEADER)) + .getFirst(GameplayHandshakeFilter.CONNECTION_MODE_HEADER)) + .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_TRUSTED_TCP_PROXY); + assertThat( + forwarded.getRequest().getHeaders().getFirst(GameplayHandshakeFilter.WORLD_SLUG_HEADER)) .isEqualTo("demo"); assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.REALM_SLUG_HEADER)) + forwarded.getRequest().getHeaders().getFirst(GameplayHandshakeFilter.REALM_SLUG_HEADER)) .isEqualTo("production"); assertThat( - mutatedExchange + forwarded .getRequest() .getHeaders() .getFirst(GameplayHandshakeFilter.POINTER_VERSION_HEADER)) .isEqualTo("17"); - assertThat(mutatedExchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); } @Test - void trustedTcpProxyHandshakeRejectsPartialRoutingBundle() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); + void trustedTcpProxyRejectsPartialRoutingBundle() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/ws/game/test") + .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) + .header("X-Proxy-Client-IP", "203.0.113.99") + .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Game-Instance-Id", "42") + .header("X-Proxy-Tenant-Id", "1") + .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") + .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") + .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") + .build()); + ServerWebExchange trusted = filterThroughChain(trustedHeaderFilter(), exchange); + ServerWebExchange partial = + withRequestHeader(trusted, GameplayHandshakeFilter.POINTER_VERSION_HEADER, null); - MockServerWebExchange exchange = MockServerWebExchange.from(request); - AtomicBoolean headerTrustDelegated = new AtomicBoolean(); - ServerWebExchange trustedExchange = - filterThroughChain(headerTrustFilter, exchange, headerTrustDelegated); - assertThat(headerTrustDelegated) - .as("HeaderTrustFilter must delegate before GameplayHandshakeFilter rejects the bundle") - .isTrue(); - trustedExchange = - withRequestHeader(trustedExchange, GameplayHandshakeFilter.POINTER_VERSION_HEADER, null); - filter.filter(trustedExchange, e -> Mono.empty()).block(); + filter().filter(partial, ignored -> Mono.empty()).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) @@ -836,40 +298,10 @@ void trustedTcpProxyHandshakeRejectsPartialRoutingBundle() { } @Test - void trustedTcpProxyHandshakeRejectsMalformedPointerVersion() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); + void trustedTcpProxyRejectsMalformedPointerVersion() { + MockServerWebExchange exchange = trustedProxyExchange("demo", "production", "v17", "1", "42"); - MockServerWebExchange exchange = MockServerWebExchange.from(request); - AtomicBoolean headerTrustDelegated = new AtomicBoolean(); - ServerWebExchange trustedExchange = - filterThroughChain(headerTrustFilter, exchange, headerTrustDelegated); - assertThat(headerTrustDelegated) - .as("HeaderTrustFilter must delegate before GameplayHandshakeFilter rejects the bundle") - .isTrue(); - trustedExchange = - withRequestHeader(trustedExchange, GameplayHandshakeFilter.POINTER_VERSION_HEADER, "v17"); - filter.filter(trustedExchange, e -> Mono.empty()).block(); + filter().filter(exchange, ignored -> Mono.empty()).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) @@ -877,40 +309,10 @@ void trustedTcpProxyHandshakeRejectsMalformedPointerVersion() { } @Test - void trustedTcpProxyHandshakeRejectsBlankWorldSlugInRoutingBundle() { - GatewayHeaderTrustProperties props = new GatewayHeaderTrustProperties(); - props.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); - props.getTcpProxy().setInsecureTrustedCidrs(java.util.List.of("10.0.0.0/8")); - HeaderTrustFilter headerTrustFilter = HeaderTrustFilterTest.legacyFilter(props); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); + void trustedTcpProxyRejectsBlankWorldSlugInRoutingBundle() { + MockServerWebExchange exchange = trustedProxyExchange(" ", "production", "17", "1", "42"); - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") - .header("X-Proxy-Game-Instance-Id", "42") - .header("X-Proxy-Tenant-Id", "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); - - MockServerWebExchange exchange = MockServerWebExchange.from(request); - AtomicBoolean headerTrustDelegated = new AtomicBoolean(); - ServerWebExchange trustedExchange = - filterThroughChain(headerTrustFilter, exchange, headerTrustDelegated); - assertThat(headerTrustDelegated) - .as("HeaderTrustFilter must delegate before GameplayHandshakeFilter rejects the bundle") - .isTrue(); - trustedExchange = - withRequestHeader(trustedExchange, GameplayHandshakeFilter.WORLD_SLUG_HEADER, " "); - filter.filter(trustedExchange, e -> Mono.empty()).block(); + filter().filter(exchange, ignored -> Mono.empty()).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) @@ -918,27 +320,11 @@ void trustedTcpProxyHandshakeRejectsBlankWorldSlugInRoutingBundle() { } @Test - void trustedTcpProxyHandshakeRejectsMalformedTenantId() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-123") - .header(GameplayHandshakeFilter.GAME_INSTANCE_ID_HEADER, "42") - .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "bad-id") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); + void trustedTcpProxyRejectsMalformedTenantId() { + MockServerWebExchange exchange = + trustedProxyExchange("demo", "production", "17", "bad-id", "42"); - MockServerWebExchange exchange = MockServerWebExchange.from(request); - filter.filter(exchange, e -> Mono.empty()).block(); + filter().filter(exchange, ignored -> Mono.empty()).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) @@ -946,27 +332,10 @@ void trustedTcpProxyHandshakeRejectsMalformedTenantId() { } @Test - void trustedTcpProxyHandshakeRejectsNonPositiveGameInstanceId() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); + void trustedTcpProxyRejectsNonPositiveGameInstanceId() { + MockServerWebExchange exchange = trustedProxyExchange("demo", "production", "17", "1", "0"); - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-123") - .header(GameplayHandshakeFilter.GAME_INSTANCE_ID_HEADER, "0") - .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); - - MockServerWebExchange exchange = MockServerWebExchange.from(request); - filter.filter(exchange, e -> Mono.empty()).block(); + filter().filter(exchange, ignored -> Mono.empty()).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) @@ -974,176 +343,75 @@ void trustedTcpProxyHandshakeRejectsNonPositiveGameInstanceId() { } @Test - void trustedTcpProxyHandshakeRejectsPartialProxyIdentityBundle() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - - MockServerHttpRequest request = - MockServerHttpRequest.get("/ws/game/test") - .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-123") - .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "1") - .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, "demo") - .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, "production") - .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, "17") - .build(); - - MockServerWebExchange exchange = MockServerWebExchange.from(request); - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_SCOPE_MISMATCH); - } - - @Test - void rejectsExpiredConnectToken() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("test")); - JwtUtil expiredJwtUtil = new JwtUtil(SECRET, -1L); - String token = - expiredJwtUtil.generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-expired", - "requestId", "req-expired", - "jti", "jti-expired")); - + void trustedTcpProxyMalformedIdentityBundleIsDenied() { + GameplayHandshakeFilter filter = filter(); MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) + .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-123") + .header(GameplayHandshakeFilter.TENANT_ID_HEADER, "1") .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_EXPIRED); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) - .isNull(); + .isEqualTo(GameplayHandshakeFilter.CONNECT_SCOPE_MISMATCH); } - @Test - void rejectsReplayedConnectToken() { - ReactiveStringRedisTemplate redisTemplate = mock(ReactiveStringRedisTemplate.class); - @SuppressWarnings("unchecked") - ReactiveValueOperations valueOps = mock(ReactiveValueOperations.class); - when(redisTemplate.opsForValue()).thenReturn(valueOps); - when(valueOps.setIfAbsent( - eq("gateway:connect-token:jti:jti-replay"), eq("1"), any(java.time.Duration.class))) - .thenReturn(Mono.just(true), Mono.just(false)); - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - redisTemplate, - environmentWithProfiles("test")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-replay", - "requestId", "req-replay", - "jti", "jti-replay")); - - MockServerWebExchange first = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - MockServerWebExchange second = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - - filter.filter(first, e -> Mono.empty()).block(); - filter.filter(second, e -> Mono.empty()).block(); - - assertThat(second.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(second.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REPLAYED); + private static GameplayHandshakeFilter filter() { + return new GameplayHandshakeFilter( + TEST_RUNTIME_IDENTITY, GameplayWebSocketObservability.disabled()); } - @Test - void rejectsWhenReplayProtectionStorageIsMissingOutsideDevOrTest() { - GameplayHandshakeFilter filter = - new GameplayHandshakeFilter( - new JwtUtil(SECRET, 30_000L), - TEST_RUNTIME_IDENTITY, - null, - environmentWithProfiles("prod")); - String token = - new JwtUtil(SECRET, 30_000L) - .generateToken( - "7", - Map.of( - "aud", "gameplay-connect", - "accountId", "7", - "tenantId", "1", - "worldSlug", "demo", - "realmSlug", "production", - "gameInstanceId", "42", - "pointerVersion", "17", - "connectScopeId", "scope-no-redis", - "requestId", "req-no-redis", - "jti", "jti-no-redis")); - - MockServerWebExchange exchange = - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game/test") - .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) - .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - - assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); - assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_REPLAY_PROTECTION_UNAVAILABLE); + private static HeaderTrustFilter trustedHeaderFilter() { + GatewayHeaderTrustProperties properties = new GatewayHeaderTrustProperties(); + properties.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); + properties.getTcpProxy().setInsecureTrustedCidrs(List.of("10.0.0.0/8")); + return HeaderTrustFilterTest.legacyFilter(properties); } - private ServerWebExchange filterThroughChain(WebFilter filter, ServerWebExchange exchange) { - return filterThroughChain(filter, exchange, new AtomicBoolean()); + private static MockServerWebExchange trustedProxyExchange( + String worldSlug, + String realmSlug, + String pointerVersion, + String tenantId, + String gameInstanceId) { + return MockServerWebExchange.from( + MockServerHttpRequest.get("/ws/game/test") + .header(GameplayHandshakeFilter.PROXY_CONNECTION_ID_HEADER, "conn-123") + .header(GameplayHandshakeFilter.TENANT_ID_HEADER, tenantId) + .header(GameplayHandshakeFilter.GAME_INSTANCE_ID_HEADER, gameInstanceId) + .header(GameplayHandshakeFilter.WORLD_SLUG_HEADER, worldSlug) + .header(GameplayHandshakeFilter.REALM_SLUG_HEADER, realmSlug) + .header(GameplayHandshakeFilter.POINTER_VERSION_HEADER, pointerVersion) + .build()); } - private ServerWebExchange filterThroughChain( - WebFilter filter, ServerWebExchange exchange, AtomicBoolean delegated) { - ServerWebExchange[] holder = new ServerWebExchange[1]; - WebFilterChain chain = - e -> { - delegated.set(true); - holder[0] = e; - return Mono.empty(); - }; - filter.filter(exchange, chain).block(); - return holder[0] == null ? exchange : holder[0]; + private static ServerWebExchange filterThroughChain( + WebFilter filter, ServerWebExchange exchange) { + AtomicReference forwarded = new AtomicReference<>(); + filter + .filter( + exchange, + forwardedExchange -> { + forwarded.set(forwardedExchange); + return Mono.empty(); + }) + .block(); + return forwarded.get() == null ? exchange : forwarded.get(); } - private ServerWebExchange withRequestHeader( + private static ServerWebExchange withRequestHeader( ServerWebExchange exchange, String headerName, String headerValue) { return exchange .mutate() diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java index 8929f7be69..929e3835b7 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java @@ -2,37 +2,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -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 io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.WebSocket; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.concurrent.CompletableFuture; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; -import net.firedevops.firemud.common.security.JwtUtil; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.health.contributor.Health; import org.springframework.boot.health.contributor.Status; class GameplayRouteReadinessHealthIndicatorTest { @Test - void healthReturnsOutOfServiceWhenLocalGameplayRouteCannotUpgrade() { + void firstPartyReadinessRemainsDownUntilCanonicalAdmissionPrerequisitesAreQualified() { GameplayRouteReadinessHealthIndicator indicator = - new GameplayRouteReadinessHealthIndicator( - 1, tracker(), provider(new JwtUtil(SECRET, 30_000L))); + new GameplayRouteReadinessHealthIndicator(tracker()); Health health = indicator.health(); Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); @@ -44,57 +29,18 @@ void healthReturnsOutOfServiceWhenLocalGameplayRouteCannotUpgrade() { assertIterableEquals( List.of("contract", "admissionMeaning", "dependencies", "failingDependency"), health.getDetails().keySet()); + assertEquals("gameplayRoute", health.getDetails().get("failingDependency")); Map gameplayRoute = Objects.requireNonNull(dependencies.get("gameplayRoute")); assertEquals("DOWN", gameplayRoute.get("status")); - } - - @Test - void readinessProbeUsesProtectedConnectTokenCookie() { - HttpClient client = mock(HttpClient.class); - WebSocket.Builder builder = mock(WebSocket.Builder.class); - when(client.newWebSocketBuilder()).thenReturn(builder); - when(builder.header(anyString(), anyString())).thenReturn(builder); - when(builder.buildAsync(any(URI.class), any(WebSocket.Listener.class))) - .thenReturn(CompletableFuture.failedFuture(new IOException("probe unavailable"))); - - GameplayRouteReadinessHealthIndicator indicator = - new GameplayRouteReadinessHealthIndicator( - 1, tracker(), provider(new JwtUtil(SECRET, 30_000L)), client); - - indicator.health(); - - verify(builder) - .header(eq("Cookie"), org.mockito.ArgumentMatchers.startsWith("Firemud-Connect-Token=")); - verify(builder, never()).header(eq("X-Firemud-Connect-Token"), anyString()); + assertEquals("websocketUpgrade", gameplayRoute.get("check")); + assertEquals("first-party admission", gameplayRoute.get("target")); + assertEquals( + "Canonical Account connect-context production, shared replay fencing, and dedicated " + + "Gateway signing keys are not qualified", + gameplayRoute.get("reason")); } private static ReadinessTransitionTracker tracker() { return new ReadinessTransitionTracker(new SimpleMeterRegistry()); } - - private static final String SECRET = "testsecretkeytestsecretkeytest1234"; - - private static ObjectProvider provider(JwtUtil jwtUtil) { - return new ObjectProvider<>() { - @Override - public JwtUtil getObject(Object... args) { - return jwtUtil; - } - - @Override - public JwtUtil getIfAvailable() { - return jwtUtil; - } - - @Override - public JwtUtil getIfUnique() { - return jwtUtil; - } - - @Override - public JwtUtil getObject() { - return jwtUtil; - } - }; - } }