diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 562c9f6907..84e7ac59f2 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -187,7 +187,7 @@ In production, FireMUD is deployed into Kubernetes (e.g., AWS EKS, Google GKE, o render matching checked-in baseline policies from the Helm chart using chart-specific selectors for the preview stack's labels. - Configuration and secrets are managed through ConfigMaps and Secrets. -- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests eight per-workload gRPC leaves from `firemud-ca-issuer` (five publication workloads, Account, Game Session, and Social Groups) and materializes and reconciles thirteen runtime Secret projections (the five shared-role projections plus eight distinct `firemud-grpc-` projections). In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the eight fixed per-workload gRPC leaves for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. +- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests eight serving-workload gRPC leaves from `firemud-ca-issuer` (five publication workloads, Account, Game Session, and Social Groups) and a ninth client-only Gateway workload leaf for authenticated gameplay receiving. It materializes and reconciles fourteen runtime Secret projections: the five shared-role projections, eight serving-workload projections and `firemud-grpc-spring-cloud-gateway` for the independent outbound Gateway client. The latter has the exact same-namespace Gateway URI SAN and `clientAuth` usage, without DNS/server usage; it does not replace Gateway management-server TLS or the `gateway-internal-ws` server leaf. In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the eight fixed serving-workload gRPC leaves and separate client-only Gateway leaf for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. - The cluster uses **IPVS** (or a similar load-balancing mode) to route service traffic efficiently. - Redis is deployed as **two logical roles** in both Kubernetes and Docker Compose (see [Redis Architecture](../system-architecture-redis.md)): - A **Coordination Redis** deployment runs as a clustered StatefulSet with automatic failover in production and smaller clusters in non-production. It uses AOF, persistent volumes, and `noeviction` in player-facing environments to preserve volatile coordination state across normal rollouts and pod restarts within the documented tail-loss envelope; Redis is not the authoritative recovery or audit log. AOF, persistent volumes, and `noeviction` alone are insufficient for player-facing replay safety: the deployment must also satisfy the [ADR 0029 replay-readiness contract](../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), including Redis 7.2+, ACL isolation, reserved capacity and an admission-readiness threshold, atomic marker consumption, configured `WAITAOF` local/replica acknowledgement thresholds, and a shared reset/uncertain-durability quarantine fence. A profile that cannot prove those controls is not eligible to admit new player handshakes. @@ -322,11 +322,11 @@ FireMUD's preview environment is a hosted single-node k3s cluster intended for r Hosted Helm values select certificate identity explicitly at `previewStack.certificateIdentity.mode`. A missing mode means `standalone`; the only accepted explicit values are `standalone` and `hosted-controller`. Malformed, duplicate, non-string, or unknown mode configuration is fatal, and selecting `hosted-controller` never falls back to workflow-created certificate identity. This keeps the controller and its authority dormant before activation while preserving existing standalone deployments. -For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and eight workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`): the five publication workloads plus Account, Game Session, and Social Groups. It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. +For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and nine workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`): the five publication workloads plus Account, Game Session and Social Groups serving leaves, and the independent client-only `spring-cloud-gateway` leaf for the [authenticated gameplay hop](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. The internal preview CA is not installed while a legacy preview credential can read its private-key Secret or create signing requests or issuer aliases. Its only Kubernetes private-key copies are `firemud-system/firemud-grpc-ca` and `cert-manager/firemud-grpc-ca`; no runtime namespace receives a CA private key. Trusted namespace management, namespace-local runtime deployment, fixed standalone Certificate writing, hosted identity requesting, and recovery use distinct scoped credentials. The runtime and Certificate writers are bound only in the validated runtime namespace. Fail-closed admission binds the canonical internal issuer, its two protected CA Secret copies, exact standalone and retained Certificate shapes (including each gRPC workload SAN and Secret mapping), and cert-manager-generated CertificateRequests; cert-manager's built-in auto-approval is not itself an authorization boundary. Before any CA material is installed, operators prove live denial of direct and alias issuance paths and rotate the former `preview-deployer` credential. The CA recovery copy belongs to a separate `develop`-restricted recovery-only GitHub Environment and is restored only by its scoped trusted procedure. The same procedure can be instantiated with different credentials and trust material for a future production boundary, but this preview preparation does not establish production readiness. See the [preview trust bootstrap sequence](../../../k8s/trust-bootstrap/README.md). -The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all thirteen labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and eight distinct workload projections (the five publication workloads plus `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all thirteen labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. +The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all fourteen labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and nine distinct workload projections (the eight serving-workload leaves and the independent `firemud-grpc-spring-cloud-gateway` outbound client leaf). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all fourteen labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A Namespace-backed counter permits at most three proof-retry dispatches for one exact base/head/merge/image tuple and resets when that tuple changes; the counter and tuple are read and updated with the Namespace `resourceVersion`, and malformed evidence fails closed. These controls bound retry dispatches without claiming live proof. @@ -334,17 +334,17 @@ Post-apply identity, rollout, and mode-specific verification runs after `deploy- The trusted consumer derives one immutable exposure mode from the validated sanitized artifact before allocation or runtime mutation: `Service/tcp-proxy-service.spec.type: ClusterIP` selects `private`, and `NodePort` selects `public`; any other type, missing service, or later mode mismatch fails closed. The trusted workflow records that mode as the `firemud.dev/preview-exposure-mode` label on the runtime Namespace, not as an annotation; PR-controlled rendering cannot choose a different mode after validation. Requester credentials remain confined to the protected `trusted-hosted-cluster` workflow boundary and are used only for the canonical identity request, never exposed to the PR-controlled source or render jobs. -The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all thirteen labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. +The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all fourteen labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. The `public` mode owned by #2795 retains the allocated preview NodePort and its Telnet-port annotation. It requires the same head-bound projections, rollout, HTTPS, bridge, and gRPC readiness plus the served public Telnet check and `LOGIN -> PLAY -> LOOK` smoke; a failed public check is a terminal failure for that mode. The workflow never converts a failed public deployment or smoke into `private`, and private success cannot satisfy the public mode's Telnet or ADR 0178 two-public-path obligations. The private exception is limited to this explicit parent bridge proof and does not amend the accepted public transport-complete target. -The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all thirteen labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. +The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all fourteen labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. Privileged preview janitor, preview reconciler, dev-demo deploy/destroy, and dev-demo reconciler jobs accept scheduled or typed `repository_dispatch` requests rather than branch-selectable `workflow_dispatch` requests. A repository maintainer can trigger those trusted default-branch operations through `POST /repos///dispatches` with `event_type` set to `preview-janitor`, `preview-reconcile`, `dev-demo`, or `dev-demo-reconcile`; `dev-demo` accepts a validated `client_payload` with optional `action` (`deploy` or `destroy`), `head_sha`, `image_tag`, fixed `hostname`, and fixed `telnet_port`. The reconciler uses the same `dev-demo` event for exact-head retry. Manual per-PR deploy/release requests use the default-branch preview source workflow's typed `preview-deploy` or `preview-destroy` repository dispatch with a validated `client_payload` containing matching `action`, canonical `pr_number`, current `head_sha`, and fixed `preview_domain`; the source resolves the effective head-or-base image tag independently and produces only a sanitized render artifact or destroy intent for the trusted lifecycle. Priority labeling, capacity allocation, and cleanup remain trusted lifecycle decisions. Before a trusted operator activates the hosted identity controller, that operator must provision the fixed `firemud-system/firemud-grpc-ca` `Opaque` Secret with exactly `ca.crt` and `ca.key`. The configured trust-anchor value is the lowercase 64-hex SHA-256 fingerprint of the DER-encoded CA certificate. Bootstrap verifies the key shape and certificate fingerprint without printing either value; the controller independently verifies that the CA certificate and private key correspond before it issues any transport-only leaf. The controller only consumes this prerequisite and is not a CA provisioning authority. Standalone mode uses the same protected issuer for per-workload gRPC leaves: `firemud-grpc-ca` private-key copies stay in `firemud-system` and `cert-manager`, while cert-manager owns only leaf Secrets in `dev` and `pr-N` runtime namespaces. Leaf keys rotate with their Certificates; deleting a runtime namespace removes its leaf Certificates and projections without affecting the shared CA copies. -Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all thirteen runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus eight distinct per-workload gRPC projections: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), Game Session (`firemud-grpc-game-session-service`), and Social Groups (`firemud-grpc-social-groups-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the eight workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. +Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all fourteen runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus eight serving-workload gRPC projections and the independent Gateway gameplay-client projection: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), Game Session (`firemud-grpc-game-session-service`), Social Groups (`firemud-grpc-social-groups-service`), and the client-only Gateway (`firemud-grpc-spring-cloud-gateway`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the nine workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and the label-scoped Account, Game Session, and Social Groups TCP/6565 selectors remain explicit; the existing Social Groups served-identity probe checks the current projected leaf at its fixed gRPC endpoint. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gateway↔TCP Proxy bridge proof remain required. diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 6732843377..19f30c887e 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -106,7 +106,7 @@ Before the [initial-context adapter](../system-architecture-redis-usage-and-prof ## TLS & Certificates -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. Static render and hosted-controller contract checks cover the eight distinct bindings and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP gameplay receiving requires the [dedicated workload-mTLS hop](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving); see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. A ninth workload identity is the independent client-only `firemud-grpc-spring-cloud-gateway` leaf for authenticated gameplay. Its dedicated gameplay-client TLS paths and mounts leave the existing Gateway management-server binding and Gateway-internal WebSocket server leaf unchanged. Static render and hosted-controller contract checks cover the eight serving-workload bindings, the client-only Gateway binding, and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) @@ -121,6 +121,21 @@ A sample `Certificate` manifest is provided at `k8s/base/firemud-grpc-certificat | `FIREMUD_GRPC_PRIVATE_KEY_PATH` | Filesystem path to the private key matching the certificate chain | `certs/client.key` | | `FIREMUD_GRPC_CA_CERT_PATH` | Filesystem path to the CA bundle used to verify peer services | `certs/ca.crt` | +### Authenticated TCP Gameplay Bridge + +Ordinary Gateway-to-backend HTTP and WebSocket routes remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls. Authenticated TCP gameplay receiving uses a separate verified-origin `wss://` connection from Gateway to Game Session, with a dedicated client identity and a dedicated Game Session TLS listener. The [Security Architecture](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the trust and custody contract; the [player access tracker](../../project-management/implementation-tracking/player-access-and-session.md) records current registration and deployment proof status. + +| Variable | Purpose | Default / current binding | +| -------- | ------- | ------- | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL` | Gateway's authenticated receiver URI; the authenticated client is absent when this property is unset. | No code default; unset unless deployment binds it. Hosted Helm binds `wss://game-session-service.$(FIREMUD_GRPC_WORKLOAD_NAMESPACE).svc.cluster.local:8444/ws/game/tcp`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH` | Gateway's dedicated client certificate chain for the authenticated receiver. | Empty by default; base and hosted bindings use `/gameplay-client-tls/tls.crt`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH` | Private key matching the dedicated Gateway client certificate. | Empty by default; base and hosted bindings use `/gameplay-client-tls/tls.key`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH` | Trust bundle used by Gateway to verify Game Session's authenticated listener certificate. | Empty by default; base and hosted bindings use `/gameplay-client-trust/ca.crt`. | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED` | Enables Game Session's separate authenticated gameplay TLS listener. | `false`; hosted Helm sets `true`. | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT` | Port for the separate listener, distinct from the configured ordinary HTTP port. | `8444`; hosted Helm sets `8444`. | + +The TLS path defaults are empty in Gateway's authenticated-client binding; Kubernetes supplies the dedicated mounted paths shown above. Game Session's listener is disabled unless enabled explicitly. The shared `firemud-grpc` SSL bundle currently supplies the listener certificate and reload source; these gameplay-specific Gateway client paths do not replace Gateway's `FIREMUD_GRPC_*` management-plane paths or its independent TCP Proxy-facing WebSocket server identity. Exact registration, issuance, and deployment evidence remains subject to the linked owner and tracker. + ### Gateway HTTP Management-Plane TLS (Target State) Gateway-owned HTTP management endpoints use a dedicated operator client identity and listener trust bundle. These paths are separate from the Gateway service's `FIREMUD_GRPC_*` workload identity and are resolved from the selected `operator-credential-binding/v1` record. For `SECRET_BACKED` and `CERT_MANAGER` bindings, the client certificate/key and trust bundle are file-backed through the variables below; a `WORKLOAD_IDENTITY` binding uses its provider-projected client identity and trust bundle and does not require a substitute Secret or these file paths. The binding record's closed `bindingType` and source-specific resolution, not this catalog or endpoint-local configuration, determine which representation applies: diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index 6c162d5237..b72f112c03 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -135,7 +135,7 @@ This section describes the Kubernetes-backed environments that use the canonical - Kubernetes `ConfigMap` objects store non‑secret configuration values like host names or feature flags. - Sensitive values (database passwords, TLS private keys, and interim JWT signing bundles) are delivered through Kubernetes `Secret` objects. The public `jwt-jwks` projection is delivered separately as read-only public material; hosted preview materializes it as a `ConfigMap`. -- TLS certificates are issued by **cert-manager** and rotated automatically. The eight gRPC workload consumers (the five publication services plus Account, Game Session, and Social Groups) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Each distinct workload projects only `tls.crt` and `tls.key` from its own Secret at `/tls`, and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust` for peer trust. Live issuance and served-identity readiness remain unproved, and hosted rendering is not player-facing or promotion evidence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). +- TLS certificates are issued by **cert-manager** and rotated automatically. The eight gRPC workload consumers (the five publication services plus Account, Game Session, and Social Groups) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Each distinct workload projects only `tls.crt` and `tls.key` from its own Secret at `/tls`, and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust` for peer trust. A ninth, client-only Gateway workload leaf is issued and projected independently for [authenticated gameplay receiving](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). It mounts only its private key/certificate under `/gameplay-client-tls` and public shared CA trust under `/gameplay-client-trust`; it does not replace Gateway management TLS or the separate Gateway-internal WebSocket server leaf. Live issuance and served-identity readiness remain unproved, and hosted rendering is not player-facing or promotion evidence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). - JWT authority and lifecycle are defined by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). This overview records only the interim Account private-bundle mount, public JWKS mounts, and watcher delivery. - In player-facing environments (`hobby-self-hosted`, staging, production), the selected `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` mode allows only Account Service to consume JWT private signing material from a mounted file via `FIREMUD_AUTH_JWT_SECRET_PATH`, and only Account uses `JwtSecretWatcher` on that path; Account and every validator must consume the public JWKS projection. The selected `TARGET_NON_EXPORTABLE_SIGNER` mode has no private path or application private material and uses the same public-JWKS consumer boundary. The current `LEGACY_SECRET_DIAGNOSTIC` mode is shared-HMAC Secret/path wiring evidence only and is never player-facing authorization; inline-only or HMAC-only configuration and private-key mounts in validators are non-compliant for accepted modes. Current hosted preview is a separate HMAC/test wiring path and its hosted validation does not prove validator consumption. - Database credentials are stored in Secrets and rotated via explicit operational Jobs and runbooks (for example `db-credential-rotation` in `system-architecture-backup-recovery.md#post-restore-secret-hardening`); there is no fully automatic cadence today. @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate each of the eight distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP LOGIN/lobby/PLAY receiving instead uses the dedicated workload-mTLS WebSocket boundary; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups, plus the separate client-only Gateway leaf. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped serving-workload Secrets, the client-only `firemud-grpc-spring-cloud-gateway` Secret, and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The separately issued ninth workload leaf, `firemud-grpc-spring-cloud-gateway`, is client-only for authenticated TCP gameplay receiving. Its dedicated `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` binding leaves Gateway management-server `FIREMUD_GRPC_*` paths and its independent TCP-Proxy-facing WebSocket server leaf unchanged. Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct serving-workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate all nine distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index a5104b03b2..9e594b15da 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -14,6 +14,8 @@ Game Session follows the configuration scheme from [Environment Variables & Secr TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, `FIREMUD_GRPC_CA_CERT_PATH`](../../infrastructure/environment-and-secrets.md#grpc-tls-certificates). Peer services can be discovered using variables prefixed `FIREMUD_SERVICES_`. The OpenTelemetry collector endpoint can be overridden via `OTEL_ENDPOINT`. +The authenticated TCP gameplay receiver uses a separate internal TLS listener, disabled by default and distinct from the configured ordinary HTTP port. [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the mTLS trust and custody contract. The [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge) records the deployed bindings. + | Variable | Purpose | Default | | -------- | ------- | ------- | | `GAME_TICK_DURATION_MS` | Tick cadence (`tick_interval_ms`): target interval between ticks for a region | `1000` | @@ -25,6 +27,8 @@ TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC | `FIREMUD_SERVICES_WORLD_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for World Management Service | `world-management-service:6565` | | `FIREMUD_SERVICES_ENTITY_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for Entity Management Service | `entity-management-service:6565` | | `FIREMUD_CONFLICT_TTL_SECONDS` | TTL for conflict hotspot tracking in Redis | `300` | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED` | Enables the separate mTLS listener for authenticated TCP gameplay receiving. | `false` (hosted Helm: `true`) | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT` | Port for the separate listener; must differ from the ordinary HTTP port. | `8444` (hosted Helm: `8444`) | ## FireMUD Settings Domains @@ -77,3 +81,7 @@ The generated reference carries the current defaults, descriptions, valid values - Bounded semantic reconnect context, including its retention/resource controls, scope, and non-authority semantics, is owned by [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#canonical-resume-context-model) and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). This service document links that owner rather than duplicating the full contract. Prompt/status output remains excluded from semantic reconnect context unless a future explicit transcript policy says otherwise. - The owner documentation records the current implementation/proof gaps for oversized-single-entry handling and namespace/schema-envelope accounting; this service document does not claim strict hard-ceiling enforcement. - The older internal reconnect-adjacent rendered-room snapshot helper is no longer part of the surfaced settings model and should not be treated as an authoritative `LOOK` cache. + +## Authenticated TCP Receiving + +The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving accepts only actual protected LOGIN/lobby source owners. Their runtime and protected-source composition is a separate successor boundary; absent owners or source qualification remain unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 96ea81ea4f..d62e9ab4d6 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -20,6 +20,7 @@ Spring Cloud Gateway reads its configuration from a small set of sources. The fu | `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` | Cache/Rate-Limit Redis endpoint used by the gateway `RequestRateLimiter` filter. | See [Redis Connection](../../infrastructure/environment-and-secrets.md#redis-connection). | | `firemud.gateway.header-trust.*` | Header-trust and canonicalization configuration enforced by `HeaderTrustFilter` for public ingress versus trusted proxy sources. | Service-local gateway trust boundary; behavior must stay aligned with [Gateway Architecture](../../system-architecture-gateway.md#header-trust-model). | | `FIREMUD_GATEWAY_TCP_PROXY_TLS_*` / `FIREMUD_GATEWAY_TCP_PROXY_TRUST_*` | Dedicated internal TLS listener material, environment classification, and the one selected TCP Proxy trust profile. | Service-local implementation of [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md); exact variables are listed below. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL` and `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` | Dedicated verified-origin `wss` client for authenticated TCP gameplay receiving. | See the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge); custody and trust rules belong to [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). | | `firemud.gateway.backendUnavailableGraceMs` / `firemud.gateway.backendUnavailableRecoverySuccessCount` | Target gameplay-route backend-unavailable elapsed-time cutoff and recovery hysteresis knobs. The grace value must be positive and no greater than ADR 0013's 30,000 ms hard cutoff; ordinary qualifying recovery targets 10 seconds. | Not implemented in the current bound properties or bridge. Canonical behavior lives in [Gateway Architecture](../../system-architecture-gateway.md#backend-unavailable-grace-window), [Reconnection Strategy](../../system-architecture-reconnection.md#backend-unavailable-scenarios), and [ADR 0013](../../decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md). | | `FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, `FIREMUD_GRPC_CA_CERT_PATH` | TLS certificate and key paths for the gateway internal gRPC management plane. | See [gRPC TLS Certificates](../../infrastructure/environment-and-secrets.md#grpc-tls-certificates). | | `OTEL_ENDPOINT` | OpenTelemetry collector endpoint for traces. | See [Observability](../../infrastructure/environment-and-secrets.md#observability). | @@ -32,7 +33,7 @@ The trusted default-branch workflow treats the hosted preview Gateway configurat The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. -The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. +The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Game Session on TCP/8444 for the dedicated authenticated mTLS WebSocket receiver at `/ws/game/tcp`, Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. ### TCP Proxy TLS listener @@ -97,15 +98,20 @@ Any additional gateway-local caches must explicitly declare whether they are str - **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). +- Ordinary Spring Cloud Gateway backend routes use in-cluster `http://` and `ws://` endpoints under their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; those route exceptions do not establish authenticated TCP receiving authority. That receiver uses a separate verified-origin `wss://` connection to Game Session with the dedicated client identity and trust paths documented in the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge), under the [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). Internal service-to-service gRPC traffic uses mTLS as described in the [Security Architecture](../../system-architecture-security.md). - When internal WebSocket clients such as the TCP Proxy Service connect over `wss://` to `/ws/game/**`, the host used in `GATEWAY_WS_URL` must match a name present in the Gateway certificate SANs so SNI and hostname verification succeed. Using a bare IP or an unrelated hostname causes client-side TLS failure, and those failures should remain visible in TCP Proxy bridge metrics and logs. ## Dependencies - Internal dependencies: - - Game Session Service and other backend services via configured `http://` and `ws://` route targets. + - Game Session Service and other backend services via configured ordinary `http://` and `ws://` route targets, which remain explicit in-cluster exceptions. + - Game Session's authenticated TCP receiver via its dedicated verified-origin `wss://` endpoint and Gateway client mTLS identity; see the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge) and [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). - TCP Proxy Service, which forwards Telnet traffic into the gateway. - External dependency: - Spring Cloud Gateway infrastructure. See [Gateway Architecture](../../system-architecture-gateway.md), [Deployment Environments](../../infrastructure/deployment-environments.md), and [Protocol Bridging](../../system-architecture-protocol-bridging.md) for the shared topology. + +## Authenticated TCP Receiving + +The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving composes only actual protected LOGIN/lobby source owners. Missing source qualification remains unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index 9e0657df5c..9c9fbd1236 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -38,7 +38,7 @@ Before the first player-facing deployment into `hobby-self-hosted`, `staging`, o 1. Provision the target namespace and registry pull credentials used by workloads. 2. Provision per-environment PostgreSQL credentials (`postgres-credentials`) and, when rotation Jobs are used, `postgres-admin-credentials`. 3. Select and record the custody state before applying workloads. The checked-in player-facing Kustomize mode is legacy Secret-backed signing plus public Secret JWKS wiring (`jwt-signing-keys` Secret and `jwt-jwks` Secret); it may appear in pre-apply diagnostics but is non-authorizing and is not an accepted player-facing custody state. Hosted preview Helm remains a separate diagnostic ConfigMap-backed path. For `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK`, establish trusted pre-apply evidence for the pre-created interim `jwt-signing-keys` Secret, the separate interim Account-owned public `jwt-jwks` ConfigMap, and the materialization controller's name-scoped RBAC. Account has exclusive mounted/signing use of the private bundle; the materialization controller has only bounded, Account-authorized byte handling needed to materialize it and no competing signing authority. The [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative) define custody and operation authority; this runbook requires every private-slot `generate`, `materialize`, `resourceVersion`-CAS, and `prune` action to use a persisted Account-authorized operation, with the controller executing only that operation and unable to choose slots or mutate desired key-ring state independently. For target non-exportable signer mode, establish trusted pre-apply evidence for the approved signer reference, target Account-owned public `jwt-jwks` ConfigMap, Account publication/CAS authority, and no private-material mount or distribution. In both accepted modes, `FIREMUD_AUTH_JWKS_PATH` is mandatory for Account and every validator; only the interim mode sets `FIREMUD_AUTH_JWT_SECRET_PATH`, while target non-exportable signer mode leaves it unset. These bootstrap records prove intended bindings and custody boundaries only; post-apply live signer, public-JWKS, and validator convergence is a separate owner-produced gate. -4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account, Game Session, and Social Groups workload Secrets `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. Each of these eight leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all eight distinct workload leaves. Both checked-in Kustomize and hosted Helm Pods for all eight distinct workloads project only `tls.crt` and `tls.key` from their corresponding workload Secret at `/tls` and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust`. Peer trust uses `/grpc-trust/ca.crt` so these workloads can verify both the retained shared leaf and the distinct workload leaves. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. +4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account, Game Session, and Social Groups workload Secrets `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. Separately provision the ninth, client-only `firemud-grpc-spring-cloud-gateway` Secret using the profile owned by the [deployment-environment contract](./infrastructure/deployment-environments.md#kubernetes-characteristics). All nine leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; each Secret's `ca.crt` must establish trust for its own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all nine distinct workload leaves. Both checked-in Kustomize and hosted Helm Pods for all eight distinct serving workloads project only `tls.crt` and `tls.key` from their corresponding workload Secret at `/tls` and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust`. Gateway separately projects its client-only `tls.crt` and `tls.key` at `/gameplay-client-tls` and shared `ca.crt` at `/gameplay-client-trust`, leaving its management-server and TCP-Proxy-facing server bindings unchanged. Peer trust uses `/grpc-trust/ca.crt` for the eight serving workloads and `/gameplay-client-trust/ca.crt` for the Gateway client so these workloads can verify both the retained shared leaf and the distinct workload leaves. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each serving-workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each serving workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep all nine workload leaves and private keys distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. 5. Provision per-environment external integration credentials: backup/object-store, asset-store, outbound-communications, and operator-control-plane credentials as needed for that environment class. 6. Run `./dev-tools/deploy/preflight.py ` and require the common checks `PREFLIGHT-BOOTSTRAP-001`, `PREFLIGHT-SECRETS-001`, `PREFLIGHT-SECRETS-002`, `PREFLIGHT-BRIDGE-001`, `PREFLIGHT-REDIS-001`, `PREFLIGHT-EXTERNAL-001`, and `PREFLIGHT-SERVICES-001`, plus exactly one authenticated custody proof whose `proofId`, `custodyMode`, and `contractVersion` exactly match the selected mode: `PREFLIGHT-JWT-INTERIM-001` for `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` or `PREFLIGHT-JWT-002` for `TARGET_NON_EXPORTABLE_SIGNER`. Preserve that exact tuple in the deployment record for retry/replay. An unknown, unsupported, or not-yet-implemented state fails closed. `PREFLIGHT-JWT-001` and `PREFLIGHT-JWKS-001` may be emitted as legacy diagnostic wiring results, but they are never custody proof or player-facing readiness evidence and cannot substitute for the selected custody proof. 7. Record trusted pre-apply bootstrap secret-compliance evidence for each Tier A credential class. First deployment may use immutable initial-provisioning evidence (`lastProvisionedAt`) instead of rotation evidence, but the record must still satisfy the canonical secret-compliance schema before the environment is considered promotable or traffic-open. This evidence proves provisioning and binding only; it does not prove live signer or validator convergence. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index f479fef6a1..2089f46ef3 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -71,6 +71,8 @@ For the Telnet-to-WebSocket bridge – including the `GATEWAY_WS_URL` contract, ### Header Trust Model +Authenticated TCP LOGIN/lobby/PLAY uses the [dedicated Gateway-to-Game Session mTLS receiver](./system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). Only TCP provenance actually verified by this Gateway may be relayed on that hop; ordinary forwarded headers and the in-cluster HTTP/WebSocket exception do not establish backend LOGIN custody. + Spring Cloud Gateway acts as the canonicalizer for client identity and session/tenant headers. It defines a strict trust boundary between **public ingress**, the **Telnet TCP Proxy**, and **internal services**: - Headers that may carry client, session, or routing identity (`X-Client-IP`, `X-Game-Instance-Id`, `X-Tenant-Id`, `X-World-Slug`, `X-Realm-Slug`, `X-Pointer-Version`, and all `X-Proxy-*` headers) are **never trusted directly from public clients**. The gateway strips or overwrites any such headers that arrive from the external load balancer or browser/WebSocket clients before routing to backend services. @@ -79,7 +81,7 @@ Spring Cloud Gateway acts as the canonicalizer for client identity and session/t - Derives canonical `X-Client-IP` from `X-Proxy-Client-IP` (and any PROXY-provided metadata) and overwrites any existing `X-Client-IP`. - Generates and forwards only canonical `X-Game-Instance-Id` and `X-Tenant-Id` from the corresponding authenticated proxy inputs where appropriate for gameplay routes; raw `X-Proxy-Game-Instance-Id` and `X-Proxy-Tenant-Id` never reach downstream services. - Accepts the routing bundle only when all three fields are present and valid or all three are absent, rejects a partial or malformed bundle, and forwards the validated advisory `X-World-Slug`, `X-Realm-Slug`, and `X-Pointer-Version` values to Game Session. - - Preserves the authenticated TCP Proxy's `X-Proxy-Connection-Id` value unchanged as the **sole mTLS-bound raw-name correlation exception**: a server-owned opaque Telnet-socket identity for disconnect correlation and observability. Gateway does not generate a replacement identifier or treat it as authorization material. The TCP Proxy's `NotifyDisconnect` event carries this same `proxyConnectionId` with its per-connection `disconnectSequence`; a public or untrusted raw value is never forwarded. + - Preserves the authenticated TCP Proxy's connection UUID unchanged as the **sole mTLS-bound raw-name correlation exception**. The TCP Proxy's `NotifyDisconnect` event carries this same `proxyConnectionId` with its per-connection `disconnectSequence` for lifecycle correlation. - Downstream services must treat `X-Client-IP`, `X-Game-Instance-Id`, `X-Tenant-Id`, `X-World-Slug`, `X-Realm-Slug`, and `X-Pointer-Version` as **gateway-owned or gateway-validated** headers. Services must ignore or overwrite any attempts by callers to spoof these values via gRPC metadata or additional HTTP headers and should rely on their own Redis/session keys and authoritative pointer reads for identity and admission as described in [Authentication & Authorization](./system-architecture-authentication.md) and [Multi-Tenancy](./system-architecture-multi-tenancy.md). - All JWT validation and authorization logic lives in downstream admin and meta services (such as the Logging & Admin Service and Account Service), which must treat Spring Cloud Gateway as a dumb proxy and may not assume it has performed any authentication checks. @@ -94,7 +96,7 @@ Spring Cloud Gateway is the **canonicalization point** for any client-identity a These headers are treated as **untrusted inputs** unless the gateway has authenticated the upstream hop as the TCP Proxy Service: - `X-Proxy-Client-IP` – the Telnet client IP address as observed by the TCP Proxy Service (ideally recovered via PROXY protocol from the Telnet edge proxy in Kubernetes SNAT scenarios). -- `X-Proxy-Connection-Id` – the TCP Proxy's server-generated stable identifier for the Telnet socket. This is the sole mTLS-bound raw-name correlation exception: Gateway preserves this authenticated value unchanged so it remains the `proxyConnectionId` used with the TCP Proxy's `disconnectSequence` to correlate `NotifyDisconnect` events; it is not a Gateway-generated session, scope, or authorization identifier. +- `X-Proxy-Connection-Id` – the TCP Proxy's stable, server-generated Telnet-socket correlation identifier. On certificate-bound gameplay routes Gateway requires the canonical lowercase UUID v4 form with the RFC variant and returns HTTP 403 for invalid values. Gateway preserves the verified value unchanged for disconnect correlation. Backend session and authorization have their own identifiers and checks. - `X-Proxy-Game-Instance-Id` / `X-Proxy-Tenant-Id` – advisory context captured from server-owned proxy defaults or a future explicitly selected transport adapter. These values are never semantic protocol negotiation or gameplay authority. ### Public Ingress Strip/Drop Rules @@ -139,7 +141,7 @@ After applying strip/authentication rules, the gateway sets or forwards the down - `X-Client-IP` – canonical client IP address: - If the upstream hop is authenticated as the TCP Proxy Service and `X-Proxy-Client-IP` is present, set `X-Client-IP` from `X-Proxy-Client-IP`. - Otherwise derive `X-Client-IP` from the trusted load balancer forwarded headers (for example `X-Forwarded-For`) using the gateway’s configured trusted-proxy rules. -- `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-Proxy-Connection-Id` – Gateway strips the raw inbound header and re-adds only the verified connection UUID for correlation with `NotifyDisconnect {proxyConnectionId, disconnectSequence}`. - `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 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. @@ -504,7 +506,7 @@ If gameplay execution is sharded across multiple Game Session instances, that sh ## TLS Termination for Gateway - **Browser / Web clients** – External `https://` / `wss://` connections terminate at the Internet-facing load balancer. The load balancer forwards `http://` / `ws://` traffic to Spring Cloud Gateway pods in the DMZ. The gateway then routes traffic to backend services using in-cluster `http://` and `ws://` targets (typically on port `8080`), while backend services communicate with each other over mTLS-protected gRPC as described in [Security Architecture](./system-architecture-security.md#tls-termination-for-gateway). -- **Telnet clients** – Telnet (plaintext) or Telnet-over-TLS connections terminate at the TCP Proxy Service. The proxy then connects to the canonical gameplay route `/ws/game/**` on Spring Cloud Gateway by dialing the Gateway’s internal-only WebSocket mTLS listener over `wss://` with mutual TLS. Spring Cloud Gateway forwards gameplay to the Game Session Service over the same WebSocket route (`/ws/game/**`). Detailed certificate and environment variable mappings are documented in [Security Architecture](./system-architecture-security.md#tls-termination-for-gateway) and [Protocol Bridging](./system-architecture-protocol-bridging.md#websocket-bridge-configuration). +- **Telnet clients** – Telnet and Telnet-over-TLS connections terminate at the TCP Proxy Service. The proxy connects to Gateway's internal gameplay listener at `/ws/game/**` over `wss://` with mutual TLS. Gateway forwards verified TCP origins to Game Session's [dedicated `/ws/game/tcp` mTLS receiver](./system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). [Protocol Bridging](./system-architecture-protocol-bridging.md#websocket-bridge-configuration) describes the Proxy-to-Gateway configuration. ## Management Plane Security diff --git a/design/architecture/system-architecture-security.md b/design/architecture/system-architecture-security.md index 5e272599ca..6688596c1a 100644 --- a/design/architecture/system-architecture-security.md +++ b/design/architecture/system-architecture-security.md @@ -111,7 +111,7 @@ Compromise response revokes or replaces the affected workload certificate, remov ## TLS Termination & Internal Encryption - External client `https://` / `wss://` traffic is terminated at the Internet-facing load balancer. -- The **Spring Cloud Gateway** routes client traffic to backend services over in-cluster `http://` / `ws://` targets. Internal service-to-service traffic (for example, Game Session Service to other microservices) uses **mutual TLS (mTLS)** gRPC. +- The **Spring Cloud Gateway** routes ordinary client traffic to backend services over explicit in-cluster `http://` / `ws://` exceptions. Authenticated TCP LOGIN/lobby/PLAY custody uses the dedicated mTLS WebSocket boundary below. Internal service-to-service traffic (for example, Game Session Service to other microservices) uses **mutual TLS (mTLS)** gRPC. - All internal gRPC calls between microservices use **mutual TLS (mTLS)**: - Certificates are issued by **cert-manager** - Each workload identity receives a distinct private key and certificate in a dedicated Kubernetes Secret; a shared CA bundle is allowed, but application services do not share one private mTLS identity @@ -128,7 +128,7 @@ TLS for player and Telnet flows is applied hop-by-hop so traffic stays protected - **Telnet gameplay path** - Telnet client → public Telnet termination point uses TLS in every player-facing deployment. TLS may terminate at a dedicated Telnet edge proxy (for example HAProxy) or at TCP Proxy Service when `TCP_PROXY_TLS_ENABLED=true` and `TCP_PROXY_TLS_CERT` / `TCP_PROXY_TLS_KEY` are provided. A dedicated edge forwards to TCP Proxy through an authenticated, cryptographically protected internal listener (for example mTLS) using PROXY protocol where client-IP preservation is required. Network restriction and PROXY framing alone do not authenticate the sender; until the edge-to-TCP Proxy channel is authenticated, the recovered address is advisory only and must not drive per-IP throttles, abuse controls, or admission decisions. Raw Telnet remains available only for local development, automated proof, and explicitly private networks; it is not exposed directly to the public Internet or accepted as player-facing production evidence. On the PROXY-protocol listener, malformed or truncated PROXY headers are treated as a hard failure by the proxy: the connection is closed, `tcpproxy.telnet.discarded{reason="proxy_protocol"}` is incremented, and the proxy never silently falls back to using the TCP peer IP. - TCP Proxy Service → Spring Cloud Gateway uses `wss://` with mutual TLS by connecting to a dedicated internal-only Gateway WebSocket mTLS listener (for example a `spring-cloud-gateway-mtls` `ClusterIP` Service on a separate TLS port). The proxy presents a client certificate and key from `FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH` / `FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH`, and validates the gateway certificate against `FIREMUD_GATEWAY_WS_CA_CERT_PATH` with hostname verification enabled using the host from `GATEWAY_WS_URL`. Spring Cloud Gateway promotes `X-Proxy-*` headers only after authenticating this hop via the client certificate identity; see [Gateway Architecture](./system-architecture-gateway.md#tcp-proxy--gateway-authentication). The full Proxy → Gateway WebSocket TLS configuration is summarized in the **TLS Config Matrix** section below. - - Spring Cloud Gateway forwards gameplay to the Game Session Service over the `/ws/game/**` WebSocket route. Game Session Service then communicates with other microservices over mTLS gRPC using the same `FIREMUD_GRPC_*` variables that all services share. + - Spring Cloud Gateway relays authenticated TCP gameplay to Game Session over the dedicated mTLS `/ws/game/tcp` receiver below. The ordinary in-cluster WebSocket exception cannot supply authenticated TCP LOGIN custody. Game Session Service then communicates with other microservices over mTLS gRPC using the same `FIREMUD_GRPC_*` variables that all services share. - For a compact view of all TLS and trust surfaces specific to the TCP Proxy (Telnet plaintext/TLS, WebSocket mTLS to Gateway, and internal gRPC mTLS), see the TCP Proxy Service design’s **TLS & Trust Surfaces (Summary)** section in `design/architecture/microservices/tcp-proxy-service/README.md`. Local Docker Compose environments may use plain `http://` / `ws://` for simplicity. In production Kubernetes, browser TLS terminates at the external load balancer, while player-facing Telnet TLS terminates at either the dedicated Telnet edge proxy or TCP Proxy Service itself; both are Internet-edge termination points for their respective transports. Subsequent Telnet bridge and service hops follow the authenticated `wss://`/mTLS contracts above. @@ -154,11 +154,23 @@ This matrix is the authoritative reference for configuring the Proxy → Gateway --- +### Authenticated TCP Gateway to Game Session Receiving + +The credential-bearing TCP LOGIN/lobby/PLAY receiver is `/ws/game/tcp` on a dedicated internal Game Session TLS connector, separate from the ordinary HTTP port. It requires client certificates and accepts only the exact `spiffe://firemud/ns//sa/spring-cloud-gateway` URI SAN in the receiver's configured namespace, with `clientAuth` usage. Gateway validates the Game Session CA chain, hostname and exact same-namespace `game-session-service` URI SAN before releasing the upgrade request. Game Session reuses its distinct `FIREMUD_GRPC_*` server key, certificate and trust binding. Gateway uses an independently issued client-only workload leaf for this hop, distinct from both its existing management-server bundle and its TCP-Proxy-facing WebSocket server leaf; sharing the legacy generic leaf does not qualify either peer. + +Gateway may relay the TCP-origin address and original proxy connection UUID only from its private proof produced after the selected TCP Proxy mTLS trust policy succeeds. Header strings, public ingress, development CIDR trust and network location cannot produce that proof. Game Session validates the relay on the dedicated authenticated connector, derives the transport session identifier from the verified proxy connection UUID, and refuses an explicit `X-Firemud-Transport-Session-Id` on that hop. It allocates a fresh backend generation and binds it to the exact live WebSocket object. Retained UUIDs, numeric transport IDs, menus and SQL witnesses do not reconstruct that custody. + +The ordinary HTTP/WebSocket connector is not a supported TCP gameplay fallback. Missing or disabled authenticated Gateway upstream or Game Session listener configuration leaves TCP gameplay unavailable; stripping the trusted TCP connection mode to reach an ordinary receiver cannot supply authenticated custody. + +A genuine `InitialGameplayLoginOwner` outcome retains the identical verified private Account result on that connection. Every lobby/entitlement operation borrows that result and exact live transport together; replacement, disconnect, logout and shutdown revoke new use, drain in-flight callbacks, wipe private bytes and attempt exact-original cleanup. A new backend connection never inherits the old LOGIN result. LOGIN and JOIN success do not grant gameplay admission or bypass the canonical World/capacity/final-binding owners. + +Gateway selects the receiver using `firemud.gateway.gameplay.bridge.authenticated-upstream-url`, a `wss://` URL ending exactly in `/ws/game/tcp`. Gateway's dedicated `firemud.gateway.gameplay.bridge.tls.cert-chain`, `.private-key` and `.ca-cert` properties use `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH`, `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH` and `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH` as environment aliases. They never replace its management-server `FIREMUD_GRPC_*` binding. Game Session binds `firemud.gameplay.authenticated-listener.enabled` and `.port` (default `8444`); the port must differ from ordinary HTTP. SSL bundle rotation updates the Game Session connector, and the Gateway uses the existing TLS certificate watcher for new outbound connections. Protected Redis bindings, external reset/restore/promotion exclusion, committed Account issuance/currentness and canonical admission sources remain independently required. A configured URI or mounted file is not their qualification. Current receiving and proof limits belong to the [player access tracker](../project-management/implementation-tracking/player-access-and-session.md). + ## Cross-Service Trust - Exact-profile JWT validation uses the Account Service’s JWKS endpoint; backend delegation uses the receiver-specific private player-delegation profile for that route. -- Internal service-to-service **gRPC** traffic is authenticated using **mTLS** with cert-manager-issued certificates. The documented Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions and retain their existing Gateway trust, header-canonicalization, and NetworkPolicy controls. Current implementation drift is that Gateway REST listens with the default plaintext HTTP configuration and forwards credential-bearing requests (including `Authorization`) over in-cluster `http://` routes; this is not target HTTPS/mTLS or traffic-open/promotion proof. The target Gateway management plane uses HTTPS with its dedicated operator mTLS binding, while any remaining in-cluster HTTP exception must stay explicitly bounded and non-authorizing by itself. -- Peer-level trust is enforced via **Kubernetes NetworkPolicies**, which restrict ingress and egress paths between services. +- Internal service-to-service **gRPC** traffic is authenticated using **mTLS** with cert-manager-issued certificates. The documented ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions and retain their existing Gateway trust, header-canonicalization, and NetworkPolicy controls. Authenticated TCP LOGIN/lobby/PLAY receiving is excluded from that exception and requires the [dedicated mTLS WebSocket boundary](#authenticated-tcp-gateway-to-game-session-receiving). Current implementation drift is that Gateway REST listens with the default plaintext HTTP configuration and forwards credential-bearing requests (including `Authorization`) over in-cluster `http://` routes; this is not target HTTPS/mTLS or traffic-open/promotion proof. The target Gateway management plane uses HTTPS with its dedicated operator mTLS binding, while any remaining in-cluster HTTP exception must stay explicitly bounded and non-authorizing by itself. +- **Kubernetes NetworkPolicies** restrict ingress and egress reachability. Authenticated workload trust comes from the verified mTLS peer identity; network location and forwarded headers alone do not establish authority. --- 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 5ff84ebab3..649e872d33 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -446,10 +446,24 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -Account's private gameplay LOGIN implementation is source-only and remains unregistered: issuance, signing, registry, disposal, and Game Session cleanup sources are not composed into the production runtime. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). +Account's private gameplay LOGIN has fail-closed dispatch through the existing Account gRPC registration, but its issuer, response-recovery, registry, evidence-repository, trusted-JWKS and disposal graph remains unregistered. Canonical envelopes and exact-original retirement are unavailable without an independently supplied receiver and never select legacy credential fallback. The protected-source and runtime composition, including its configuration and focused proof, belongs to the successor source-composition boundary in [#3409](https://github.com/benhook1013/FireMUD/pull/3409). Game Session's protected Coordination binding, LOGIN/lobby runtime graph, external maintenance qualification and trusted Account verifier remain absent here; the authenticated receiver fails closed without them. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). Canonical disposal and original-attempt rules belong to [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), the [Redis initial-context acknowledgement owner](../../architecture/system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy), and [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). Protected binding-history/restore qualification, production trust and custody, and runtime activation remain gaps; source fixtures do not establish authenticated intake or playable LOGIN. +The unregistered [initial LOGIN owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) now pins the identical retained private result through each owned callback and drains existing borrows before transfer or custody-loss cleanup, without holding owner/result monitors across callbacks or SQL/Redis/Account work. Direct result closure also drains pins before erasure; reentrant lifecycle changes are refused and exact-original cleanup remains retryable after `HELD`. Focused owner/result units exercise identity, failure release, transfer, closure and concurrent draining. Three prepared additions to [physical LOGIN-context proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java) compose actual installed LOGIN bytes with retained non-admitting lobby storage and the SQL-row-to-result ordering. Physical execution is unrun locally because Docker is unavailable; controlled Account/transport/routing fixtures do not establish authenticated ingress association, backend-generation binding, reset qualification, registration, admission, activation or canonical PLAY Smoke readiness. + +### Authenticated TCP LOGIN receiving preparation + +The Gateway retains a process-private TCP-origin proof only after authenticating its selected TCP Proxy peer. Its dedicated client uses the existing file-backed workload TLS configuration, checks its own same-namespace Gateway identity, and verifies the exact same-namespace Game Session peer before releasing the WebSocket upgrade or relayed origin headers. Game Session receives that hop only on the separate client-certificate-required TLS connector and `/ws/game/tcp` path. Header strings on ordinary HTTP cannot produce authenticated transport custody. The canonical exception change belongs to [Cross-Service Trust](../../architecture/system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). + +The exact live backend socket/generation owns the genuine `InitialGameplayLoginOwner.Outcome`; lobby operations borrow its identical private result inside synchronous custody callbacks. Disconnect, replacement and shutdown revoke the old generation before draining and exact-original cleanup. Reconnection cannot reconstruct LOGIN from correlation IDs or retained SQL. WORLDS/REALMS/JOIN use the existing non-admitting lobby owners. The receiver refuses PLAY rather than invoking the retired numeric subscription-entitlement path. A complete canonical final admission/binding composition is still required. + +The checked-in local Compose, base and Kustomize configurations do not enable the authenticated listener/upstream pair, so their ordinary TCP gameplay path fails closed under the [receiving contract](../../architecture/system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). Hosted shared values select the authenticated path, but the genuine `InitialGameplayLoginOwner` remains unregistered here: protected hosted LOGIN returns `UNAVAILABLE`, and PLAY remains intentionally denied even after a qualified LOGIN. This preparation does not enable the required public LOGIN/PLAY/LOOK smoke, hosted deployment success or branch-image publication; the separate direct-backend diagnostic exception above does not prove this protected path. + +The latest completed focused gate passes 54 Gateway and 94 Game Session cases with zero failures, errors or skips, including actual mutual-TLS WebSocket upgrade, wrong-workload/namespace refusal before HTTP origin headers, exact-result custody, overlapping replacement drain, shutdown revocation and friendly JOIN wire routing. These cases use controlled upstream Account/result sources and are not genuine end-to-end Account issuance or public LOGIN-to-PLAY proof. The first Account dispatch run preserved 144 passing cases and four failed reject-before-payload assertions. After moving canonical selector dispatch behind the existing peer guard, the exact 148-case Account suite passes with zero failures, errors or skips. The physical Tomcat connector case requires client TLS, accepts only the exact Gateway namespace/workload, denies forged headers over public HTTP and limits the dedicated listener to the gameplay path. + +Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The earlier complete source-composition graph has separately recorded Account and Game Session main/unit static proof in the successor; that historical result does not qualify this narrower patch boundary. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client and runtime composition is retained in the successor; deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. + ### Account signer/currentness storage evidence preparation Account V99–V125 and the associated owner repositories, typed evidence carriers, mounted-bundle signer source, and validator-profile sources form a passive storage/evidence preparation only. The selected RPCs, coordinators, transport composition, provisioning, receiver execution, runtime registration, and consumer enforcement are not included or activated. The earlier local result of 727 Account and 154 Common Security cases is historical. The later local Account result is 738 cases with one skip; integration sources compiled, while local integration execution skipped 99 of 101 definitions without Docker. Exact-head hosted Account integration task 114264913703 passed on `607004fe786b2a9e1270a31c90f9031b486b3278` and is historical; its retained evidence does not expose per-suite case or skip counts. The later exact-head result at `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` is also historical: hosted Account task 114304559873, Validation 38083268673, and artifact 11681094163 recorded physical PostgreSQL 18.6 readiness storage proof with 1 case, 70.952 seconds, and 0 skipped, including lawful expired-dispatch recovery. At `e63729562c39e664513bad2be2222e11a6886388`, the required Validation and Smoke checks passed. Hosted Account run 38088195334, task 114319172067, and artifact 11683606431 tested merge commit `05304721b3e705925b4344280a98a65c094f8823`, with parents `75e92718a983ac134cbb75fafbf173ac6b0360e0` and `e63729562c39e664513bad2be2222e11a6886388`, using immutable PostgreSQL 18.6 image `sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336`; the readiness and inventory suites each passed 2 of 2 cases with zero skips or failures. This is bounded storage proof with synthetic inventory/resource inputs, not evidence of live Kubernetes currentness, readiness activation, or signer activation. The AA-1.3 capability remains `partial` / `drift-found`; this subsection updates its passive anchors and proof limits without changing that state or closing a gate. Other capability rows and prior gates remain unchanged. Runtime readiness is not claimed. This preparation does not establish an issuer/currentness path or close `PLAY`, admission, or playable readiness; the canonical design remains [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). @@ -585,7 +599,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.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); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.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` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. 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 retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [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); [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); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [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); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `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); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. 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 shared subscription-version/billing-sequence projection 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. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing 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. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `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) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.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); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. 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` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing 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. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. 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. 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); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [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); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.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 [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/dev-tools/deploy/preflight.py b/dev-tools/deploy/preflight.py index 551b0a0538..ba347469a3 100644 --- a/dev-tools/deploy/preflight.py +++ b/dev-tools/deploy/preflight.py @@ -155,7 +155,8 @@ def _hosted_bridge_secret_ready_attempts_for_timeout(timeout_seconds: int) -> in "social-groups-service", *ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, ) -GRPC_WORKLOAD_SECRET_CONSUMERS = SHARED_TRUST_GRPC_WORKLOADS +GATEWAY_CLIENT_WORKLOADS = ("spring-cloud-gateway",) +GRPC_WORKLOAD_SECRET_CONSUMERS = (*SHARED_TRUST_GRPC_WORKLOADS, *GATEWAY_CLIENT_WORKLOADS) GRPC_WORKLOAD_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} PUBLICATION_GRPC_TRUST_SECRET_NAME = "firemud-grpc-tls" PUBLICATION_GRPC_TRUST_SECRET_KEYS = {"ca.crt"} @@ -974,9 +975,25 @@ def publication_workload_secret_requirements( requirements: list[tuple[str, str, set[str]]] = [] leaf_secret_names: list[str] = [] for workload in GRPC_WORKLOAD_SECRET_CONSUMERS: + client_only = workload in GATEWAY_CLIENT_WORKLOADS + leaf_volume_name = "gameplay-client-tls" if client_only else "grpc-tls" + trust_volume_name = "gameplay-client-trust" if client_only else "grpc-trust" + leaf_root = "/gameplay-client-tls" if client_only else "/tls" + trust_root = "/gameplay-client-trust" if client_only else "/grpc-trust" + path_names = ( + ( + "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH", + "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH", + "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH", + ) + if client_only + else GRPC_TLS_PATH_NAMES + ) is_publication_workload = workload in PUBLICATION_GRPC_WORKLOADS workload_label = ( - "publication workload" if is_publication_workload else "gRPC workload" + "Gateway gameplay client" + if client_only + else "publication workload" if is_publication_workload else "gRPC workload" ) deployments = [ document @@ -1010,20 +1027,20 @@ def publication_workload_secret_requirements( grpc_volumes = [ volume for volume in volumes - if isinstance(volume, dict) and volume.get("name") == "grpc-tls" + if isinstance(volume, dict) and volume.get("name") == leaf_volume_name ] trust_volumes = [ volume for volume in volumes - if isinstance(volume, dict) and volume.get("name") == "grpc-trust" + if isinstance(volume, dict) and volume.get("name") == trust_volume_name ] if len(grpc_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-tls volume for {workload_label} {workload}; found {len(grpc_volumes)}" + f"Expected exactly one {leaf_volume_name} volume for {workload_label} {workload}; found {len(grpc_volumes)}" ) if len(trust_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-trust volume for {workload_label} {workload}; found {len(trust_volumes)}" + f"Expected exactly one {trust_volume_name} volume for {workload_label} {workload}; found {len(trust_volumes)}" ) grpc_volume = grpc_volumes[0] secret = grpc_volume.get("secret") @@ -1057,22 +1074,22 @@ def publication_workload_secret_requirements( or not leaf_projection_is_valid ): raise ValueError( - f"Rendered {workload_label} {workload} has a malformed grpc-tls Secret volume" + f"Rendered {workload_label} {workload} has a malformed {leaf_volume_name} Secret volume" ) if secret_name == workload_mtls_secret_name: raise ValueError( - f"Rendered {workload_label} {workload} grpc-tls Secret must be distinct from " + f"Rendered {workload_label} {workload} {leaf_volume_name} Secret must be distinct from " f"the workload mTLS Secret {workload_mtls_secret_name}" ) if secret_name == PUBLICATION_GRPC_TRUST_SECRET_NAME: raise ValueError( - f"Rendered {workload_label} {workload} grpc-tls Secret must not use the " + f"Rendered {workload_label} {workload} {leaf_volume_name} Secret must not use the " "shared trust Secret firemud-grpc-tls" ) expected_leaf_secret_name = f"firemud-grpc-{workload}" if secret_name != expected_leaf_secret_name: raise ValueError( - f"Rendered {workload_label} {workload} grpc-tls Secret must be " + f"Rendered {workload_label} {workload} {leaf_volume_name} Secret must be " f"{expected_leaf_secret_name}; found {secret_name}" ) @@ -1106,7 +1123,7 @@ def publication_workload_secret_requirements( ): raise ValueError( f"Rendered {workload_label} {workload} requires the shared CA-only " - f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" + f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its {trust_volume_name} volume" ) containers = pod_spec.get("containers") @@ -1130,7 +1147,7 @@ def publication_workload_secret_requirements( documents, deployment, container, - relevant_names=set(GRPC_TLS_PATH_NAMES), + relevant_names=set(path_names), ) if env_issues: raise ValueError( @@ -1143,6 +1160,35 @@ def publication_workload_secret_requirements( raise TypeError( f"Rendered {workload_label} {workload} has no valid container env list" ) + if client_only: + namespace_entries = [ + entry + for entry in container_env + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" + ] + if namespace_entries != [{ + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }]: + raise ValueError( + "Gateway gameplay client must bind its workload namespace to metadata.namespace" + ) + management_paths = { + "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", + "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", + "FIREMUD_GRPC_CA_CERT_PATH": "/tls/ca.crt", + } + for name, path in management_paths.items(): + entries = [ + entry + for entry in container_env + if isinstance(entry, dict) and entry.get("name") == name + ] + if entries != [{"name": name, "value": path}]: + raise ValueError( + f"Gateway must preserve management gRPC path {name} as {path}" + ) declared_grpc_path_names: list[str] = [] for entry in container_env: if not isinstance(entry, dict): @@ -1150,7 +1196,7 @@ def publication_workload_secret_requirements( f"Rendered {workload_label} {workload} has a malformed container env entry" ) name = entry.get("name") - if name not in GRPC_TLS_PATH_NAMES: + if name not in path_names: continue declared_grpc_path_names.append(name) if not set(entry).issubset({"name", "value", "valueFrom"}): @@ -1176,13 +1222,11 @@ def publication_workload_secret_requirements( f"Rendered {workload_label} {workload} has ambiguous gRPC TLS path env entries" ) - expected_grpc_paths = { - "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/tls.crt", - "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", - "FIREMUD_GRPC_CA_CERT_PATH": "/grpc-trust/ca.crt", - } + expected_grpc_paths = dict( + zip(path_names, (f"{leaf_root}/tls.crt", f"{leaf_root}/tls.key", f"{trust_root}/ca.crt")) + ) grpc_paths: dict[str, str] = {} - for name in GRPC_TLS_PATH_NAMES: + for name in path_names: path = environment.get(name) if ( not isinstance(path, str) @@ -1221,8 +1265,8 @@ def publication_workload_secret_requirements( ) expected_mounts = { - "grpc-tls": "/tls", - "grpc-trust": "/grpc-trust", + leaf_volume_name: leaf_root, + trust_volume_name: trust_root, } validated_mounts: dict[str, dict[str, Any]] = {} for volume_name, mount_path in expected_mounts.items(): @@ -1244,13 +1288,13 @@ def publication_workload_secret_requirements( validated_mounts[volume_name] = mount if any( - not path_is_under_mount(path, "/tls") + not path_is_under_mount(path, leaf_root) for path in ( - grpc_paths["FIREMUD_GRPC_CERT_CHAIN_PATH"], - grpc_paths["FIREMUD_GRPC_PRIVATE_KEY_PATH"], + grpc_paths[path_names[0]], + grpc_paths[path_names[1]], ) ) or not path_is_under_mount( - grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], "/grpc-trust" + grpc_paths[path_names[2]], trust_root ): raise ValueError( f"Rendered {workload_label} {workload} gRPC TLS paths do not match its leaf/trust mount layout" diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index f9c762ad36..dbca5d270f 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -68,7 +68,8 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: DISTINCT_GRPC_WORKLOADS = ( PUBLICATION_GRPC_WORKLOADS | ACCOUNT_GRPC_WORKLOADS | GAME_SESSION_GRPC_WORKLOADS | SOCIAL_GROUPS_GRPC_WORKLOADS ) -NAMESPACE_BOUND_GRPC_WORKLOADS = DISTINCT_GRPC_WORKLOADS | {"logging-admin-service"} +GATEWAY_CLIENT_WORKLOADS = {"spring-cloud-gateway"} +NAMESPACE_BOUND_GRPC_WORKLOADS = DISTINCT_GRPC_WORKLOADS | GATEWAY_CLIENT_WORKLOADS | {"logging-admin-service"} EXPECTED_NAMES = { "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, "Service": SERVICE_IMAGES | {"spring-cloud-gateway-mtls", "postgres", "redis-coord", "redis-cache", "minio"}, @@ -84,6 +85,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "social-groups-service-controller-ingress", "spring-cloud-gateway-ingress", "spring-cloud-gateway-egress", + "game-session-authenticated-gameplay-ingress", "tcp-proxy-service-egress", }, } @@ -157,7 +159,7 @@ def _trusted_database_images(values_path: Path) -> dict[str, str]: "minio-credentials", "firemud-grpc-tls", } -DISTINCT_GRPC_SECRET_OWNERS = {f"firemud-grpc-{service}": service for service in DISTINCT_GRPC_WORKLOADS} +DISTINCT_GRPC_SECRET_OWNERS = {f"firemud-grpc-{service}": service for service in DISTINCT_GRPC_WORKLOADS | GATEWAY_CLIENT_WORKLOADS} CANONICAL_INGRESS_ISSUER = "letsencrypt-prod" ALLOCATED_TELNET_PORT_ANNOTATION = "firemud.dev/allocated-telnet-port" CERTIFICATE_IDENTITY_MODES = {"standalone", "hosted-controller"} @@ -280,8 +282,12 @@ def _application_service_spec( service, (("tcp-8080", 8080, 8080), ("tcp-6565", 6565, 6565)), ) - for service in SERVICE_IMAGES - {"spring-cloud-gateway", "tcp-proxy-service"} + for service in SERVICE_IMAGES - {"spring-cloud-gateway", "tcp-proxy-service", "game-session-service"} }, + "game-session-service": _application_service_spec( + "game-session-service", + (("tcp-8080", 8080, 8080), ("tcp-6565", 6565, 6565), ("tcp-8444", 8444, 8444)), + ), "spring-cloud-gateway": _application_service_spec( "spring-cloud-gateway", (("tcp-80", 80, 8080), ("tcp-6565", 6565, 6565)), @@ -593,6 +599,14 @@ def _infrastructure_deployment_spec( }, ] EXPECTED_INTERNAL_NETWORK_POLICY_SPECS = { + "game-session-authenticated-gameplay-ingress": { + "podSelector": {"matchLabels": {"app": "game-session-service"}}, + "policyTypes": ["Ingress"], + "ingress": [{ + "from": [{"podSelector": {"matchLabels": {"app": "spring-cloud-gateway"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }], + }, "internal-services": { "podSelector": INTERNAL_SERVICES_SELECTOR, "policyTypes": ["Ingress", "Egress"], @@ -627,6 +641,10 @@ def _infrastructure_deployment_spec( {"protocol": "TCP", "port": 53}, ], }, + { + "to": [{"podSelector": {"matchLabels": {"app": "game-session-service"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }, { "to": [ { @@ -816,7 +834,8 @@ def _is_distinct_grpc_secret_volume_source(document: object, path: str, value: o if not isinstance(volume, dict): return False source = volume.get("secret") - return volume.get("name") == "grpc-tls" and isinstance(source, dict) and source.get("secretName") == value + expected_volume_name = "gameplay-client-tls" if owner in GATEWAY_CLIENT_WORKLOADS else "grpc-tls" + return volume.get("name") == expected_volume_name and isinstance(source, dict) and source.get("secretName") == value def _is_manifest_secret_reference(value: object, expected_namespace: str) -> bool: @@ -855,16 +874,27 @@ def _validate_image_reference( fail(f"{location} uses an unapproved image") -def _expected_gateway_container_env(expected_namespace: str) -> list[dict[str, str]]: +def _expected_gateway_container_env(expected_namespace: str) -> list[dict]: if re.fullmatch(r"pr-[1-9][0-9]{0,50}", expected_namespace) is None: fail(f"runtime namespace is not canonical: {expected_namespace!r}") return [ {"name": "SPRING_PROFILES_ACTIVE", "value": "prod"}, {"name": "SPRING_FLYWAY_TABLE", "value": "flyway_schema_history_gateway"}, {"name": "SERVICE_SCHEMA", "value": "gateway"}, + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }, {"name": "FIREMUD_GRPC_CERT_CHAIN_PATH", "value": "/tls/client.crt"}, {"name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", "value": "/tls/client.key"}, {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH", "value": "/gameplay-client-tls/tls.crt"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH", "value": "/gameplay-client-tls/tls.key"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH", "value": "/gameplay-client-trust/ca.crt"}, + { + "name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL", + "value": "wss://game-session-service.$(FIREMUD_GRPC_WORKLOAD_NAMESPACE).svc.cluster.local:8444/ws/game/tcp", + }, {"name": "FIREMUD_GATEWAY_TCP_PROXY_TLS_ENABLED", "value": "true"}, {"name": "FIREMUD_GATEWAY_TCP_PROXY_TLS_BIND_ADDRESS", "value": "0.0.0.0"}, {"name": "FIREMUD_GATEWAY_TCP_PROXY_TLS_PORT", "value": "8443"}, @@ -1526,6 +1556,8 @@ def validate_service_consumers( f"{expected_namespace}-tcp-proxy-bridge", ) if service == "spring-cloud-gateway": + expected_mounts["gameplay-client-tls"] = ("/gameplay-client-tls", "firemud-grpc-spring-cloud-gateway") + expected_mounts["gameplay-client-trust"] = ("/gameplay-client-trust", "firemud-grpc-tls") expected_mounts["gateway-ws-server-tls"] = ( "/gateway-ws-server-tls", f"{expected_namespace}-gateway-internal-ws", @@ -1548,7 +1580,7 @@ def validate_service_consumers( mount = mounts[volume_name] if mount.get("mountPath") != mount_path or mount.get("readOnly") is not True: fail(f"Deployment/{service} has an unsafe {volume_name} mount") - if volume_name in {"gateway-ws-server-tls", "gateway-ws-client-tls"} and mount != { + if volume_name in {"gateway-ws-server-tls", "gateway-ws-client-tls", "gameplay-client-tls", "gameplay-client-trust"} and mount != { "name": volume_name, "mountPath": mount_path, "readOnly": True, @@ -1575,14 +1607,14 @@ def validate_service_consumers( ): fail(f"Deployment/{service} distinct workload falls back to shared firemud-grpc-tls") fail(f"Deployment/{service} has an unexpected {volume_name} source") - if volume_name == "grpc-trust": + if volume_name in {"grpc-trust", "gameplay-client-trust"}: expected_source = { "secretName": source_name, "items": [{"key": "ca.crt", "path": "ca.crt"}], } if source != expected_source: fail(f"Deployment/{service} has an unsafe grpc-trust projection") - if volume_name == "grpc-tls" and service in DISTINCT_GRPC_WORKLOADS: + if (volume_name == "grpc-tls" and service in DISTINCT_GRPC_WORKLOADS) or volume_name == "gameplay-client-tls": expected_source = { "secretName": source_name, "items": [ diff --git a/dev-tools/hosted/preview/wait-for-hosted-identity.sh b/dev-tools/hosted/preview/wait-for-hosted-identity.sh index 268f892dd2..c872d2e469 100644 --- a/dev-tools/hosted/preview/wait-for-hosted-identity.sh +++ b/dev-tools/hosted/preview/wait-for-hosted-identity.sh @@ -154,6 +154,7 @@ if [[ "${1:-}" == "--projections" ]]; then "firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt" "firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt" "firemud-grpc-social-groups-service|grpc-social-groups-service|tls.crt,tls.key,ca.crt" + "firemud-grpc-spring-cloud-gateway|grpc-spring-cloud-gateway|tls.crt,tls.key,ca.crt" ) initialize_wait_state "$timeout_seconds" all_projections_ready=true diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index 399c3fc851..7e8b055dd0 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -51,6 +51,7 @@ workloads=( account-service game-session-service social-groups-service + spring-cloud-gateway ) secret_exists() { @@ -214,22 +215,35 @@ validate_workload_certificate() { exit } ' | tr -d '[:space:]')" - [[ "$extended_key_usage" == 'TLSWebServerAuthentication,TLSWebClientAuthentication' ]] || { - echo "workload certificate EKU must be exactly serverAuth/clientAuth: $certificate" >&2 + local expected_extended_key_usage='TLSWebServerAuthentication,TLSWebClientAuthentication' + local expected_eku_description='serverAuth/clientAuth' + if [[ "$workload" == spring-cloud-gateway ]]; then + expected_extended_key_usage='TLSWebClientAuthentication' + expected_eku_description='clientAuth' + fi + [[ "$extended_key_usage" == "$expected_extended_key_usage" ]] || { + echo "workload certificate EKU must be exactly ${expected_eku_description}: $certificate" >&2 return 1 } if ! san_values="$(openssl x509 -in "$certificate" -noout -ext subjectAltName | awk 'NR > 1 { print }' | tr ',' '\n' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"; then echo "workload certificate SANs could not be read: $certificate" >&2 return 1 fi - [[ "$(printf '%s\n' "$san_values" | sed '/^$/d' | wc -l)" -eq 5 ]] || { - echo "workload certificate must contain exactly one URI SAN and four DNS SANs: $certificate" >&2 + local expected_san_count=5 + if [[ "$workload" == spring-cloud-gateway ]]; then + expected_san_count=1 + fi + [[ "$(printf '%s\n' "$san_values" | sed '/^$/d' | wc -l)" -eq "$expected_san_count" ]] || { + echo "workload certificate must contain exactly ${expected_san_count} authorized SANs: $certificate" >&2 return 1 } printf '%s\n' "$san_values" | grep -Fx "URI:${expected_uri}" >/dev/null || { echo "workload certificate has the wrong URI SAN: $certificate" >&2 return 1 } + if [[ "$workload" == spring-cloud-gateway ]]; then + return 0 + fi for expected_dns in \ "$workload" \ "${workload}.${namespace}" \ diff --git a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh index dc56d74a5c..e4c0bec1e9 100644 --- a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh +++ b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh @@ -31,6 +31,7 @@ workloads=( account-service game-session-service social-groups-service + spring-cloud-gateway ) write_certificates() { @@ -53,17 +54,27 @@ spec: rotationPolicy: Always isCA: false revisionHistoryLimit: 1 +EOF + if [[ "$workload" != spring-cloud-gateway ]]; then + cat <"$fixture_dir/$workload.ext" <&2 exit 1 fi -grep -Fq '8 distinct workload leaves' "$fixture_dir/success.out" || { - echo "the helper did not accept eight valid cert-manager projections" >&2 +grep -Fq '9 distinct workload leaves' "$fixture_dir/success.out" || { + echo "the helper did not accept nine valid cert-manager projections" >&2 exit 1 } large_constraints_log="$fixture_dir/large-constraints.log" @@ -302,7 +309,7 @@ if ! FORCE_LARGE_BASIC_CONSTRAINTS_OUTPUT=true run_helper complete "$large_const echo "the helper failed to validate a CA extension after capturing its complete output" >&2 exit 1 fi -grep -Fq '8 distinct workload leaves' "$fixture_dir/large-constraints.out" || { +grep -Fq '9 distinct workload leaves' "$fixture_dir/large-constraints.out" || { echo "the helper did not accept valid CA constraints with large extension output" >&2 exit 1 } @@ -323,7 +330,7 @@ for secret in firemud-grpc-tls "${workloads[@]/#/firemud-grpc-}"; do exit 1 } done -last_projection_line="$(grep -n '^snapshot dev/firemud-grpc-social-groups-service fields=tls.crt,tls.key,ca.crt$' "$success_log" | tail -n 1 | cut -d: -f1)" +last_projection_line="$(grep -n '^snapshot dev/firemud-grpc-spring-cloud-gateway fields=tls.crt,tls.key,ca.crt$' "$success_log" | tail -n 1 | cut -d: -f1)" reapply_line="$(grep -n '^apply dev/firemud-grpc-tls$' "$success_log" | cut -d: -f1)" legacy_delete_line="$(grep -n '^delete dev/firemud-grpc-ca$' "$success_log" | cut -d: -f1)" [[ -n "$last_projection_line" && -n "$reapply_line" && -n "$legacy_delete_line" && \ @@ -341,7 +348,7 @@ if ! run_helper complete "$warning_lookup_log" "$fixture_dir/warning-lookup-stat cat "$fixture_dir/warning-lookup.out" "$fixture_dir/warning-lookup.err" >&2 exit 1 fi -grep -Fq '8 distinct workload leaves' "$fixture_dir/warning-lookup.out" || { +grep -Fq '9 distinct workload leaves' "$fixture_dir/warning-lookup.out" || { echo "a warning on an absent Secret was treated as an existing Secret" >&2 exit 1 } @@ -379,6 +386,40 @@ for resource in \ } done +# A Gateway credential must never acquire serving authority or DNS aliases. +cp "$data_dir/spring-cloud-gateway.crt" "$fixture_dir/gateway-good.crt" +for invalid_gateway_profile in serving dns; do + if [[ "$invalid_gateway_profile" == serving ]]; then + bad_eku='serverAuth,clientAuth' + bad_sans='URI:spiffe://firemud/ns/dev/sa/spring-cloud-gateway' + else + bad_eku=clientAuth + bad_sans='URI:spiffe://firemud/ns/dev/sa/spring-cloud-gateway,DNS:spring-cloud-gateway' + fi + cat >"$fixture_dir/gateway-invalid.ext" <"$fixture_dir/gateway-$invalid_gateway_profile.out" 2>"$fixture_dir/gateway-$invalid_gateway_profile.err"; then + echo "the helper accepted Gateway $invalid_gateway_profile authority" >&2 + exit 1 + fi + if grep -q '^delete ' "$fixture_dir/gateway-$invalid_gateway_profile.log"; then + echo "the helper removed retained material before rejecting Gateway $invalid_gateway_profile authority" >&2 + exit 1 + fi +done +cp "$fixture_dir/gateway-good.crt" "$data_dir/spring-cloud-gateway.crt" + # A failed lookup must retain its diagnostic and remove the temporary stderr # capture along with the helper's certificate workspace. failed_lookup_cert_parent="$fixture_dir/failed-lookup-certs" @@ -479,7 +520,7 @@ if grep -q '^delete ' "$incomplete_log"; then fi # Each workload projection becomes ready on its second read, one simulated -# second later. The helper must apply one timeout to all eight workloads rather +# second later. The helper must apply one timeout to all nine workloads rather # than resetting a fresh timeout for every workload. aggregate_timeout_log="$fixture_dir/aggregate-timeout.log" if run_helper delayed-each-workload "$aggregate_timeout_log" \ diff --git a/dev-tools/tests/hosted-gateway-bridge-contract.sh b/dev-tools/tests/hosted-gateway-bridge-contract.sh index 643b7a6b09..2cc9febab7 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -244,6 +244,23 @@ gateway_deployment = named("Deployment", "spring-cloud-gateway") proxy_deployment = named("Deployment", "tcp-proxy-service") gateway, gateway_env = env_map(gateway_deployment) proxy, proxy_env = env_map(proxy_deployment) +_, session_env = env_map(named("Deployment", "game-session-service")) +if session_env.get("FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED") != "true" or session_env.get("FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT") != "8444": + raise SystemExit("Game Session must enable its dedicated authenticated gameplay listener on 8444") +if gateway_env.get("FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL") != "wss://game-session-service.$(FIREMUD_GRPC_WORKLOAD_NAMESPACE).svc.cluster.local:8444/ws/game/tcp": + raise SystemExit("Gateway must route authenticated TCP provenance only over the dedicated Game Session mTLS path") +session_ports = named("Service", "game-session-service")["spec"]["ports"] +if {"port": 8444, "name": "tcp-8444", "targetPort": 8444, "protocol": "TCP"} not in session_ports: + raise SystemExit("Game Session Service must expose the dedicated 8444 mTLS connector") +if named("NetworkPolicy", "game-session-authenticated-gameplay-ingress")["spec"] != { + "podSelector": {"matchLabels": {"app": "game-session-service"}}, + "policyTypes": ["Ingress"], + "ingress": [{ + "from": [{"podSelector": {"matchLabels": {"app": "spring-cloud-gateway"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }], +}: + raise SystemExit("Dedicated Game Session gameplay ingress must be limited to Gateway pods") if proxy_deployment["spec"].get("strategy") != {"type": "Recreate"}: raise SystemExit("preview TCP Proxy Deployment must use the Recreate strategy") postgres_deployment = named("Deployment", "postgres") @@ -508,6 +525,10 @@ if gateway_egress_policy != { {"protocol": "TCP", "port": 53}, ], }, + { + "to": [{"podSelector": {"matchLabels": {"app": "game-session-service"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }, { "to": [{ "podSelector": { @@ -537,7 +558,7 @@ if gateway_egress_policy != { ], }: raise SystemExit( - "Gateway egress policy must allow only DNS, canonical HTTP routes, Redis cache, and OTEL" + "Gateway egress policy must allow only DNS, authenticated gameplay TLS, canonical HTTP routes, Redis cache, and OTEL" ) proxy_policy = named("NetworkPolicy", "tcp-proxy-service-egress")["spec"] proxy_gateway_rules = [ diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 52b6daf14b..82c607da96 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -377,7 +377,7 @@ require_literal "$CRD" "self.desiredState == oldSelf.desiredState || (oldSelf.de forbid_literal "$CRD" "self.metadata.namespace == 'firemud-system'" forbid_literal "$CRD" "x-kubernetes-preserve-unknown-fields" require_literal "$CRD" "self.metadata.name.matches('^(dev-demo|pr-[1-9][0-9]{0,50})$')" -for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcSocialGroupsService grpcPublication; do +for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcSocialGroupsService grpcGatewayClient grpcPublication; do require_literal "$CRD" "$field" done require_literal "$APPLICATION_CONFIG" "dev-demo-requested-head-annotation: firemud.dev/requested-dev-demo-head-sha" @@ -396,7 +396,7 @@ import yaml source = Path(os.environ["CRD"]).read_text(encoding="utf-8") assert source.count("&consumer_status_schema") == 1 -assert source.count("*consumer_status_schema") == 8 +assert source.count("*consumer_status_schema") == 9 crd = yaml.safe_load(source) schema = crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"] assert crd["spec"].get("preserveUnknownFields", False) is False @@ -461,6 +461,7 @@ assert all(value == consumer_schemas[0] for value in consumer_schemas[1:]) assert consumer_properties["grpcAccountService"] == consumer_schemas[0] assert consumer_properties["grpcGameSessionService"] == consumer_schemas[0] assert consumer_properties["grpcSocialGroupsService"] == consumer_schemas[0] +assert consumer_properties["grpcGatewayClient"] == consumer_schemas[0] publication_roles = consumer_properties["grpcPublication"] assert publication_roles["type"] == "object" assert publication_roles["maxProperties"] == 5 @@ -659,7 +660,7 @@ assert set(binding_policy_names) == policy_names identity_namespace_fragment = "pr-[1-9][0-9]{0,50}-identity" grpc_workload_service_regex_group = ( "(game-design-service|world-management-service|entity-management-service|" - "game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)" + "game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)" ) admission_variable_contracts = { "firemud-hosted-identity-secret-boundary": { @@ -1387,10 +1388,10 @@ assert "request.operation != 'DELETE'" in secret_match assert "oldObject.metadata.name == 'firemud-grpc-tls'" in secret_match assert "object.metadata.name == 'firemud-grpc-tls'" in secret_match for publication_secret_pattern in ( - "oldObject.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$')", - "object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$')", - "oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')", - "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')", + "oldObject.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$')", + "object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$')", + "oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$')", + "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$')", ): assert publication_secret_pattern in normalized_secret_match @@ -1448,6 +1449,7 @@ def canonical_primary_name(namespace, name): "grpc-account-service", "grpc-game-session-service", "grpc-social-groups-service", + "grpc-spring-cloud-gateway", } @@ -1461,7 +1463,7 @@ def namespace_controller_secret_delete_is_allowed(namespace, name, username=name if name in {"firemud-grpc-tls", "firemud-grpc-tls-previous"}: return True fixed_workload_secret = re.fullmatch( - r"firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)(-previous)?", + r"firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)(-previous)?", name, ) return bool(fixed_workload_secret) or canonical_primary_name(namespace, name.removesuffix("-previous")) @@ -1629,7 +1631,7 @@ assert "firemud-grpc-tls" not in controller_delete_expression assert "oldObject.metadata.name.startsWith(" in controller_delete_expression assert "(request.operation != 'DELETE' && has(object.metadata.labels)" in certificate_match assert "object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9))" in certificate_match -assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service']" in certificate_match +assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway']" in certificate_match assert "grpc-publication-" in certificate_match assert "grpc-account-service" in certificate_match assert "grpc-game-session-service" in certificate_match @@ -1696,7 +1698,7 @@ assert "object.spec.issuerRef.group == 'cert-manager.io'" in profile_expression internal_issuer_profile = ( "((object.metadata.labels['firemud.dev/role'] in " "['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', " - "'grpc-game-session-service', 'grpc-social-groups-service'] || " + "'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway'] || " "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && " "object.spec.issuerRef.name == 'firemud-ca-issuer')" ) @@ -1746,6 +1748,17 @@ for role, service in ( "object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))" ) assert service_profile in normalized_profile_expression +gateway_client_profile = ( + "(object.metadata.labels['firemud.dev/role'] != 'grpc-spring-cloud-gateway' || " + f"(object.metadata.name == {namespace_service} + '-grpc-spring-cloud-gateway' && " + "object.spec.secretName == object.metadata.name && " + "(!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && " + f"object.spec.uris == ['spiffe://firemud/ns/' + {namespace_service} + '/sa/spring-cloud-gateway'] && " + "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))" +) +assert gateway_client_profile in normalized_profile_expression +assert "object.metadata.name == 'dev-grpc-spring-cloud-gateway'" in cert_manager_expression +assert "'firemud-grpc-spring-cloud-gateway'" in controller_secret_expression assert_balanced_cel_delimiters(profile_expression, "publication Certificate profile") for required_publication_common_guard in ( "request.operation != 'DELETE'", @@ -2224,7 +2237,8 @@ require_literal "$ADMISSION" "'firemud-grpc-game-session-service'" require_literal "$ADMISSION" "'firemud-grpc-social-groups-service'" require_literal "$ADMISSION" "'-grpc-account-service-previous'), " require_literal "$ADMISSION" "'-grpc-game-session-service-previous'), " -require_literal "$ADMISSION" "'-grpc-social-groups-service-previous')] &&" +require_literal "$ADMISSION" "'-grpc-social-groups-service-previous'), " +require_literal "$ADMISSION" "'-grpc-spring-cloud-gateway-previous')] &&" require_literal "$ADMISSION" "request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' ||" require_literal "$BOOTSTRAP" "crd_deadline=\$((SECONDS + WAIT_SECONDS))" # shellcheck disable=SC2016 # Match the literal bootstrap default. @@ -3960,6 +3974,12 @@ def service_consumer_documents(): } ) if service == "spring-cloud-gateway": + sources["gameplay-client-tls"] = ( + "/gameplay-client-tls", "secret", "firemud-grpc-spring-cloud-gateway" + ) + sources["gameplay-client-trust"] = ( + "/gameplay-client-trust", "secret", "firemud-grpc-tls" + ) sources["gateway-ws-server-tls"] = ( "/gateway-ws-server-tls", "secret", @@ -3979,12 +3999,12 @@ def service_consumer_documents(): {"key": "tls.key", "path": "tls.key"}, {"key": "ca.crt", "path": "ca.crt"}, ] - elif name == "grpc-tls" and distinct_workload: + elif (name == "grpc-tls" and distinct_workload) or name == "gameplay-client-tls": projection["items"] = [ {"key": "tls.crt", "path": "tls.crt"}, {"key": "tls.key", "path": "tls.key"}, ] - elif name == "grpc-trust": + elif name in {"grpc-trust", "gameplay-client-trust"}: projection["items"] = [ {"key": "ca.crt", "path": "ca.crt"}, ] @@ -4058,6 +4078,28 @@ def service_consumer_documents(): valid_consumers = service_consumer_documents() validator.validate_service_consumers(valid_consumers, "pr-42", "standalone", "public") +for forbidden_client_projection in ("shared-leaf", "server-leaf", "private-trust", "management-path"): + malformed = copy.deepcopy(valid_consumers) + gateway = next(document for document in malformed if document["metadata"]["name"] == "spring-cloud-gateway") + pod = gateway["spec"]["template"]["spec"] + client_volume = next(volume for volume in pod["volumes"] if volume["name"] == "gameplay-client-tls") + trust_volume = next(volume for volume in pod["volumes"] if volume["name"] == "gameplay-client-trust") + if forbidden_client_projection == "shared-leaf": + client_volume["secret"]["secretName"] = "firemud-grpc-tls" + elif forbidden_client_projection == "server-leaf": + client_volume["secret"]["secretName"] = "pr-42-gateway-internal-ws" + elif forbidden_client_projection == "private-trust": + trust_volume["secret"]["items"].append({"key": "client.key", "path": "client.key"}) + else: + entry = next(entry for entry in pod["containers"][0]["env"] if entry["name"] == "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH") + entry["value"] = "/tls/client.crt" + try: + validator.validate_service_consumers(malformed, "pr-42", "standalone", "public") + except ValueError: + pass + else: + raise AssertionError(f"validator accepted Gateway client {forbidden_client_projection}") + logging_namespace_failure = ( "Deployment/logging-admin-service must bind " "FIREMUD_GRPC_WORKLOAD_NAMESPACE to metadata.namespace" @@ -4862,13 +4904,14 @@ def allows_shared_namespace_identity(service, env): "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, } - if service == "logging-admin-service": + if service in {"logging-admin-service", "spring-cloud-gateway"}: return namespace_identity == expected_namespace_identity return namespace_identity is None -# The exact downward-API namespace identity is valid only for Logging & Admin -# among shared transports; every other shared service must reject this shape. +# Logging & Admin and Gateway's separate gameplay client need the exact downward-API +# namespace identity while their gRPC transports retain the shared secret and paths. +# Every other shared service must reject this shape. negative_shared_namespace_fixture = { "FIREMUD_GRPC_WORKLOAD_NAMESPACE": { "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", @@ -4876,10 +4919,23 @@ negative_shared_namespace_fixture = { } } for service in shared_services: - if service != "logging-admin-service" and allows_shared_namespace_identity( - service, negative_shared_namespace_fixture + if ( + service not in {"logging-admin-service", "spring-cloud-gateway"} + and allows_shared_namespace_identity(service, negative_shared_namespace_fixture) ): fail(f"shared namespace identity fixture unexpectedly accepted for {service}") +for service in ("logging-admin-service", "spring-cloud-gateway"): + for invalid_identity in ( + {"name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "value": "literal-namespace"}, + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}}, + }, + ): + if allows_shared_namespace_identity( + service, {"FIREMUD_GRPC_WORKLOAD_NAMESPACE": invalid_identity} + ): + fail(f"shared namespace identity fixture accepted malformed identity for {service}") def assert_distinct_workload_service(service, deployment_map, source): @@ -4966,7 +5022,7 @@ for service in shared_services: container, service, "/tls/client.crt", "/tls/client.key", "/tls/ca.crt" ) env = env_map(container, service) - if service == "logging-admin-service": + if service in {"logging-admin-service", "spring-cloud-gateway"}: if not allows_shared_namespace_identity(service, env): fail( f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 535f7d75c6..fc45886f37 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -719,6 +719,7 @@ contains "$waiter" 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.cr contains "$waiter" 'firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt' contains "$waiter" 'firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt' contains "$waiter" 'firemud-grpc-social-groups-service|grpc-social-groups-service|tls.crt,tls.key,ca.crt' +contains "$waiter" 'firemud-grpc-spring-cloud-gateway|grpc-spring-cloud-gateway|tls.crt,tls.key,ca.crt' for workload in \ game-design-service \ world-management-service \ @@ -6088,6 +6089,9 @@ if [[ "$1" == -n && "$2" == pr-42 && "$3" == get && "$4" == secret ]]; then firemud-grpc-social-groups-service) printf '%s' '{"metadata":{"name":"firemud-grpc-social-groups-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-social-groups-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-spring-cloud-gateway) + printf '%s' '{"metadata":{"name":"firemud-grpc-spring-cloud-gateway","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-spring-cloud-gateway","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; *) printf 'unexpected projection Secret: %s\n' "$secret_name" >&2 exit 2 @@ -6203,20 +6207,20 @@ run_projection_waiter_fixture() { fi } -# Successful two-retry fixtures read 13 canonical projections plus two retries. -run_projection_waiter_fixture projection-absence 0 15 2 +# Successful two-retry fixtures read 14 canonical projections plus two retries. +run_projection_waiter_fixture projection-absence 0 16 2 run_projection_waiter_fixture projection-command-failure 42 1 0 'Error from server (Forbidden)' run_projection_waiter_fixture projection-command-not-found 46 1 0 'Error from server (NotFound)' run_projection_waiter_fixture projection-command-unauthorized 47 1 0 'Error from server (Unauthorized)' run_projection_waiter_fixture projection-command-usage-error 2 1 0 'error: unknown flag' -run_projection_waiter_fixture projection-transport-recovery 0 15 2 +run_projection_waiter_fixture projection-transport-recovery 0 16 2 run_projection_waiter_fixture projection-transport-exhaustion 45 3 2 'Unable to connect to the server' -run_projection_waiter_fixture projection-etcd-timeout-recovery 0 15 2 -run_projection_waiter_fixture projection-etcd-leader-recovery 0 15 2 -run_projection_waiter_fixture projection-overload-recovery 0 15 2 -run_projection_waiter_fixture projection-unavailable-recovery 0 15 2 -run_projection_waiter_fixture projection-currently-unavailable-recovery 0 15 2 -run_projection_waiter_fixture projection-apiserver-shutdown-recovery 0 15 2 +run_projection_waiter_fixture projection-etcd-timeout-recovery 0 16 2 +run_projection_waiter_fixture projection-etcd-leader-recovery 0 16 2 +run_projection_waiter_fixture projection-overload-recovery 0 16 2 +run_projection_waiter_fixture projection-unavailable-recovery 0 16 2 +run_projection_waiter_fixture projection-currently-unavailable-recovery 0 16 2 +run_projection_waiter_fixture projection-apiserver-shutdown-recovery 0 16 2 run_active_waiter_fixture() { local scenario="$1" diff --git a/dev-tools/tests/preflight-contract.sh b/dev-tools/tests/preflight-contract.sh index 97a03fe0a4..982c3a122a 100644 --- a/dev-tools/tests/preflight-contract.sh +++ b/dev-tools/tests/preflight-contract.sh @@ -1306,6 +1306,34 @@ social_spec = social_groups["spec"]["template"]["spec"] social_spec["containers"][0]["name"] = "social-groups-service" social_spec["volumes"][0]["secret"]["secretName"] = "firemud-grpc-social-groups-service" documents.append(social_groups) +gateway = next( + document for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "spring-cloud-gateway" +) +gateway_pod = gateway["spec"]["template"]["spec"] +gateway_container = gateway_pod["containers"][0] +gateway_container["env"] = [ + {"name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}}, + {"name": "FIREMUD_GRPC_CERT_CHAIN_PATH", "value": "/tls/client.crt"}, + {"name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", "value": "/tls/client.key"}, + {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH", "value": "/gameplay-client-tls/tls.crt"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH", "value": "/gameplay-client-tls/tls.key"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH", "value": "/gameplay-client-trust/ca.crt"}, +] +gateway_container["volumeMounts"].extend([ + {"name": "gameplay-client-tls", "mountPath": "/gameplay-client-tls", "readOnly": True}, + {"name": "gameplay-client-trust", "mountPath": "/gameplay-client-trust", "readOnly": True}, +]) +gateway_pod["volumes"].extend([ + {"name": "gameplay-client-tls", "secret": {"secretName": "firemud-grpc-spring-cloud-gateway", "items": [ + {"key": "tls.crt", "path": "tls.crt"}, {"key": "tls.key", "path": "tls.key"}, + ]}}, + {"name": "gameplay-client-trust", "secret": {"secretName": "firemud-grpc-tls", "items": [ + {"key": "ca.crt", "path": "ca.crt"}, + ]}}, +]) path.write_text(yaml.safe_dump_all(documents, sort_keys=False), encoding="utf-8") PY @@ -9971,6 +9999,24 @@ publication_documents = [ } for workload in module.GRPC_WORKLOAD_SECRET_CONSUMERS ] +for document in publication_documents: + if document["metadata"]["name"] != "spring-cloud-gateway": + continue + pod = document["spec"]["template"]["spec"] + pod["volumes"][0]["name"] = "gameplay-client-tls" + pod["volumes"][1]["name"] = "gameplay-client-trust" + container = pod["containers"][0] + container["env"] = [ + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH", "value": "/gameplay-client-tls/tls.crt"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH", "value": "/gameplay-client-tls/tls.key"}, + {"name": "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH", "value": "/gameplay-client-trust/ca.crt"}, + {"name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}}, + {"name": "FIREMUD_GRPC_CERT_CHAIN_PATH", "value": "/tls/client.crt"}, + {"name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", "value": "/tls/client.key"}, + {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, + ] + container["volumeMounts"][0].update(name="gameplay-client-tls", mountPath="/gameplay-client-tls") + container["volumeMounts"][1].update(name="gameplay-client-trust", mountPath="/gameplay-client-trust") if module.PUBLICATION_GRPC_WORKLOADS != ( "game-design-service", "world-management-service", @@ -9996,7 +10042,7 @@ if {name for name, _, _ in publication_requirements} != ( expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): raise SystemExit( - "workload Secret requirements do not follow the eight leaf bindings and shared trust binding" + "workload Secret requirements do not follow the nine leaf bindings and shared trust binding" ) publication_keys = {name: keys for name, _, keys in publication_requirements} if any(namespace != "firemud" for _, namespace, _ in publication_requirements): @@ -10029,6 +10075,19 @@ def expect_publication_static_failure(description, documents, expected_fragment= ) +gateway_index = module.GRPC_WORKLOAD_SECRET_CONSUMERS.index("spring-cloud-gateway") +gateway_wrong_secret = copy.deepcopy(publication_documents) +gateway_wrong_secret[gateway_index]["spec"]["template"]["spec"]["volumes"][0]["secret"]["secretName"] = "firemud-grpc-tls" +expect_publication_static_failure("a Gateway client sharing its management credential", gateway_wrong_secret) +gateway_wrong_path = copy.deepcopy(publication_documents) +gateway_wrong_path[gateway_index]["spec"]["template"]["spec"]["containers"][0]["env"][0]["value"] = "/tls/client.crt" +expect_publication_static_failure("a Gateway client using the management TLS path", gateway_wrong_path) +gateway_private_trust = copy.deepcopy(publication_documents) +gateway_private_trust[gateway_index]["spec"]["template"]["spec"]["volumes"][1]["secret"]["items"].append({"key": "client.key", "path": "client.key"}) +expect_publication_static_failure("a Gateway client trust projection exposing a private key", gateway_private_trust) +gateway_namespace = copy.deepcopy(publication_documents) +gateway_namespace[gateway_index]["spec"]["template"]["spec"]["containers"][0]["env"][3] = {"name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "value": "other"} +expect_publication_static_failure("a Gateway client overriding its namespace", gateway_namespace) social_groups_index = module.SHARED_TRUST_GRPC_WORKLOADS.index("social-groups-service") missing_social_groups_documents = copy.deepcopy(publication_documents) missing_social_groups_documents.pop(social_groups_index) @@ -10593,7 +10652,7 @@ with patch.object( if module.publication_workload_secret_issues( publication_expected, publication_documents ): - raise SystemExit("complete eight-workload Secret fixture failed preflight") + raise SystemExit("complete nine-workload Secret fixture failed preflight") if {name for name, _, _ in queried_publication_secrets} != ( expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): diff --git a/dev-tools/tests/standalone-grpc-certificates-contract.sh b/dev-tools/tests/standalone-grpc-certificates-contract.sh index 233bf697fc..9062117df7 100644 --- a/dev-tools/tests/standalone-grpc-certificates-contract.sh +++ b/dev-tools/tests/standalone-grpc-certificates-contract.sh @@ -74,9 +74,10 @@ workloads = ( "account-service", "game-session-service", "social-groups-service", + "spring-cloud-gateway", ) if len(documents) != len(workloads): - raise SystemExit(f"expected eight Certificate documents, got {len(documents)}") + raise SystemExit(f"expected nine Certificate documents, got {len(documents)}") for workload, document in zip(workloads, documents, strict=True): expected_name = f"{namespace}-grpc-{workload}" if document.get("apiVersion") != "cert-manager.io/v1" or document.get("kind") != "Certificate": @@ -103,29 +104,31 @@ for workload, document in zip(workloads, documents, strict=True): "rotationPolicy": "Always", }: raise SystemExit(f"{expected_name} has an unexpected private-key profile") - if spec.get("dnsNames") != [ + expected_dns = None if workload == "spring-cloud-gateway" else [ workload, f"{workload}.{namespace}", f"{workload}.{namespace}.svc", f"{workload}.{namespace}.svc.cluster.local", - ]: + ] + if spec.get("dnsNames") != expected_dns: raise SystemExit(f"{expected_name} has unexpected DNS identities") if spec.get("uris") != [f"spiffe://firemud/ns/{namespace}/sa/{workload}"]: raise SystemExit(f"{expected_name} has an unexpected workload URI") - if spec.get("usages") != [ + expected_usages = ["digital signature", "key encipherment", "client auth"] if workload == "spring-cloud-gateway" else [ "digital signature", "key encipherment", "server auth", "client auth", - ]: + ] + if spec.get("usages") != expected_usages: raise SystemExit(f"{expected_name} has unexpected usages") if spec.get("encodeUsagesInRequest") is not True: raise SystemExit(f"{expected_name} omits encoded usages") PY actual_wait_count="$(grep -c ' wait ' "$STATE_DIR/calls")" - [[ "$actual_wait_count" -eq 8 ]] || { - echo "expected eight Certificate readiness waits for $namespace, got $actual_wait_count" >&2 + [[ "$actual_wait_count" -eq 9 ]] || { + echo "expected nine Certificate readiness waits for $namespace, got $actual_wait_count" >&2 exit 1 } if grep -E 'get secret|create secret|apply.*secret' "$STATE_DIR/calls" >/dev/null; then @@ -168,6 +171,7 @@ for workload in ( "account-service", "game-session-service", "social-groups-service", + "spring-cloud-gateway", ): assert workload in request_text, workload assert f"firemud-grpc-{workload}" in certificate_text, workload diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index 35d59e629d..60e556e220 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -184,7 +184,7 @@ def check_contract(items: list[dict]) -> None: "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", "firemud-hosted-identity-controller", "system:serviceaccount:kube-system:namespace-controller", - "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')", + "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$')", ): require(certificate, needle, "Certificate boundary") status_rules = certificate_status["matchConstraints"]["resourceRules"] @@ -212,7 +212,7 @@ def check_contract(items: list[dict]) -> None: fail("Certificate status denial message does not describe the allowed callers") require( certificate_validation, - "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$", + "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$", "standalone Certificate validation", ) for needle in ( @@ -250,6 +250,16 @@ def check_contract(items: list[dict]) -> None: expected_branch, f"standalone {workload} Certificate identity", ) + require( + normalized_certificate_validation, + "(object.metadata.name.endsWith('-grpc-spring-cloud-gateway') && " + "object.spec.secretName == 'firemud-grpc-spring-cloud-gateway' && " + "object.spec.issuerRef.name == 'firemud-ca-issuer' && " + "(!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && " + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/spring-cloud-gateway'] && " + "object.spec.usages == ['digital signature', 'key encipherment', 'client auth'])", + "standalone Gateway client-only identity", + ) require( certificate_validation, "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer", diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 817c2c0702..873cbac3d9 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -1878,6 +1878,10 @@ def _policy_documents(self, mode): {"protocol": "TCP", "port": 53}, ], }, + { + "to": [{"podSelector": {"matchLabels": {"app": "game-session-service"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }, { "to": [ { @@ -2585,6 +2589,16 @@ def _gateway_document(self): "mountPath": "/tls", "readOnly": True, }, + { + "name": "gameplay-client-tls", + "mountPath": "/gameplay-client-tls", + "readOnly": True, + }, + { + "name": "gameplay-client-trust", + "mountPath": "/gameplay-client-trust", + "readOnly": True, + }, { "name": "jwt-signing-keys", "mountPath": "/var/run/secrets/firemud/jwt", @@ -2603,6 +2617,23 @@ def _gateway_document(self): "name": "grpc-tls", "secret": {"secretName": "firemud-grpc-tls"}, }, + { + "name": "gameplay-client-tls", + "secret": { + "secretName": "firemud-grpc-spring-cloud-gateway", + "items": [ + {"key": "tls.crt", "path": "tls.crt"}, + {"key": "tls.key", "path": "tls.key"}, + ], + }, + }, + { + "name": "gameplay-client-trust", + "secret": { + "secretName": "firemud-grpc-tls", + "items": [{"key": "ca.crt", "path": "ca.crt"}], + }, + }, { "name": "jwt-signing-keys", "secret": {"secretName": "jwt-signing-keys"}, @@ -2630,6 +2661,34 @@ def test_gateway_exact_environment_contract_is_accepted(self): [self._gateway_document()], "pr-42" ) + def test_gateway_rejects_unsafe_gameplay_mount(self): + for option, value in (("readOnly", False), ("subPath", "tls.key")): + with self.subTest(option=option): + document = self._gateway_document() + mounts = document["spec"]["template"]["spec"]["containers"][0]["volumeMounts"] + gameplay_mount = next( + mount for mount in mounts if mount["name"] == "gameplay-client-tls" + ) + gameplay_mount[option] = value + with ( + patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}), + self.assertRaisesRegex(ValueError, "unsafe gameplay-client-tls mount"), + ): + self.validator.validate_service_consumers([document], "pr-42") + + def test_gateway_rejects_extra_gameplay_client_tls_item(self): + document = self._gateway_document() + volumes = document["spec"]["template"]["spec"]["volumes"] + gameplay_volume = next( + volume for volume in volumes if volume["name"] == "gameplay-client-tls" + ) + gameplay_volume["secret"]["items"].append({"key": "ca.crt", "path": "ca.crt"}) + with ( + patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}), + self.assertRaisesRegex(ValueError, "unsafe grpc-tls projection"), + ): + self.validator.validate_service_consumers([document], "pr-42") + def test_gateway_rejects_redirect_and_jvm_environment_injection(self): for injected in ( { diff --git a/k8s/base/spring-cloud-gateway.yaml b/k8s/base/spring-cloud-gateway.yaml index 63419f4ffe..5252ab891d 100644 --- a/k8s/base/spring-cloud-gateway.yaml +++ b/k8s/base/spring-cloud-gateway.yaml @@ -25,6 +25,16 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH + value: /gameplay-client-tls/tls.crt + - name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH + value: /gameplay-client-tls/tls.key + - name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH + value: /gameplay-client-trust/ca.crt - name: FIREMUD_GRPC_CERT_CHAIN_PATH value: /tls/client.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH @@ -53,6 +63,12 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: gameplay-client-tls + mountPath: /gameplay-client-tls + readOnly: true + - name: gameplay-client-trust + mountPath: /gameplay-client-trust + readOnly: true - name: gateway-ws-server-tls mountPath: /gateway-ws-server-tls readOnly: true @@ -126,6 +142,20 @@ spec: - name: grpc-tls secret: secretName: firemud-grpc-tls + - name: gameplay-client-tls + secret: + secretName: firemud-grpc-spring-cloud-gateway + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: gameplay-client-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt - name: gateway-ws-server-tls secret: secretName: production-gateway-internal-ws diff --git a/k8s/helm/README.md b/k8s/helm/README.md index ffd8aeb535..62caffd564 100644 --- a/k8s/helm/README.md +++ b/k8s/helm/README.md @@ -48,7 +48,7 @@ helm upgrade --install pr-123 ./firemud \ --create-namespace ``` -Before applying the full-stack chart, trusted environment setup must provision these eight namespace-scoped workload leaf Secrets: `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, `firemud-grpc-automation-scripting-service`, `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. It must also provision the shared `firemud-grpc-tls` trust bundle with issuer CA trust for all eight leaves. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for all eight leaves; hosted-controller setup must wait for all eight workload Secret projections before applying the chart. Hosted Helm workloads use their own Secret for the leaf certificate and key and the shared bundle's `ca.crt` projection for peer trust. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.md), under the canonical [deployment-environment contract](../../design/architecture/infrastructure/deployment-environments.md) and [ADR 0038](../../design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). Direct `helm template` only renders Secret references; it does not prove that the Secrets exist or are ready. Keep certificate material and secret credentials out of PR-controlled values and workflows. +Before applying the full-stack chart, trusted environment setup must provision the eight namespace-scoped serving-workload leaf Secrets (`firemud-grpc-` for the five publication workloads, Account, Game Session, and Social Groups), the separate client-only `firemud-grpc-spring-cloud-gateway` Secret, and the shared `firemud-grpc-tls` trust bundle. Standalone setup requests all nine through [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh); hosted-controller setup waits for all nine workload projections. Gateway's new `gameplay-client-tls` mount contains only its outbound leaf and key, while `gameplay-client-trust` exposes only the shared bundle's `ca.crt`. Its existing management gRPC and internal WebSocket server mounts remain separate. The canonical issuance, identity profiles, and readiness rules are owned by [Deployment Environments](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) and [certificate management](../../design/architecture/infrastructure/environment-and-secrets-overview.md#certificate-management-and-watchers). `helm template` renders references only; it does not prove existing Secrets, live issuance, or an authenticated gameplay exchange. Keep certificate material and credentials out of PR-controlled values and workflows. The hosted chart owns public `jwt-jwks` as a `ConfigMap`. Helm treats a same-name legacy Secret and the target ConfigMap as distinct resource identities, so the upgrade creates the ConfigMap and removes the obsolete Secret without a manual pre-delete. The `dev-tools/tests/helm-jwks-contract.sh` test proves the target rendered resource and workload wiring; it is not a live-cluster upgrade or downtime proof. diff --git a/k8s/helm/firemud/templates/_helpers.tpl b/k8s/helm/firemud/templates/_helpers.tpl index db8901e051..1407f6ed59 100644 --- a/k8s/helm/firemud/templates/_helpers.tpl +++ b/k8s/helm/firemud/templates/_helpers.tpl @@ -171,3 +171,12 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} {{- include "firemud.grpcSecretName" .root -}} {{- end -}} {{- end -}} + +{{- define "firemud.gatewayGameplayClientEnv" -}} +- name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH + value: /gameplay-client-tls/tls.crt +- name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH + value: /gameplay-client-tls/tls.key +- name: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH + value: /gameplay-client-trust/ca.crt +{{- end -}} diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index 678c165074..fdf42aacae 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -64,11 +64,13 @@ {{- $managedTelnetEnv := list "TCP_PROXY_TELNET_MODE" "TCP_PROXY_TLS_ENABLED" "TCP_PROXY_TLS_CERT" "TCP_PROXY_TLS_KEY" }} {{- $managedGatewayWsServerEnv := list "FIREMUD_GATEWAY_TCP_PROXY_TLS_ENABLED" "FIREMUD_GATEWAY_TCP_PROXY_TLS_BIND_ADDRESS" "FIREMUD_GATEWAY_TCP_PROXY_TLS_PORT" "FIREMUD_GATEWAY_TCP_PROXY_TLS_CERT_CHAIN_PATH" "FIREMUD_GATEWAY_TCP_PROXY_TLS_PRIVATE_KEY_PATH" "FIREMUD_GATEWAY_TCP_PROXY_TLS_CLIENT_CA_PATH" "FIREMUD_GATEWAY_TCP_PROXY_TRUST_ENVIRONMENT" "FIREMUD_GATEWAY_TCP_PROXY_TRUST_PROFILE" "FIREMUD_GATEWAY_TCP_PROXY_TRUST_URI_SAN" }} {{- $managedGatewayWsClientEnv := list "GATEWAY_WS_URL" "FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH" "FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH" "FIREMUD_GATEWAY_WS_CA_CERT_PATH" }} +{{- $managedGameplayClientEnv := list "FIREMUD_GRPC_WORKLOAD_NAMESPACE" "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH" "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH" "FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH" }} {{- $grpcWorkloadNames := include "firemud.grpcWorkloadNames" . | fromJsonArray }} {{- range $service := .Values.previewStack.services }} {{- $serviceType := default "ClusterIP" $service.serviceType }} {{- $usesGrpcWorkloadIdentity := has $service.name $grpcWorkloadNames }} {{- $mountGrpcTrustBundle := and $service.mountGrpcTls $usesGrpcWorkloadIdentity }} +{{- $mountGameplayClientTls := and (eq $service.name "spring-cloud-gateway") $service.mountGrpcTls }} {{- $publicTelnetService := and (eq $service.name "tcp-proxy-service") (or (eq $serviceType "NodePort") (eq $serviceType "LoadBalancer")) }} {{- $telnetPort := "" }} {{- if and $publicTelnetService $telnetTlsEnabled (not $service.mountTelnetTls) }} @@ -109,6 +111,9 @@ {{- if and $mountGatewayWsServerTls (has $key $managedGatewayWsServerEnv) }} {{- fail (printf "previewStack.services.%s.extraEnv key %s collides with the managed Gateway WebSocket server TLS environment" $service.name $key) }} {{- end }} +{{- if and $mountGameplayClientTls (has $key $managedGameplayClientEnv) }} +{{- fail (printf "previewStack.services.%s.extraEnv key %s collides with the managed Gateway gameplay client TLS environment" $service.name $key) }} +{{- end }} {{- if and $mountGatewayWsClientTls (has $key $managedGatewayWsClientEnv) }} {{- fail (printf "previewStack.services.%s.extraEnv key %s collides with the managed Gateway WebSocket client TLS environment" $service.name $key) }} {{- end }} @@ -188,7 +193,7 @@ spec: - name: SERVICE_SCHEMA value: {{ default (replace "-" "_" $service.name) $service.schema | quote }} {{- if $service.mountGrpcTls }} - {{- if or $usesGrpcWorkloadIdentity (eq $service.name "logging-admin-service") }} + {{- if or $usesGrpcWorkloadIdentity (eq $service.name "logging-admin-service") $mountGameplayClientTls }} - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE valueFrom: fieldRef: @@ -204,6 +209,9 @@ spec: {{- else }} {{ include "firemud.grpcTlsEnv" $ | nindent 12 }} {{- end }} + {{- end }} + {{- if $mountGameplayClientTls }} +{{ include "firemud.gatewayGameplayClientEnv" $ | nindent 12 }} {{- end }} {{- range $key, $value := $service.extraEnv }} - name: {{ $key }} @@ -233,6 +241,14 @@ spec: mountPath: /tls readOnly: true {{- end }} + {{- if $mountGameplayClientTls }} + - name: gameplay-client-tls + mountPath: /gameplay-client-tls + readOnly: true + - name: gameplay-client-trust + mountPath: /gameplay-client-trust + readOnly: true + {{- end }} {{- if $mountGrpcTrustBundle }} - name: grpc-trust mountPath: /grpc-trust @@ -311,6 +327,22 @@ spec: path: tls.key {{- end }} {{- end }} + {{- if $mountGameplayClientTls }} + - name: gameplay-client-tls + secret: + secretName: firemud-grpc-spring-cloud-gateway + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: gameplay-client-trust + secret: + secretName: {{ include "firemud.grpcSecretName" $ }} + items: + - key: ca.crt + path: ca.crt + {{- end }} {{- if $mountGrpcTrustBundle }} - name: grpc-trust secret: diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index f5de2c3d8d..e05bb9b65c 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -303,6 +303,13 @@ spec: port: 53 - protocol: TCP port: 53 + - to: + - podSelector: + matchLabels: + app: game-session-service + ports: + - protocol: TCP + port: 8444 - to: - podSelector: matchExpressions: @@ -334,6 +341,27 @@ spec: --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy +metadata: + name: game-session-authenticated-gameplay-ingress + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: game-session-service + policyTypes: + - Ingress + ingress: + - from: + - podSelector: + matchLabels: + app: spring-cloud-gateway + ports: + - protocol: TCP + port: 8444 +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy metadata: name: tcp-proxy-service-egress labels: diff --git a/k8s/helm/firemud/values-hosted-shared.example.yaml b/k8s/helm/firemud/values-hosted-shared.example.yaml index 6bea3181ef..d15fc01acf 100644 --- a/k8s/helm/firemud/values-hosted-shared.example.yaml +++ b/k8s/helm/firemud/values-hosted-shared.example.yaml @@ -358,11 +358,16 @@ previewStack: envFromShared: true mountGrpcTls: true healthPort: 8080 + extraEnv: + FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED: "true" + FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT: "8444" ports: - port: 8080 targetPort: 8080 - port: 6565 targetPort: 6565 + - port: 8444 + targetPort: 8444 - name: logging-admin-service schema: logging_admin_service image: @@ -398,6 +403,8 @@ previewStack: mountGrpcTls: true mountGatewayWsServerTls: true healthPort: 8080 + extraEnv: + FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL: "wss://game-session-service.$(FIREMUD_GRPC_WORKLOAD_NAMESPACE).svc.cluster.local:8444/ws/game/tcp" ports: - port: 80 targetPort: 8080 diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 8df1914c3a..77cef3e458 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -18,9 +18,9 @@ There is no user-supplied hostname, Secret, Certificate, issuer, port, key, roll The trusted preview workflow derives an explicit mode from the validated runtime artifact: a `ClusterIP` `tcp-proxy-service` selects `private`, and a `NodePort` selects `public`. The runtime Namespace must carry the matching `firemud.dev/preview-exposure-mode` label; an absent, unknown, or changed mode is invalid. The controller never infers private mode from a failed public probe. -In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete publication projections, the distinct Account, Game Session, and Social Groups workload projections, and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. +In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all [fourteen labeled, key-complete runtime projections](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. -In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five publication projections, the distinct Account, Game Session, and Social Groups workload projections, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). +In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all [fourteen labeled, key-complete runtime projections](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle), and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). ## Resource and status contract @@ -34,13 +34,11 @@ Controller-managed resources carry these stable labels: Existing runtime namespaces retain their workflow labels. PR namespaces must have `firemud.dev/preview=true` and a matching `firemud.dev/pr-number`; the demo namespace must have `firemud.dev/dev-demo=true` and `firemud.dev/environment-class=dev-demo-cluster`. -Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and role evidence for ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and the shared gRPC transport bundle. The `grpcPublication` map remains exactly the five fixed publication roles; `grpcAccountService`, `grpcGameSessionService`, and `grpcSocialGroupsService` separately retain each workload's `RoleStatus` high-water evidence. Readiness therefore covers eight gRPC workload identities: the five publication roles plus Account, Game Session, and Social Groups. Each role status records only non-secret revision, source and source-object generations, SPKI fingerprint, provenance, and state. `Ready` is true only when the current runtime Namespace UID and requested 40-character head SHA match the observed profile, the separately recorded post-Helm deployed head matches that request, all eight gRPC workload identities and other consumers have converged, and the mode-specific served probes pass. Public mode includes the served Telnet probe; private mode deliberately omits it and requires served HTTPS, the private bridge, and gRPC instead. A runtime UID, request, deployed-head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. +Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and role revision/high-water evidence. The `grpcPublication` map remains exactly the five fixed publication roles. `grpcAccountService`, `grpcGameSessionService`, and `grpcSocialGroupsService` retain the other three serving-workload statuses; `grpcGatewayClient` separately retains the outbound-only Gateway identity status. All nine workload identities must materialize, project, and roll out before readiness. The exact lifecycle and readiness contract is owned by [Deployment Environments](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle). A runtime UID, requested/deployed head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. -Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, tracks the eight distinct hosted gRPC workload leaves alongside the shared `firemud-grpc-tls` bundle (which remains the common CA trust source and leaf source for three other gRPC workloads), and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The eight workload leaves are the five publication roles plus Account, Game Session, and Social Groups; static render and controller-contract checks cover their fixed bindings and readiness evidence. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to the fixed Account, Game Session, and Social Groups gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make the controller Ready. These checks do not establish live certificate issuance or production-promotion evidence. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. -Renewal repeats the same generation-safe sequence. -Ordinary internal WebSocket identity renewal updates retained and projected material in place; it does not terminate the bridge. A consumer that has not reloaded the new identity keeps the controller non-ready. Explicit `Retired` intent while a runtime still exists instead scales both `spring-cloud-gateway` and `tcp-proxy-service` to zero and waits for their observed replica counts to reach zero before any retained identity cleanup can proceed, preventing stale in-memory identity reuse when replacement material is unavailable. +Normal Active reconciliation manages fourteen runtime Secret projections: the five shared roles and nine distinct workload identities. `firemud-grpc-spring-cloud-gateway` supplies only the dedicated outbound gameplay client mount. Gateway retains its shared `firemud-grpc-tls` management gRPC credential and its separate `-gateway-internal-ws` server credential. The eight serving workloads and existing served probes are unchanged; no Gateway gRPC server or probe is added. Certificate profiles, trust and rotation rules belong to [Deployment Environments](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) and the [certificate-management contract](../../design/architecture/infrastructure/environment-and-secrets-overview.md#certificate-management-and-watchers). Controller projection/rollout evidence does not prove the Gateway-to-Game Session gameplay exchange, live issuance, or production promotion. Missing runtime namespaces retain identity material and report a blocked or degraded condition. Retirement waits for an exact runtime Namespace `404`, then removes identity material and publishes generation-bound `Retired` with `Ready=False` while retaining the finalizer. The lifecycle requester observes that terminal status and deletes the request; only the subsequent deletion reconcile removes the finalizer. If retirement instead observes `RuntimeIdentityChanged`, the controller preserves its previously observed profile and never adopts the mismatched live values as retirement authority. The trusted lifecycle recovers by removing the whole disposable runtime namespace and proving the runtime-first exact `404`; the next retirement reconcile can then follow the normal ownership-checked retained-identity cleanup path. This does not authorize manual retained-identity deletion or bypass the bridge-shutdown and runtime-absence gates. Timeouts, non-404 API errors, resource-version conflicts, unknown API responses, mismatched SAN/EKU, or failed rollout/probe evidence stop the state machine without destructive cleanup. Reconciliation is idempotent and retries after interruption. diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index 58eaede844..d345c1e6bc 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -136,7 +136,7 @@ spec: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - name: grpcWorkloadServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)'" + expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)'" matchConstraints: matchPolicy: Equivalent resourceRules: @@ -162,17 +162,17 @@ spec: request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (oldObject.metadata.name == 'firemud-grpc-tls' || oldObject.metadata.name == 'firemud-grpc-account-service' || oldObject.metadata.name == 'firemud-grpc-game-session-service' || oldObject.metadata.name == 'firemud-grpc-social-groups-service' || - oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || - oldObject.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') || + (oldObject.metadata.name == 'firemud-grpc-tls' || oldObject.metadata.name == 'firemud-grpc-account-service' || oldObject.metadata.name == 'firemud-grpc-game-session-service' || oldObject.metadata.name == 'firemud-grpc-social-groups-service' || oldObject.metadata.name == 'firemud-grpc-spring-cloud-gateway' || + oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') || + oldObject.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') || oldObject.metadata.name == 'firemud-grpc-tls-previous' || - oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))) || + oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))-previous$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || - object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') || - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || object.metadata.name == 'firemud-grpc-spring-cloud-gateway' || + object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') || + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') || object.metadata.name == 'firemud-grpc-tls-previous' || - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))))) + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))-previous$'))))) validations: # Namespace deletion also deletes the exact retained material. Allow # only the built-in kube-system namespace controller, DELETE, managed @@ -207,7 +207,8 @@ spec: (object.metadata.name == 'firemud-grpc-automation-scripting-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-automation-scripting-service') || (object.metadata.name == 'firemud-grpc-account-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-account-service') || (object.metadata.name == 'firemud-grpc-game-session-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service') || - (object.metadata.name == 'firemud-grpc-social-groups-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service'))))) || + (object.metadata.name == 'firemud-grpc-social-groups-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service') || + (object.metadata.name == 'firemud-grpc-spring-cloud-gateway' && object.metadata.labels['firemud.dev/role'] == 'grpc-spring-cloud-gateway'))))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && ((request.operation == 'DELETE' && (oldObject.metadata.name == 'firemud-grpc-tls' || @@ -228,9 +229,9 @@ spec: (request.operation != 'DELETE' && has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.labels['firemud.dev/retention'] == 'retained' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || object.metadata.name == 'firemud-grpc-spring-cloud-gateway' || (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && object.metadata.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -258,7 +259,7 @@ spec: object.metadata.annotations['cert-manager.io/certificate-name'] == object.metadata.name && ((object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet'] && object.metadata.annotations['cert-manager.io/issuer-name'] == 'letsencrypt-prod') || - ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer')) && object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && @@ -277,7 +278,8 @@ spec: object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == 'dev-grpc-account-service') || (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == 'dev-grpc-game-session-service') || - (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == 'dev-grpc-social-groups-service'))) || + (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == 'dev-grpc-social-groups-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-spring-cloud-gateway' && object.metadata.name == 'dev-grpc-spring-cloud-gateway'))) || (request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') && object.metadata.labels['firemud.dev/identity-name'] == request.namespace.substring(0, request.namespace.size() - 9) && ((object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-tls' && @@ -292,7 +294,8 @@ spec: object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-account-service') || (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-game-session-service') || - (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-social-groups-service'))))))) + (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-social-groups-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-spring-cloud-gateway' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-spring-cloud-gateway'))))))) message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret reason: Forbidden - expression: >- @@ -322,7 +325,7 @@ spec: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - name: grpcWorkloadServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)'" + expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)'" matchConstraints: matchPolicy: Equivalent resourceRules: @@ -348,12 +351,12 @@ spec: (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$'))) || ((request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && + oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') && oldObject.metadata.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')) || (request.operation != 'DELETE' && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') && object.metadata.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) @@ -386,7 +389,7 @@ spec: has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9)) && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && object.metadata.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : @@ -401,7 +404,7 @@ spec: object.spec.dnsNames == [((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.preview.firedevops.net'] && (!has(object.spec.uris) || object.spec.uris.size() == 0) && object.spec.issuerRef.name == 'letsencrypt-prod') || - ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service', 'grpc-spring-cloud-gateway'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.spec.issuerRef.name == 'firemud-ca-issuer')) && object.spec.issuerRef.kind == 'ClusterIssuer' && object.spec.issuerRef.group == 'cert-manager.io' && @@ -445,7 +448,13 @@ spec: (object.spec.secretName == object.metadata.name && object.spec.dnsNames == ['social-groups-service', 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/social-groups-service'] && - object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))))) || + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-spring-cloud-gateway' || + (object.metadata.name == ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-grpc-spring-cloud-gateway' && + object.spec.secretName == object.metadata.name && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/spring-cloud-gateway'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.subResource == 'status' && request.operation == 'UPDATE' && @@ -561,7 +570,7 @@ spec: object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && r.resources == ['certificates'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-spring-cloud-gateway')] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && @@ -571,12 +580,12 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-spring-cloud-gateway'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-spring-cloud-gateway-previous')] && r.verbs == ['get']) && object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-spring-cloud-gateway'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-spring-cloud-gateway-previous')] && r.verbs == ['update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && @@ -589,7 +598,7 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service', 'firemud-grpc-account-service', 'firemud-grpc-game-session-service', 'firemud-grpc-social-groups-service'] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service', 'firemud-grpc-account-service', 'firemud-grpc-game-session-service', 'firemud-grpc-social-groups-service', 'firemud-grpc-spring-cloud-gateway'] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && diff --git a/k8s/hosted-identity-controller/crd.yaml b/k8s/hosted-identity-controller/crd.yaml index f1a0a7e594..399675e012 100644 --- a/k8s/hosted-identity-controller/crd.yaml +++ b/k8s/hosted-identity-controller/crd.yaml @@ -206,6 +206,7 @@ spec: grpcAccountService: *consumer_status_schema grpcGameSessionService: *consumer_status_schema grpcSocialGroupsService: *consumer_status_schema + grpcGatewayClient: *consumer_status_schema grpcPublication: type: object description: Per-publication workload certificate projection and rollout evidence only; this does not prove receiver-method authorization or authorize publication identity activation. diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index ae70355c28..47a70c91a9 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -57,7 +57,7 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$'))) + owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$'))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -112,7 +112,7 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$'))) + owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$'))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -149,24 +149,24 @@ spec: (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || ((oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'CREATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || ((object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'UPDATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || (object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')) || (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || (oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -174,21 +174,21 @@ spec: (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')) || + oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$')) || (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && (request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')) || + oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$')) || (request.operation != 'DELETE' && ((request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && (request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || object.metadata.name.contains('-grpc-')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') && object.metadata.name.startsWith(request.namespace + '-') && has(object.spec.secretName) && ((object.metadata.name.contains('-grpc-') && - object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)$')) || + object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -270,10 +270,16 @@ spec: object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.dnsNames == ['social-groups-service', 'social-groups-service.' + request.namespace, 'social-groups-service.' + request.namespace + '.svc', 'social-groups-service.' + request.namespace + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/social-groups-service'] && - object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))) || + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-spring-cloud-gateway') && + object.spec.secretName == 'firemud-grpc-spring-cloud-gateway' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/spring-cloud-gateway'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service|spring-cloud-gateway))$') && has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.issuerRef.kind == 'ClusterIssuer' && diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index e3ac2ec028..a0addcc784 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -37,6 +37,8 @@ import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; @@ -52,6 +54,7 @@ import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -61,6 +64,7 @@ import net.firedevops.firemud.common.security.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; @@ -85,6 +89,13 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private final String workloadNamespace; private final boolean localDemoAuthenticationEnabled; private final String localDemoEmail; + private AccountGameplayAuthenticateReceiver canonicalGameplay; + + /** Canonical methods share this one AccountService registration; absence never selects legacy. */ + @Autowired + void canonicalGameplayReceiver(ObjectProvider receiver) { + canonicalGameplay = receiver.getIfAvailable(); + } public AccountGrpcService(PingService pingService, AccountService accountService) { this(pingService, accountService, null, null); @@ -415,6 +426,17 @@ public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { requireCredentialPeer(request); + if (request.hasSourceContext() || !request.getRequestId().isEmpty()) { + if (canonicalGameplay == null) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Canonical LOGIN authority unavailable") + .asRuntimeException()); + } else { + canonicalGameplay.authenticate(request, responseObserver); + } + return; + } net.firedevops.firemud.accountservice.dto.AuthenticationResult result = accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = @@ -461,6 +483,20 @@ public void authenticate( } } + @Override + public void retireInitialGameplayLogin( + RetireInitialGameplayLoginRequest request, + StreamObserver observer) { + if (canonicalGameplay == null) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Canonical LOGIN cleanup unavailable") + .asRuntimeException()); + return; + } + canonicalGameplay.retireInitialGameplayLogin(request, observer); + } + @Override @Timed(value = "accountGrpc.requestEmailLoginOtp") public void requestEmailLoginOtp( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index cd31baed7d..3aae3e801b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -78,6 +78,72 @@ import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { + @Test + void canonicalGameplayEnvelopeNeverFallsBackToLegacyCredentialAuthentication() { + var accounts = Mockito.mock(AccountService.class); + var service = + new AccountGrpcService(Mockito.mock(PingService.class), accounts, null, WORKLOAD_NAMESPACE); + var failure = new AtomicReference(); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("player@example.test") + .setPassword("transient-secret") + .setRequestId(UUID.randomUUID().toString()) + .build(), + new StreamObserver<>() { + @Override + public void onNext(AuthenticateResponse value) { + throw new AssertionError("No canonical owner"); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("No canonical owner"); + } + })); + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(failure.get()).getCode()); + Mockito.verifyNoInteractions(accounts); + } + + @Test + void canonicalAuthenticateAndExactRetirementShareSingleRegisteredAccountService() { + var accounts = Mockito.mock(AccountService.class); + var receiver = + Mockito.mock( + net.firedevops.firemud.accountservice.service.session + .AccountGameplayAuthenticateReceiver.class); + var provider = + Mockito + .> + mock(); + Mockito.when(provider.getIfAvailable()).thenReturn(receiver); + var service = + new AccountGrpcService(Mockito.mock(PingService.class), accounts, null, WORKLOAD_NAMESPACE); + service.canonicalGameplayReceiver(provider); + var request = + AuthenticateRequest.newBuilder().setRequestId(UUID.randomUUID().toString()).build(); + StreamObserver auth = Mockito.mock(); + withPeer(GAME_SESSION_PEER, () -> service.authenticate(request, auth)); + Mockito.verify(receiver).authenticate(request, auth); + var retirement = + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.newBuilder().build(); + StreamObserver cleanup = + Mockito.mock(); + service.retireInitialGameplayLogin(retirement, cleanup); + Mockito.verify(receiver).retireInitialGameplayLogin(retirement, cleanup); + Mockito.verifyNoInteractions(accounts); + } + private static final String WORKLOAD_NAMESPACE = "test"; private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; private static final String ACCOUNT_UUID_READBACK_FAILURE = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index 66a8783f25..bd4b016d75 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -120,19 +120,29 @@ private Optional compose(Instant createdAt, Instant expiresAt) { return Optional.of(new Snapshot(choices, original.fingerprint(), createdAt, expiresAt)); } - /** Resolves only the retained vector, then revalidates the complete selected owner record. */ + /** + * Resolves only the retained vector, then revalidates the complete selected owner record. + * + * @throws UnknownWorldSelectorException when a nonblank selector does not uniquely match a choice + * in a live menu owned by this service + * @throws ExpiredWorldSelectionException when this service's exact menu has expired before the + * resolution begins + */ public Optional resolve(SelectionSnapshot retained, String selector) { - if (retained == null - || retained.owner != this - || selector == null - || selector.isBlank() - || !isLive(retained.snapshot)) { + if (retained == null || retained.owner != this || selector == null || selector.isBlank()) { return Optional.empty(); } Snapshot snapshot = retained.snapshot; + Instant now = clock.instant(); + if (now.isBefore(snapshot.createdAt())) { + return Optional.empty(); + } + if (!now.isBefore(snapshot.expiresAt())) { + throw new ExpiredWorldSelectionException(); + } Optional selected = select(snapshot.choices(), selector); if (selected.isEmpty()) { - return Optional.empty(); + throw new UnknownWorldSelectorException(); } CanonicalPlayableTarget expected = selected.orElseThrow().target(); CanonicalPlayableTarget current; @@ -279,6 +289,24 @@ private String selector() { } } + /** A nonblank selector did not uniquely select a choice in this exact live menu. */ + public static final class UnknownWorldSelectorException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public UnknownWorldSelectorException() { + super("Unknown or ambiguous world selector"); + } + } + + /** The exact selection owner's retained menu expired before resolution began. */ + public static final class ExpiredWorldSelectionException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ExpiredWorldSelectionException() { + super("World selection menu expired"); + } + } + private record RuntimeWorldIdentity(long tenantId, String worldSlug) {} private record RuntimeTargetIdentity(long tenantId, long gameInstanceId) {} 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 14b7c392cb..94b61a6315 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 @@ -9,12 +9,14 @@ import java.security.MessageDigest; import java.time.Clock; import java.util.Arrays; +import java.util.HashSet; import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -64,6 +66,8 @@ public final class CanonicalGameplayLoginResult implements AutoCloseable { private final byte[] compactJwt; private final NonSecretEvidence evidence; private final Object lifecycleMutex = new Object(); + private final Set borrowers = new HashSet<>(); + private Thread closingThread; private boolean closed; private CanonicalGameplayLoginResult(byte[] compactJwt, NonSecretEvidence evidence) { @@ -294,20 +298,83 @@ private static UUID v4(String text) { public byte[] compactJwtBytes() { synchronized (lifecycleMutex) { - if (closed) throw new IllegalStateException("Canonical LOGIN private result is closed"); + if (closed || (closingThread != null && !borrowers.contains(Thread.currentThread()))) { + 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. */ + /** + * Pins this identical process-local result and its private bytes through the callback. Closing + * refuses new pins and drains existing callbacks before erasure, without holding a monitor across + * callback work. A callback must not retain the result or perform reentrant lifecycle operations. + * This lifetime guard supplies no transport, currentness, or admission authority. + */ + public T withLivePrivateResult(Function action) { + Objects.requireNonNull(action, "Private result action required"); + Thread borrower = Thread.currentThread(); + synchronized (lifecycleMutex) { + if (closed || closingThread != null || !borrowers.add(borrower)) { + throw new IllegalStateException("Canonical LOGIN private result is unavailable"); + } + } + try { + return action.apply(this); + } finally { + synchronized (lifecycleMutex) { + borrowers.remove(borrower); + lifecycleMutex.notifyAll(); + } + } + } + + /** + * Refuses lifecycle mutation by this result's current callback thread, without changing state. + */ + public void requireNotBorrowedByCurrentThread() { + synchronized (lifecycleMutex) { + if (borrowers.contains(Thread.currentThread()) || closingThread == Thread.currentThread()) { + throw new IllegalStateException("Canonical LOGIN private result is borrowed"); + } + } + } + @Override public void close() { + boolean interrupted = false; synchronized (lifecycleMutex) { - if (!closed) { - Arrays.fill(compactJwt, (byte) 0); - closed = true; + if (borrowers.contains(Thread.currentThread()) || closingThread == Thread.currentThread()) { + throw new IllegalStateException("Canonical LOGIN private result is borrowed"); + } + while (closingThread != null) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + if (closed) { + if (interrupted) Thread.currentThread().interrupt(); + return; } + closingThread = Thread.currentThread(); + while (!borrowers.isEmpty()) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + } + // No callback or secret reader can start while erasure runs outside the lifecycle monitor. + Arrays.fill(compactJwt, (byte) 0); + synchronized (lifecycleMutex) { + closed = true; + closingThread = null; + lifecycleMutex.notifyAll(); } + if (interrupted) Thread.currentThread().interrupt(); } public NonSecretEvidence evidence() { 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 index 0740d01f5f..1af8214274 100644 --- 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 @@ -21,6 +21,16 @@ public final class InitialGameplayLoginCredentialPresentation implements AutoClo private boolean current = true; private boolean requestCreated; + /** A receiving transport can present credentials only with its genuine authenticated ingress. */ + public static InitialGameplayLoginCredentialPresentation fromAuthenticatedTcp( + net.firedevops.firemud.gamesession.websocket.AuthenticatedDirectTextIngress ingress, + String normalizedEmail, + char[] ownedSecret) { + Objects.requireNonNull(ingress, "Authenticated TCP ingress required"); + return new InitialGameplayLoginCredentialPresentation( + normalizedEmail, ingress.clientAddress(), ownedSecret); + } + /** Ownership of {@code ownedSecret} transfers to this presentation. */ InitialGameplayLoginCredentialPresentation( String normalizedEmail, String canonicalClientAddress, char[] ownedSecret) { 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 index a107392d88..0d3bc4a846 100644 --- 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 @@ -1,8 +1,11 @@ package net.firedevops.firemud.gamesession.service; +import java.util.HashSet; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.function.Function; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; @@ -232,6 +235,8 @@ public static final class Outcome implements AutoCloseable { private CanonicalGameplayLoginResult transferredResult; private final Object lifecycleMutex = new Object(); private boolean resultTransferred; + private final Set borrowers = new HashSet<>(); + private Thread drainingThread; private boolean closed; private Optional custodyLossCleanup = Optional.empty(); @@ -293,43 +298,135 @@ public InitialGameplayLoginCleanupOwner.Status cleanupStatus() { return cleanupStatus; } - /** Transfers the verified private result exactly once to its receiving caller. */ - public Optional takePrivateResult() { + /** + * Borrows the identical installed result while this outcome retains ownership. Transfer, + * closure and retirement first block new borrows and drain existing callbacks. Neither owner + * nor result monitors cover callback work or cleanup I/O. Reentrant borrowing and lifecycle + * mutation are refused. This process-local guard supplies no transport or admission authority. + */ + public T withOwnedPrivateResult(Function action) { + Objects.requireNonNull(action, "Private result action required"); + Thread borrower = Thread.currentThread(); + CanonicalGameplayLoginResult result; 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); + if (closed + || drainingThread != null + || resultTransferred + || privateResult == null + || !borrowers.add(borrower)) { + throw new IllegalStateException("Owned initial LOGIN result is unavailable"); + } + result = privateResult; + } + try { + return result.withLivePrivateResult(action); + } finally { + synchronized (lifecycleMutex) { + borrowers.remove(borrower); + lifecycleMutex.notifyAll(); + } + } + } + + private void beginDrain() { + CanonicalGameplayLoginResult retained; + synchronized (lifecycleMutex) { + if (borrowers.contains(Thread.currentThread()) + || drainingThread == Thread.currentThread()) { + throw new IllegalStateException("Initial LOGIN result is borrowed"); + } + retained = privateResult != null ? privateResult : transferredResult; + } + // A direct result callback must not wait behind a drain that is itself waiting for its pin. + // Check before any mutation, outside the Outcome monitor, including transferred custody. + if (retained != null) retained.requireNotBorrowedByCurrentThread(); + boolean interrupted = false; + synchronized (lifecycleMutex) { + while (drainingThread != null) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + drainingThread = Thread.currentThread(); + while (!borrowers.isEmpty()) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + } + if (interrupted) Thread.currentThread().interrupt(); + } + + private void endDrain() { + synchronized (lifecycleMutex) { + drainingThread = null; + lifecycleMutex.notifyAll(); + } + } + + /** Transfers the verified private result exactly once after draining owned borrows. */ + public Optional takePrivateResult() { + beginDrain(); + try { + 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); + } + } finally { + endDrain(); } } /** - * 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. + * Called only at actual original pre-admission custody loss, including after transfer or a HELD + * cleanup observation. It drains owned callbacks, erases the exact result and retries cleanup + * against the exact original coordinates. It is not a rebind or reset authority. */ public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { - synchronized (lifecycleMutex) { + beginDrain(); + try { 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; - } + eraseRetainedResults(true); + return recordOriginalCleanup(); + } finally { + endDrain(); + } + } + + private void eraseRetainedResults(boolean includeTransferred) { + CanonicalGameplayLoginResult retained; + synchronized (lifecycleMutex) { closed = true; - custodyLossCleanup = Optional.of(attemptOriginalCleanup()); - return custodyLossCleanup.orElseThrow(); + retained = + privateResult != null ? privateResult : includeTransferred ? transferredResult : null; + } + // Draining excludes new callbacks; result.close also drains direct result borrowers. + if (retained != null) retained.close(); + synchronized (lifecycleMutex) { + privateResult = null; + if (includeTransferred) transferredResult = null; + } + } + + private InitialGameplayLoginCleanupOwner.CleanupObservation recordOriginalCleanup() { + var observation = attemptOriginalCleanup(); + synchronized (lifecycleMutex) { + custodyLossCleanup = Optional.of(observation); } + return observation; } public Optional custodyLossCleanup() { @@ -339,21 +436,22 @@ public Optional custodyLoss } /** - * 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. + * Closing untransferred custody drains and wipes its result, then attempts exact-original + * cleanup. Transfer leaves cleanup to the explicit custody-loss callback. A held observation + * remains retryable through that callback; cleanup never runs under a lifecycle monitor. */ @Override public void close() { - synchronized (lifecycleMutex) { - if (!closed) { - closed = true; - if (privateResult != null) { - privateResult.close(); - privateResult = null; - custodyLossCleanup = Optional.of(attemptOriginalCleanup()); - } + beginDrain(); + try { + boolean retained; + synchronized (lifecycleMutex) { + retained = privateResult != null; } + eraseRetainedResults(false); + if (retained) recordOriginalCleanup(); + } finally { + endDrain(); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java new file mode 100644 index 0000000000..60d5234f1d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.gamesession.websocket; + +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; +import net.firedevops.firemud.gamesession.command.text.TextCommand; +import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; +import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; +import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.WebSocketSession; + +/** Public receiving path. An unavailable protected owner never falls back to numeric authority. */ +@Component +public final class AuthenticatedDirectTextCommandReceiver { + private final AuthenticatedDirectTextSessions sessions; + private final ObjectProvider logins; + private final ObjectProvider selections; + private final ObjectProvider lobbies; + + public AuthenticatedDirectTextCommandReceiver( + AuthenticatedDirectTextSessions sessions, + ObjectProvider logins, + ObjectProvider selections, + ObjectProvider lobbies) { + this.sessions = sessions; + this.logins = logins; + this.selections = selections; + this.lobbies = lobbies; + } + + public TextCommandInterpretationResult receive(WebSocketSession socket, TextCommand command) { + try { + var connection = sessions.require(socket); + return switch (command.type()) { + case LOGIN -> { + var credentials = command.credentialsPayload().orElse(null); + if (command.args().size() != 2 + || credentials == null + || credentials.loginName() == null + || credentials.loginName().isBlank() + || credentials.password() == null + || credentials.password().isEmpty()) + yield failure("INVALID_ARGUMENT", "Usage: LOGIN "); + String email; + try { + email = EmailCanonicalization.normalize(credentials.loginName()); + } catch (IllegalArgumentException invalidEmail) { + yield failure("INVALID_ARGUMENT", "Usage: LOGIN "); + } + var owner = required(logins); + connection.login(owner, email, credentials.password().toCharArray()); + yield connection.withLogin((original, result) -> success("Logged in as " + email)); + } + case WORLDS -> { + connection.menu = required(selections).browse().orElseThrow(); + yield success(String.join("\n", connection.menu.selectors())); + } + case REALMS -> { + var request = command.realmBrowsePayload().orElse(null); + if (command.args().size() != 1 + || request == null + || request.worldSelector() == null + || request.worldSelector().isBlank()) + yield failure("INVALID_ARGUMENT", "Usage: REALMS "); + yield connection.withLogin( + (original, result) -> { + if (connection.menu == null) + return failure("INVALID_ARGUMENT", "Run WORLDS before REALMS "); + connection.selectedScope = + required(lobbies) + .realms( + original, result, connection, connection.menu, request.worldSelector()); + return success(connection.selectedScope.publicTarget().realmDisplayName()); + }); + } + case JOIN -> { + var request = command.joinRequestPayload().orElse(null); + if (command.args().size() != 1 + || request == null + || request.worldSelector() == null + || request.worldSelector().isBlank()) + yield failure("INVALID_ARGUMENT", "Usage: JOIN "); + yield connection.withLogin( + (original, result) -> { + if (connection.menu == null || connection.selectedScope == null) + return failure( + "INVALID_ARGUMENT", "Run WORLDS and REALMS before JOIN "); + var selected = + required(selections) + .resolve(connection.menu, request.worldSelector()) + .orElseThrow(); + if (!selected.equals(connection.selectedScope.publicTarget())) + return failure( + "INVALID_ARGUMENT", "Use REALMS before JOIN of a different world"); + var observation = required(lobbies).join(original, result, connection); + if (observation.status() + != DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + || observation.currentReply().isEmpty()) throw new IllegalStateException(); + return success("Joined public production realm"); + }); + } + // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the + // retired numeric entitlement route must never be selected by this protected receiver. + case PLAY -> failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); + case LOGOUT -> success("Logged out"); + default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); + }; + } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { + return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); + } catch (ExpiredWorldSelectionException expiredSelection) { + return failure( + "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); + } catch (UnknownWorldSelectorException unknownSelector) { + return failure( + "INVALID_ARGUMENT", + "Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); + } catch (AuthenticatedDirectTextSessions.LoginRejectedException rejected) { + return switch (rejected.code()) { + case AuthenticationErrorCodes.INVALID_CREDENTIALS -> + failure("INVALID_CREDENTIALS", "Invalid credentials"); + case AuthenticationErrorCodes.ACCOUNT_LOCKED -> + failure("ACCOUNT_LOCKED", "Account is locked"); + case AuthenticationErrorCodes.RETRY_LATER -> + failure("RETRY_LATER", "Too many failed attempts; try again later"); + case "IDEMPOTENCY_CONFLICT", "RESPONSE_RECOVERY_EXPIRED" -> + failure(rejected.code(), "Login rejected"); + default -> failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); + }; + } catch (RuntimeException unavailable) { + return failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); + } + } + + private static T required(ObjectProvider provider) { + T value = provider.getIfAvailable(); + if (value == null) throw new IllegalStateException("Protected owner unavailable"); + return value; + } + + private static TextCommandInterpretationResult success(String message) { + return new TextCommandInterpretationResult( + CommandEnqueueResult.success(), + List.of(PlayerOutput.message(message, "message.gameplay.received"))); + } + + private static TextCommandInterpretationResult failure(String code, String message) { + return new TextCommandInterpretationResult( + CommandEnqueueResult.failure(code, message), + List.of(PlayerOutput.error(code, message, "error.gameplay.unavailable", Map.of()))); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java new file mode 100644 index 0000000000..4b7929663a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.gamesession.websocket; + +import java.security.cert.X509Certificate; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServletServerHttpRequest; + +/** Immutable transport proof minted only from the dedicated connector's authenticated TLS peer. */ +public final class AuthenticatedDirectTextIngress { + static final String ATTRIBUTE = AuthenticatedDirectTextIngress.class.getName(); + private final ObservedDirectTextTransport transport; + private final String clientAddress; + private final UUID backendGeneration = UUID.randomUUID(); + + private AuthenticatedDirectTextIngress(ObservedDirectTextTransport transport, String address) { + this.transport = transport; + this.clientAddress = address; + } + + static AuthenticatedDirectTextIngress authenticate( + ServerHttpRequest request, int dedicatedPort, String namespace, String sessionId) { + if (!(request instanceof ServletServerHttpRequest servlet) + || !servlet.getServletRequest().isSecure() + || servlet.getServletRequest().getLocalPort() != dedicatedPort + || !"/ws/game/tcp".equals(request.getURI().getPath()) + || !GrpcPeerIdentity.isValidNamespace(namespace)) throw unavailable(); + Object value = + servlet.getServletRequest().getAttribute("jakarta.servlet.request.X509Certificate"); + if (!(value instanceof X509Certificate[] chain) || chain.length == 0) throw unavailable(); + try { + chain[0].checkValidity(); + if (chain[0].getExtendedKeyUsage() == null + || !chain[0].getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.2") + || GrpcPeerIdentity.fromCertificate(chain[0]) + .filter( + peer -> peer.isService("spring-cloud-gateway") && peer.isInNamespace(namespace)) + .isEmpty()) throw unavailable(); + } catch (java.security.cert.CertificateException invalid) { + throw unavailable(); + } + var headers = request.getHeaders(); + String address = singleHeader(headers, "X-Client-IP"); + String proxyConnectionId = singleHeader(headers, "X-Proxy-Connection-Id"); + String mode = singleHeader(headers, "X-Firemud-Connection-Mode"); + if (address.length() > 64 + || address.contains("%") + || !address.matches("[0-9a-fA-F:.]+") + || !"trusted_tcp_proxy".equals(mode) + || headers.containsHeader("X-Firemud-Transport-Session-Id") + || headers.containsHeader("X-Firemud-Connect-Context")) throw unavailable(); + String canonicalAddress = java.net.InetAddress.ofLiteral(address).getHostAddress(); + var observed = + ObservedDirectTextTransport.fromHandshake(mode, sessionId, proxyConnectionId) + .orElseThrow(AuthenticatedDirectTextIngress::unavailable); + return new AuthenticatedDirectTextIngress(observed, canonicalAddress); + } + + private static String singleHeader(org.springframework.http.HttpHeaders headers, String name) { + var values = headers.get(name); + if (values == null || values.size() != 1) throw unavailable(); + String value = values.getFirst(); + if (value == null) throw unavailable(); + return value; + } + + public ObservedDirectTextTransport transport() { + return transport; + } + + public String clientAddress() { + return clientAddress; + } + + public UUID backendGeneration() { + return backendGeneration; + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Authenticated Gateway TCP provenance required"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java new file mode 100644 index 0000000000..ea5812f051 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.gamesession.websocket; + +import jakarta.annotation.PreDestroy; +import java.io.IOException; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.BiFunction; +import java.util.function.Function; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCredentialPresentation; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketSession; + +/** + * Exact live backend-generation custody. Numeric session IDs and SQL observations cannot mint it. + */ +@Component +public final class AuthenticatedDirectTextSessions { + private static final String ATTRIBUTE = AuthenticatedDirectTextSessions.class.getName(); + private static final CloseStatus GENERATION_CLOSED = + new CloseStatus(1012, "backend_generation_closed"); + private final Map current = new ConcurrentHashMap<>(); + private final Object lifecycleMonitor = new Object(); + private boolean shuttingDown; + + @PreDestroy + public void closeAll() { + java.util.List connections; + synchronized (lifecycleMonitor) { + connections = java.util.List.copyOf(current.values()); + connections.forEach(Connection::requireExternalLifecycle); + shuttingDown = true; + current.clear(); + } + connections.forEach(connection -> connection.close(GENERATION_CLOSED)); + } + + public void open(WebSocketSession socket) { + var ingress = ingress(socket); + Connection replacement; + synchronized (lifecycleMonitor) { + if (shuttingDown) throw unavailable(); + replacement = + current.compute( + ingress.transport().transportSessionId(), + (id, previous) -> { + if (previous != null) previous.requireExternalLifecycle(); + Connection next = new Connection(socket, ingress, previous); + socket.getAttributes().put(ATTRIBUTE, next); + return next; + }); + } + replacement.drainPredecessor(); + if (current.get(ingress.transport().transportSessionId()) == replacement && socket.isOpen()) + replacement.live.set(true); + else replacement.close(GENERATION_CLOSED); + } + + public Connection require(WebSocketSession socket) { + Object value = socket.getAttributes().get(ATTRIBUTE); + if (!(value instanceof Connection connection) + || connection.socket != socket + || current.get(connection.ingress.transport().transportSessionId()) != connection) + throw unavailable(); + connection.requireLive(); + return connection; + } + + public void close(WebSocketSession socket, CloseStatus status) { + Objects.requireNonNull(status, "Close status required"); + Object value = socket.getAttributes().get(ATTRIBUTE); + if (value instanceof Connection connection && connection.socket == socket) { + connection.requireExternalLifecycle(); + current.remove(connection.ingress.transport().transportSessionId(), connection); + connection.close(status); + } + } + + private static AuthenticatedDirectTextIngress ingress(WebSocketSession socket) { + Object value = socket.getAttributes().get(AuthenticatedDirectTextIngress.ATTRIBUTE); + if (!(value instanceof AuthenticatedDirectTextIngress ingress)) throw unavailable(); + return ingress; + } + + public final class Connection implements DirectTextAuthenticatedLobbyCustody { + private final WebSocketSession socket; + private final AuthenticatedDirectTextIngress ingress; + private volatile Connection predecessor; + private final ReentrantReadWriteLock lifetime = new ReentrantReadWriteLock(true); + private final AtomicBoolean live = new AtomicBoolean(); + private final AtomicBoolean closing = new AtomicBoolean(); + private final CountDownLatch drained = new CountDownLatch(1); + private volatile Thread closingThread; + private final Map borrowed = new ConcurrentHashMap<>(); + private volatile InitialGameplayLoginCredentialPresentation credentials; + private volatile InitialGameplayLoginOwner.Outcome outcome; + DirectTextWorldSelectionService.SelectionSnapshot menu; + DirectTextAuthenticatedLobbyScope selectedScope; + + private Connection( + WebSocketSession socket, AuthenticatedDirectTextIngress ingress, Connection predecessor) { + this.socket = socket; + this.ingress = ingress; + this.predecessor = predecessor; + } + + /** Each original outcome is installed only on the exact still-live receiving connection. */ + public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSecret) { + if (!lifetime.writeLock().tryLock()) { + java.util.Arrays.fill(ownedSecret, '\0'); + throw unavailable(); + } + try { + requireLive(); + if (outcome != null) { + outcome.close(); + outcome = null; + } + menu = null; + selectedScope = null; + credentials = + InitialGameplayLoginCredentialPresentation.fromAuthenticatedTcp( + ingress, email, ownedSecret); + requireLive(); + InitialGameplayLoginOwner.Outcome received = + Objects.requireNonNull(owner).receive(credentials); + credentials = null; + if (received.status() != InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING) { + String failureCode = received.failureCode().orElse("UNAVAILABLE"); + received.close(); + throw new LoginRejectedException(failureCode); + } + outcome = received; + requireLive(); + } finally { + java.util.Arrays.fill(ownedSecret, '\0'); + if (credentials != null) { + credentials.close(); + credentials = null; + } + if (!live.get() && outcome != null) outcome.close(); + lifetime.writeLock().unlock(); + } + } + + /** Borrows the genuine installed result and pins this exact transport for the entire action. */ + public T withLogin( + BiFunction + action) { + lifetime.readLock().lock(); + try { + requireLive(); + InitialGameplayLoginOwner.Outcome owned = outcome; + if (owned == null) throw new LoginRequiredException(); + return owned.withOwnedPrivateResult( + result -> { + if (borrowed.putIfAbsent(Thread.currentThread(), result) != null) throw unavailable(); + try { + requireLive(); + T answer = action.apply(owned.coordinates(), result); + requireLive(); + return answer; + } finally { + borrowed.remove(Thread.currentThread(), result); + } + }); + } finally { + lifetime.readLock().unlock(); + } + } + + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult borrowedResult, + Function action) { + requireLive(); + if (borrowed.get(Thread.currentThread()) != borrowedResult + || outcome == null + || !outcome.coordinates().equals(original)) throw unavailable(); + T answer = Objects.requireNonNull(action).apply(ingress.transport()); + requireLive(); + return answer; + } + + public boolean isCurrent() { + return live.get() + && !closing.get() + && socket.isOpen() + && current.get(ingress.transport().transportSessionId()) == this; + } + + private void requireLive() { + if (!isCurrent()) throw unavailable(); + } + + private void close(CloseStatus status) { + requireExternalLifecycle(); + if (!closing.compareAndSet(false, true)) { + while (closingThread == null) Thread.onSpinWait(); + if (closingThread == Thread.currentThread()) return; + boolean interrupted = false; + while (true) { + try { + drained.await(); + break; + } catch (InterruptedException interruption) { + interrupted = true; + } + } + if (interrupted) Thread.currentThread().interrupt(); + return; + } + closingThread = Thread.currentThread(); + live.set(false); + var presentation = credentials; + if (presentation != null) presentation.close(); + try { + drainPredecessor(); + lifetime.writeLock().lock(); + try { + if (outcome != null) outcome.close(); + outcome = null; + menu = null; + selectedScope = null; + } finally { + lifetime.writeLock().unlock(); + } + try { + if (socket.isOpen()) socket.close(status); + } catch (IOException ignored) { + // Custody was already revoked and drained before the best-effort transport close. + } + } finally { + drained.countDown(); + } + } + + private void requireExternalLifecycle() { + for (Connection retained = this; retained != null; retained = retained.predecessor) { + if (retained.lifetime.getReadHoldCount() > 0 + || retained.lifetime.isWriteLockedByCurrentThread()) throw unavailable(); + } + } + + private void drainPredecessor() { + var previous = predecessor; + if (previous != null) { + previous.close(GENERATION_CLOSED); + predecessor = null; + } + } + } + + /** A live connection has not installed a LOGIN result; this grants no custody or authority. */ + static final class LoginRequiredException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + private LoginRequiredException() { + super("LOGIN is required on this live connection"); + } + } + + static final class LoginRejectedException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String code; + + private LoginRejectedException(String code) { + super("Authenticated gameplay LOGIN was rejected"); + this.code = code; + } + + String code() { + return code; + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Current authenticated TCP LOGIN custody is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java new file mode 100644 index 0000000000..79d832fb04 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.gamesession.websocket; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import org.apache.catalina.connector.Connector; +import org.apache.commons.logging.LogFactory; +import org.apache.coyote.http11.AbstractHttp11Protocol; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.tomcat.SslConnectorCustomizer; +import org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory; +import org.springframework.boot.web.server.Ssl; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.OncePerRequestFilter; + +/** Dedicated internal mTLS connector; the ordinary HTTP connector cannot produce TCP custody. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.gameplay.authenticated-listener", + name = "enabled", + havingValue = "true") +public class AuthenticatedGameplayListenerConfiguration { + @Bean + Filter authenticatedGameplayPathFilter( + @Value("${firemud.gameplay.authenticated-listener.port:8444}") int port) { + return new OncePerRequestFilter() { + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (request.getLocalPort() == port && !"/ws/game/tcp".equals(request.getRequestURI())) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + chain.doFilter(request, response); + } + }; + } + + @Bean + WebServerFactoryCustomizer authenticatedGameplayConnector( + SslBundles bundles, + @Value("${firemud.gameplay.authenticated-listener.port:8444}") int port, + @Value("${server.port:8080}") int publicPort) { + if (port <= 0 || port > 65535 || port == publicPort) + throw new IllegalArgumentException("Distinct internal gameplay TLS port required"); + return factory -> { + Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); + connector.setPort(port); + connector.setScheme("https"); + connector.setSecure(true); + ((AbstractHttp11Protocol) connector.getProtocolHandler()).setSSLEnabled(true); + SslConnectorCustomizer tls = + new SslConnectorCustomizer( + LogFactory.getLog(AuthenticatedGameplayListenerConfiguration.class), + connector, + Ssl.ClientAuth.NEED); + tls.customize(bundles.getBundle("firemud-grpc"), Map.of()); + bundles.addBundleUpdateHandler("firemud-grpc", bundle -> tls.update(null, bundle)); + factory.addAdditionalConnectors(connector); + }; + } +} 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 f0cf4f8156..051caf713f 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 @@ -77,6 +77,15 @@ public class GameSessionWebSocketHandler extends TextWebSocketHandler { private final RuntimeIdentity runtimeIdentity; private final TextCommandParser parser; private final TextCommandMetadataResolver textCommandMetadataResolver; + private AuthenticatedDirectTextSessions authenticatedSessions; + private AuthenticatedDirectTextCommandReceiver authenticatedReceiver; + + @Autowired + void authenticatedDirectTextReceiving( + AuthenticatedDirectTextSessions sessions, AuthenticatedDirectTextCommandReceiver receiver) { + authenticatedSessions = sessions; + authenticatedReceiver = receiver; + } public GameSessionWebSocketHandler( TextCommandInterpreter interpreter, @@ -155,6 +164,10 @@ public GameSessionWebSocketHandler( @Override public void afterConnectionEstablished(WebSocketSession session) { + if (authenticatedDirectText(session)) { + authenticatedSessions.open(session); + return; + } try (CombinedLoggingContext ignored = openLoggingContext(session)) { logger.debug( "WebSocket session {} established with sessionId={} tenantId={}", @@ -175,6 +188,10 @@ public void afterConnectionEstablished(WebSocketSession session) { @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { + if (authenticatedDirectText(session)) { + authenticatedSessions.close(session, status); + return; + } parseNumericSessionId(resolveTransportSessionId(session)) .ifPresent( sessionId -> { @@ -191,6 +208,27 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { + if (authenticatedDirectText(session)) { + TextCommand command = parser.parse(message.getPayload()); + if (command.type() == TextCommandType.NOOP) return; + var interpretation = authenticatedReceiver.receive(session, command); + try { + sendProtocolMessage( + session, + outputProjector.projectCommandResponse( + session, + command, + interpretation, + interpretation.outputs(), + resolveLocaleTag(session), + settingsResolver.presentation(null), + null)); + } finally { + if (command.type() == TextCommandType.LOGOUT) + authenticatedSessions.close(session, new CloseStatus(1000, "logout")); + } + return; + } // Check ownership before logging-context projection can read or normalize incumbent state. if ("first_party_web".equals(resolveConnectionMode(session)) && !ownsActiveTransport(resolveTransportSessionId(session), session)) { @@ -260,6 +298,18 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) } } + @Override + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { + if (authenticatedDirectText(session)) + authenticatedSessions.close(session, new CloseStatus(1011, "internal_error")); + super.handleTransportError(session, exception); + } + + private boolean authenticatedDirectText(WebSocketSession session) { + return session.getAttributes().get(AuthenticatedDirectTextIngress.ATTRIBUTE) + instanceof AuthenticatedDirectTextIngress; + } + private boolean parseSoloTick(WebSocketSession session) { Object cached = session.getAttributes().get(GameSessionWebSocketHandshakeInterceptor.SOLO_TICK_ATTR); 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 cd33e18e16..6e6ba724cf 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 @@ -6,7 +6,9 @@ import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.Map; -import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.stereotype.Component; @@ -17,6 +19,24 @@ /** Copies required request headers into stable WebSocket session attributes during upgrade. */ @Component public class GameSessionWebSocketHandshakeInterceptor implements HandshakeInterceptor { + private final boolean authenticatedListenerEnabled; + private final int authenticatedPort; + private final String namespace; + + public GameSessionWebSocketHandshakeInterceptor() { + this(false, 8444, ""); + } + + @Autowired + public GameSessionWebSocketHandshakeInterceptor( + @Value("${firemud.gameplay.authenticated-listener.enabled:false}") boolean enabled, + @Value("${firemud.gameplay.authenticated-listener.port:8444}") int port, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + authenticatedListenerEnabled = enabled; + authenticatedPort = port; + this.namespace = namespace; + } + static final String GAME_INSTANCE_HEADER = "X-Game-Instance-Id"; static final String PROXY_CONNECTION_HEADER = "X-Proxy-Connection-Id"; static final String TENANT_HEADER = "X-Tenant-Id"; @@ -56,17 +76,26 @@ public boolean beforeHandshake( bootstrapGameInstanceId, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); attributes.put(SESSION_ID_ATTR, sessionId); + attributes.remove(AuthenticatedDirectTextIngress.ATTRIBUTE); attributes.remove(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + boolean tcp = "trusted_tcp_proxy".equals(request.getHeaders().getFirst(CONNECTION_MODE_HEADER)); + if (tcp || "/ws/game/tcp".equals(request.getURI().getPath())) { + try { + if (!authenticatedListenerEnabled) + throw new IllegalArgumentException("Listener unavailable"); + var ingress = + AuthenticatedDirectTextIngress.authenticate( + request, authenticatedPort, namespace, sessionId); + attributes.put(AuthenticatedDirectTextIngress.ATTRIBUTE, ingress); + attributes.put(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, ingress.transport()); + } catch (IllegalArgumentException unavailable) { + response.setStatusCode(HttpStatus.FORBIDDEN); + return false; + } + } boolean firstParty = "first_party_web".equals(request.getHeaders().getFirst(CONNECTION_MODE_HEADER)) || StringUtils.hasText(request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); - if (!firstParty) { - ObservedDirectTextTransport.fromHandshake( - request.getHeaders().getFirst(CONNECTION_MODE_HEADER), - sessionId, - request.getHeaders().getFirst(PROXY_CONNECTION_HEADER)) - .ifPresent(value -> attributes.put(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, value)); - } if (firstParty) { attributes.put(CONNECTION_MODE_ATTR, "first_party_web"); attributes.put(CONNECT_CONTEXT_ATTR, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); 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 90fdfd7209..3db0c1bf41 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 @@ -62,31 +62,47 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; 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.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountPublicJwksCache; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; 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.CanonicalGameplayIssuerTestFixtures; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -101,6 +117,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; @@ -109,7 +126,9 @@ /** * Physical standalone AOF primary/replica, scoped ACL and PostgreSQL journal proof. Fresh PENDING - * records are seeded exclusively by the test administrator: no trusted producer is established. + * records use administrator seeding or the actual unregistered LOGIN owner in named compositions; + * no trusted ingress producer is established. Lobby routing, transport and Account scope replies + * remain controlled, without authenticated ingress or reset/replacement qualification. * Qualification is stipulated by the controlled external-authority fixture, including exclusion * through Account continuation; this is not genuine restore/promotion qualification, Cluster, TLS, * deployed custody, authenticated Account transport or LOGIN activation proof. ACK-loss injection @@ -174,6 +193,7 @@ class InitialGameplayLoginContextRedisIntegrationTest { private StatefulRedisConnection adminConnection; private RedisCommands admin; private String schema; + private DriverManagerDataSource journalDataSource; private InitialGameplayLoginCoordinationJournalRepository journal; @BeforeAll @@ -859,6 +879,363 @@ void originalClosureCannotCreateAbsentOrTouchReplacementAndNewContext(String con .containsExactly(InitialGameplayLoginContextState.pending(newContext).encode()); } + @Test + void installedOwnerBorrowsGenuineResultIntoRetainedNonAdmittingLobbyScope() throws Exception { + var fixture = installedLobbyFixture(() -> {}); + try (var installed = fixture.installed()) { + var scope = fixture.realms(); + var original = installed.coordinates(); + assertThat(fixture.repository().readCommittedScope(scope).encode()) + .containsExactly(scope.encode()); + assertThat(scope.original()).isEqualTo(original); + assertThat(scope.evidence()).isEqualTo(fixture.result().evidence()); + assertThat(scope.transport()).isEqualTo(fixture.transport()); + assertThat(admin.get(key(original))) + .containsExactly( + InitialGameplayLoginContextState.installed(original, fixture.result()).encode()); + assertThat(journal.readCommitted(original).orElseThrow().verifiedWitness()) + .contains(witness(fixture.result())); + byte[] token = fixture.result().compactJwtBytes(); + try { + assertThat(containsSequence(scope.encode(), token)).isFalse(); + assertThat(containsSequence(admin.get(key(original)), token)).isFalse(); + assertThat(new String(scope.encode(), StandardCharsets.UTF_8)) + .doesNotContain("fixture-transient-secret"); + } finally { + Arrays.fill(token, (byte) 0); + } + assertThat(installed.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + } + assertThatThrownBy(() -> fixture.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void actualInstalledBorrowExcludesCleanupUntilLobbyReadbackAndRefusesLaterBorrow() + throws Exception { + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var closing = new CountDownLatch(1); + var fixture = + installedLobbyFixture( + () -> { + entered.countDown(); + awaitLobby(release); + }); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowing = executor.submit(fixture::realms); + try { + assertThat(entered.await(10, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + fixture.installed().close(); + }); + assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + release.countDown(); + var scope = borrowing.get(15, TimeUnit.SECONDS); + closed.get(15, TimeUnit.SECONDS); + assertThat(fixture.repository().readCommittedScope(scope).encode()) + .containsExactly(scope.encode()); + assertThat( + journal.readCommitted(fixture.installed().coordinates()).orElseThrow().abandoned()) + .isTrue(); + assertThat(admin.get(key(fixture.installed().coordinates()))) + .containsExactly( + InitialGameplayLoginContextState.closed(fixture.installed().coordinates()) + .encode()); + assertThat( + journal + .readCommitted(fixture.installed().coordinates()) + .orElseThrow() + .frozenRetirementRequest()) + .contains( + InitialGameplayLoginJournalSnapshot.request( + fixture.installed().coordinates(), witness(fixture.result()))); + assertThat(fixture.installed().custodyLossCleanup()).isPresent(); + assertThatThrownBy(fixture::realms).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + verify(fixture.lobbyAccount()).issueDirectTextConnectScope(any(), any()); + } finally { + release.countDown(); + } + } finally { + fixture.installed().close(); + } + } + + @Test + void sqlRowThenResultReadProgressesWhileBorrowWaitsForRowAndCloseDrains() throws Exception { + var fixture = installedLobbyFixture(() -> {}); + var scope = fixture.realms(); + var rowLocked = new CountDownLatch(1); + var borrowEntered = new CountDownLatch(1); + var readResult = new CountDownLatch(1); + var closing = new CountDownLatch(1); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(journalDataSource)); + transaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + try (var executor = Executors.newFixedThreadPool(3)) { + var rowOwner = + executor.submit( + () -> + transaction.execute( + status -> { + fixture + .repository() + .verifyOriginal(fixture.installed().coordinates(), fixture.result()); + rowLocked.countDown(); + awaitLobby(readResult); + // This is the actual repository ordering: original SQL row, then live + // result bytes. + scope.requireCurrent( + fixture.installed().coordinates(), + fixture.result(), + fixture.transport(), + CLOCK); + // Neither drain waiting nor cleanup may hold the Outcome monitor across SQL + // work. + assertThat(fixture.installed().custodyLossCleanup()).isEmpty(); + return true; + })); + try { + boolean locked = rowLocked.await(10, TimeUnit.SECONDS); + if (!locked) rowOwner.get(1, TimeUnit.SECONDS); // Surface an early owner failure. + assertThat(locked).isTrue(); + var borrowing = + executor.submit( + () -> + fixture + .installed() + .withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(fixture.result()); + borrowEntered.countDown(); + return transaction.execute( + status -> { + DSL.using( + new TransactionAwareDataSourceProxy(journalDataSource), + SQLDialect.POSTGRES) + .execute("SET LOCAL lock_timeout = '5s'"); + return fixture + .repository() + .current( + fixture.installed().coordinates(), + result, + fixture.transport(), + CLOCK); + }); + })); + assertThat(borrowEntered.await(10, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + fixture.installed().close(); + }); + assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + readResult.countDown(); + assertThat(rowOwner.get(15, TimeUnit.SECONDS)).isTrue(); + assertThat(borrowing.get(15, TimeUnit.SECONDS).encode()).containsExactly(scope.encode()); + closed.get(15, TimeUnit.SECONDS); + assertThat( + journal.readCommitted(fixture.installed().coordinates()).orElseThrow().abandoned()) + .isTrue(); + } finally { + readResult.countDown(); + } + } finally { + fixture.installed().close(); + } + } + + /** + * Actual LOGIN installation and lobby storage, with controlled Account, routing and transport. + */ + private LobbyFixture installedLobbyFixture(Runnable duringScopeCall) throws Exception { + var contexts = + client( + new TracedProvider(writer), + new ControlledAuthority(), + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); + var account = mock(CanonicalGameplayLoginAccountClient.class); + var cleanup = cleanup(contexts, account); + var result = new AtomicReference(); + when(account.retireInitialGameplayLogin(any())) + .thenAnswer( + call -> { + var request = + call.getArgument( + 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + return new InitialGameplayLoginDisposalResult( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getCallerContextId()), + UUID.randomUUID(), + Disposition.PENDING, + ProofKind.NONE); + }); + when(account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + call -> { + var value = + validatedResult( + call.getArgument(0, AuthenticateRequest.class), UUID.randomUUID()); + result.set(value); + return value; + }); + var installed = + new InitialGameplayLoginOwner(contexts, cleanup, account) + .receive( + new InitialGameplayLoginCredentialPresentation( + "player@example.test", + "203.0.113.10", + "fixture-transient-secret".toCharArray())); + ownedKeys.add( + InitialGameplayLoginContextRedisKeys.contextKey(installed.coordinates().callerContextId())); + assertThat(installed.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + var target = lobbyTarget(); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(target)); + when(routes.readCurrentTarget(target)).thenReturn(target); + var world = + new WorldView( + target.worldSlug(), + target.worldDisplayName(), + List.of( + new RealmView( + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + true, + true, + false, + target.playableStateScope(), + target.characterCreationPolicy(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId()))); + var selection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldSupplier(() -> List.of(world)), routes, CLOCK); + var repository = + new DirectTextAuthenticatedLobbyRepository( + DSL.using(new TransactionAwareDataSourceProxy(journalDataSource), SQLDialect.POSTGRES)); + var lobbyAccount = mock(AccountClient.class); + when(lobbyAccount.issueDirectTextConnectScope(any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + duringScopeCall.run(); + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("controlled-scope") + .setEvaluatedAt(CLOCK.instant().minusSeconds(1).toString()) + .setConnectScopeExpiresAt(CLOCK.instant().plusSeconds(60).toString()) + .build(); + }); + return new LobbyFixture( + installed, + result.get(), + new ObservedDirectTextTransport("00042", UUID.randomUUID()), + new DirectTextAuthenticatedLobbyOwner( + repository, + selection, + lobbyAccount, + new DataSourceTransactionManager(journalDataSource), + CLOCK), + repository, + selection, + lobbyAccount); + } + + /** + * Transport is deliberately controlled; this fixture is not an authenticated ingress producer. + */ + private record LobbyFixture( + InitialGameplayLoginOwner.Outcome installed, + CanonicalGameplayLoginResult result, + ObservedDirectTextTransport transport, + DirectTextAuthenticatedLobbyOwner lobby, + DirectTextAuthenticatedLobbyRepository repository, + DirectTextWorldSelectionService selection, + AccountClient lobbyAccount) { + DirectTextAuthenticatedLobbyScope realms() { + return installed.withOwnedPrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + var custody = + new DirectTextAuthenticatedLobbyCustody() { + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult candidate, + Function action) { + assertThat(original).isEqualTo(installed.coordinates()); + assertThat(candidate).isSameAs(borrowed); + return action.apply(transport); + } + }; + return lobby.realms( + installed.coordinates(), borrowed, custody, selection.browse().orElseThrow(), "1"); + }); + } + } + + private static void awaitLobby(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Controlled lobby gate timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled lobby gate interrupted", failure); + } + } + + private static CanonicalPlayableTarget lobbyTarget() { + return new CanonicalPlayableTarget( + "gameplay", + "studio", + UUID.randomUUID(), + "forest", + "Forest", + UUID.randomUUID(), + "public", + "Live", + 101, + 202, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303, + 1, + 7, + "d".repeat(64), + 82, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + CLOCK.instant().minusSeconds(1), + "ALLOW_NEW"); + } + private InitialGameplayLoginCleanupOwner cleanup( InitialGameplayLoginContextRedisClient client, CanonicalGameplayLoginAccountClient account) { schema = "gs_context_" + UUID.randomUUID().toString().replace("-", ""); @@ -866,6 +1243,7 @@ private InitialGameplayLoginCleanupOwner cleanup( new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); dataSource.setSchema(schema); + journalDataSource = dataSource; CanonicalGameplayIssuerTestFixtures.migrateSchema( dataSource, schema, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java index 0c778a8049..14050a4939 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; @@ -169,6 +170,10 @@ public InitialGameplayLoginAttemptCoordinates coordinates() { } /** The actual owner outcome, retained for explicit pre-admission custody-loss cleanup. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The fixture deliberately shares its identical live Outcome for exact-original cleanup; copying or reconstructing it would lose the owned lifecycle obligation.") public InitialGameplayLoginOwner.Outcome outcome() { return outcome; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java index 987d2e10e5..15968f9f4f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java @@ -201,7 +201,8 @@ void expiredRetainedHandleCannotUseTheFreshDiscoveryPath() { clearInvocations(commands, connection, routes); assertThat(localStore.reassert(transport, menu)).isFalse(); - assertThat(localSelection.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> localSelection.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); assertThat(stored.get()).isEqualTo(original); verifyNoInteractions(commands, connection, routes); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index f1bd561f5d..9177c00339 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -82,7 +82,12 @@ void historicalEncodingRemainsClockIndependentWhileRestorationAndResolutionRefus assertThat(foreignOwner.encodeSnapshot(menu)).isEmpty(); assertThat(source.encodeSnapshot(null)).isEmpty(); assertThat(source.restoreSnapshot(original)).isEmpty(); - assertThat(source.resolve(menu, "1")).isEmpty(); + if (expired) { + assertThatThrownBy(() -> source.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + } else { + assertThat(source.resolve(menu, "1")).isEmpty(); + } assertThat(reads.get()).isEqualTo(2); verifyNoInteractions(reader); } @@ -120,7 +125,8 @@ void restoresAcrossInstancesWithOriginalOrderOwnershipAndDeadline() { clearInvocations(reader); clock.now = NOW.plusSeconds(300); assertThat(replacement.restoreSnapshot(stored)).isEmpty(); - assertThat(replacement.resolve(restored, "1")).isEmpty(); + assertThatThrownBy(() -> replacement.resolve(restored, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); verifyNoInteractions(reader); } @@ -388,9 +394,14 @@ void pairsAreCaseFoldedAndBareTenantRequiresExactlyOneSnapshotWorld() { assertThat(service.resolve(menu, "STUDIO/FOREST")).contains(first); assertThat(service.resolve(menu, "studio/other-world")).contains(sameFriendlyTenant); - assertThat(service.resolve(menu, "studio")).isEmpty(); - assertThat(service.resolve(menu, "forest")).isEmpty(); - assertThat(service.resolve(menu, "other-world")).isEmpty(); + clearInvocations(reader); + assertThatThrownBy(() -> service.resolve(menu, "studio")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + assertThatThrownBy(() -> service.resolve(menu, "forest")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + assertThatThrownBy(() -> service.resolve(menu, "other-world")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + verifyNoInteractions(reader); var single = service(List.of(world(first)), List.of(first)); assertThat(single.resolve(single.browse().orElseThrow(), "STUDIO")).contains(first); @@ -426,7 +437,12 @@ void invalidSelectorsDoNotReadSources(String selector) { clearInvocations(reader); int before = catalogReads.get(); - assertThat(service.resolve(menu, selector)).isEmpty(); + if (selector.isBlank()) { + assertThat(service.resolve(menu, selector)).isEmpty(); + } else { + assertThatThrownBy(() -> service.resolve(menu, selector)) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + } assertThat(service.resolve(menu, null)).isEmpty(); assertThat(service.resolve(null, "1")).isEmpty(); assertThat(catalogReads.get()).isEqualTo(before); @@ -447,7 +463,8 @@ void bareTenantSelectionNeverFallsBackToAnotherTenantsWorldSlug() { assertThat(service.resolve(menu, "forest")).containsSame(tenantNamedLikeFirstWorld); assertThat(service.resolve(menu, "studio/forest")).containsSame(first); assertThat(service.resolve(menu, "forest/other-world")).containsSame(tenantNamedLikeFirstWorld); - assertThat(service.resolve(menu, "other-world")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "other-world")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); } @Test @@ -468,8 +485,10 @@ void retainedOrdinalCannotBeSilentlyUpgradedToANewCatalogRevision() { assertThat(service.resolve(refreshed, "1")).containsSame(revised); clock.now = NOW.plusSeconds(300); clearInvocations(reader); - assertThat(service.resolve(oldMenu, "1")).isEmpty(); - assertThat(service.resolve(refreshed, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(oldMenu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + assertThatThrownBy(() -> service.resolve(refreshed, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); verifyNoInteractions(reader); } @@ -544,13 +563,34 @@ void expiryIsExclusiveAtFiveMinutesAndExpiredSelectionsHaveNoSourceEffects() { int before = catalogReads.get(); clock.now = NOW.plusSeconds(300); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); clock.now = NOW.plusSeconds(301); - assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "studio/forest")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); assertThat(catalogReads.get()).isEqualTo(before); verifyNoInteractions(reader); } + @Test + void expiryOutcomeRequiresTheExactOwnerAndDoesNotClassifyFutureMenusAsExpired() { + var first = target(""); + var catalog = GameplayWorldCatalog.forWorldViews(List.of(world(first))); + var service = service(catalog, List.of(first)); + var menu = service.browse().orElseThrow(); + var foreignOwner = service(catalog, List.of(first)); + clearInvocations(reader); + + clock.now = menu.expiresAt(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + assertThat(foreignOwner.resolve(menu, "1")).isEmpty(); + + clock.now = NOW.minusNanos(1); + assertThat(service.resolve(menu, "1")).isEmpty(); + verifyNoInteractions(reader); + } + @Test void expiryIsRecheckedAfterCanonicalAndCatalogReads() { var first = target(""); @@ -572,9 +612,9 @@ void expiryIsRecheckedAfterCanonicalAndCatalogReads() { }); assertThat(service.resolve(menu, "1")).isEmpty(); - clock.now = NOW; when(reader.readCurrentTarget(first)).thenReturn(first); onCatalogRead.set(() -> clock.now = NOW.plusSeconds(300)); + clock.now = NOW; assertThat(service.resolve(menu, "1")).isEmpty(); } @@ -769,7 +809,8 @@ void canonicalTargetsNeverRestoreCatalogCollisionCardinalityOrHiddenRowOmissions when(authority.listPointers()).thenReturn(pointers); var menu = service.browse().orElseThrow(); assertThat(menu.selectors()).isEmpty(); - assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "studio/forest")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); } } 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 3048066146..4453778fb0 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 @@ -22,6 +22,11 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -117,6 +122,104 @@ void closeOverwritesOwnedCompactTokenAndRefusesFurtherSecretAccess() throws Exce assertThat(result.evidence().accountId()).isEqualTo(ACCOUNT); } + @Test + void liveBorrowPreservesExactIdentityRefusesReentrancyAndReleasesAfterCallbackFailure() + throws Exception { + var result = decode(response(claims())); + assertThat( + result.withLivePrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + assertThatThrownBy(borrowed::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> borrowed.withLivePrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return borrowed.compactJwtBytes().length; + })) + .isPositive(); + assertThatThrownBy( + () -> + result.withLivePrivateResult( + borrowed -> { + throw new IllegalStateException("controlled callback failure"); + })) + .hasMessage("controlled callback failure"); + result.close(); + assertThatThrownBy(() -> result.withLivePrivateResult(borrowed -> true)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void directCloseDrainsAllBorrowersWithoutHoldingResultMonitorAndThenErasesBytes() + throws Exception { + var wire = response(claims()); + var result = decode(wire); + var field = CanonicalGameplayLoginResult.class.getDeclaredField("compactJwt"); + field.setAccessible(true); + byte[] owned = (byte[]) field.get(result); + byte[] expected = wire.getAuthToken().getBytes(StandardCharsets.US_ASCII); + var entered = new CountDownLatch(2); + var release = new CountDownLatch(1); + var closingThread = new AtomicReference(); + try (var executor = Executors.newFixedThreadPool(3)) { + var first = executor.submit(() -> borrowUntilReleased(result, entered, release, expected)); + var second = executor.submit(() -> borrowUntilReleased(result, entered, release, expected)); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var closing = + executor.submit( + () -> { + closingThread.set(Thread.currentThread()); + result.close(); + }); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (closingThread.get() == null + || closingThread.get().getState() != Thread.State.WAITING) { + if (System.nanoTime() >= deadline) throw new IllegalStateException("Close did not drain"); + Thread.sleep(1); + } + assertThatThrownBy(() -> result.withLivePrivateResult(borrowed -> true)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(result::compactJwtBytes).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> closing.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + assertThat(owned).containsExactly(expected); + release.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS)).isTrue(); + assertThat(second.get(5, TimeUnit.SECONDS)).isTrue(); + closing.get(5, TimeUnit.SECONDS); + assertThat(owned).containsOnly((byte) 0); + result.close(); + } finally { + release.countDown(); + } + } finally { + Arrays.fill(expected, (byte) 0); + result.close(); + } + } + + private static boolean borrowUntilReleased( + CanonicalGameplayLoginResult result, + CountDownLatch entered, + CountDownLatch release, + byte[] expected) { + return result.withLivePrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Borrow timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Borrow interrupted", failure); + } + // Reads must still progress while close waits for this callback's pin. + assertThat(borrowed.compactJwtBytes()).containsExactly(expected); + return true; + }); + } + @ParameterizedTest @ValueSource( strings = { 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 index aa3b50cc4e..5d78317387 100644 --- 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 @@ -1,19 +1,31 @@ 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.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.spy; +import static org.mockito.Mockito.times; 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.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; @@ -23,6 +35,8 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InOrder; /** Source ordering and owned-buffer proof; no Account, Redis, wire, or admission claim. */ @@ -112,17 +126,342 @@ void transferredResultAndOutcomeCloseLeaveCleanupOwnershipToExplicitLossCallback verify(success.fixture().cleanup).abandonAndRetire(coordinates); } + @Test + void ownedBorrowPinsExactResultAndRefusesReentrantLifecycleChanges() { + var success = successfulOutcome(); + var outcome = success.outcome(); + var value = + outcome.withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(success.result()); + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(result::close).isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + assertThatThrownBy(outcome::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(outcome::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return "non-admitting"; + }); + assertThat(value).isEqualTo("non-admitting"); + assertThat(success.result().compactJwtBytes()).isNotEmpty(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + org.mockito.Mockito.clearInvocations(success.result()); + outcome.close(); + verify(success.result()).close(); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void callbackFailureReleasesBorrowWithoutTransferringOrRetiringTheResult() { + var success = successfulOutcome(); + var outcome = success.outcome(); + assertThatThrownBy( + () -> + outcome.withOwnedPrivateResult( + result -> { + throw new IllegalStateException("controlled callback failure"); + })) + .hasMessage("controlled callback failure"); + assertThat(outcome.withOwnedPrivateResult(result -> result == success.result())) + .isTrue(); + assertThat(outcome.takePrivateResult()).containsSame(success.result()); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + outcome.abandonOriginalAfterCustodyLoss(); + verify(success.result()).close(); + } + + @Test + void concurrentCloseWaitsForOwnedBorrowThenRetiresExactOriginal() throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var closing = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowed = + executor.submit( + () -> + outcome.withOwnedPrivateResult( + result -> { + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("test timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return result == success.result(); + })); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + outcome.close(); + }); + assertThat(closing.await(5, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + verify(success.result(), never()).close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + release.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + closed.get(5, TimeUnit.SECONDS); + verify(success.result()).close(); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + } finally { + release.countDown(); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"transfer", "abandon", "direct-close"}) + void lifecycleDrainKeepsBorrowedBytesLiveAndBlocksNewBorrows(String operation) throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var lifecycleThread = new AtomicReference(); + byte[] expected = success.result().compactJwtBytes(); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowed = + executor.submit( + () -> + outcome.withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(success.result()); + entered.countDown(); + await(release); + assertThat(result.compactJwtBytes()).containsExactly(expected); + return true; + })); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var mutation = + executor.submit( + () -> { + lifecycleThread.set(Thread.currentThread()); + return switch (operation) { + case "transfer" -> outcome.takePrivateResult().orElseThrow(); + case "abandon" -> outcome.abandonOriginalAfterCustodyLoss(); + default -> { + success.result().close(); + yield true; + } + }; + }); + awaitWaiting(lifecycleThread); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> mutation.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + release.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + Object result = mutation.get(5, TimeUnit.SECONDS); + if (operation.equals("transfer")) { + assertThat(result).isSameAs(success.result()); + assertThat(success.result().compactJwtBytes()).containsExactly(expected); + outcome.close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + outcome.abandonOriginalAfterCustodyLoss(); + } else if (operation.equals("direct-close")) { + outcome.close(); + } + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + } finally { + release.countDown(); + } + } finally { + Arrays.fill(expected, (byte) 0); + outcome.close(); + } + } + + @Test + void heldOriginalCleanupRetriesOutsideOutcomeMonitorAndRefusesReentrantMutation() + throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var accessed = new AtomicBoolean(); + try (var executor = Executors.newSingleThreadExecutor()) { + when(success.fixture().cleanup.abandonAndRetire(outcome.coordinates())) + .thenAnswer( + call -> { + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + accessed.set( + executor + .submit(() -> outcome.custodyLossCleanup().isEmpty()) + .get(5, TimeUnit.SECONDS)); + return held(outcome.coordinates()); + }); + outcome.close(); + assertThat(accessed).isTrue(); + assertThat(outcome.custodyLossCleanup().orElseThrow().status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + org.mockito.Mockito.doReturn( + new InitialGameplayLoginCleanupOwner.CleanupObservation( + outcome.coordinates(), + InitialGameplayLoginCleanupOwner.Status.ACCOUNT_PENDING, + Optional.empty(), + Optional.empty())) + .when(success.fixture().cleanup) + .abandonAndRetire(outcome.coordinates()); + assertThat(outcome.abandonOriginalAfterCustodyLoss().status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.ACCOUNT_PENDING); + verify(success.fixture().cleanup, times(2)).abandonAndRetire(outcome.coordinates()); + verify(success.result()).close(); + } + } + + @Test + void equalReconstructedEvidenceCannotReplaceClosedGenuineOwnedResult() { + var success = successfulOutcome(); + try (var reconstructed = controlledPrivateResult(success.outcome().coordinates())) { + assertThat(reconstructed.evidence()).isEqualTo(success.result().evidence()); + assertThat(reconstructed).isNotSameAs(success.result()); + success.result().close(); + assertThatThrownBy(() -> success.outcome().withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + assertThat(success.outcome().takePrivateResult()).containsSame(success.result()); + assertThat(reconstructed.compactJwtBytes()).isNotEmpty(); + success.outcome().abandonOriginalAfterCustodyLoss(); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + } + } + + @Test + void directResultBorrowRefusesOwnerReentrancyWithoutChangingOwnedState() { + var success = successfulOutcome(); + success + .result() + .withLivePrivateResult( + result -> { + assertThatThrownBy(success.outcome()::close) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + return true; + }); + assertThat( + success.outcome().withOwnedPrivateResult(result -> result == success.result())) + .isTrue(); + success.outcome().close(); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void directResultPinCannotWaitBehindOutcomeDrainThatIsWaitingForTheSamePin(boolean transferred) + throws Exception { + var success = successfulOutcome(); + if (transferred) + assertThat(success.outcome().takePrivateResult()).containsSame(success.result()); + var entered = new CountDownLatch(1); + var attemptLifecycle = new CountDownLatch(1); + var closingThread = new AtomicReference(); + var borrowed = new CompletableFuture(); + var closed = new CompletableFuture(); + // Daemon workers keep this logical-deadlock regression bounded even if the cycle returns. + Thread.ofPlatform() + .daemon() + .start( + () -> { + try { + borrowed.complete( + success + .result() + .withLivePrivateResult( + result -> { + entered.countDown(); + await(attemptLifecycle); + assertThatThrownBy(success.outcome()::close) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + return true; + })); + } catch (Throwable failure) { + borrowed.completeExceptionally(failure); + } + }); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + Thread.ofPlatform() + .daemon() + .start( + () -> { + closingThread.set(Thread.currentThread()); + try { + if (transferred) success.outcome().abandonOriginalAfterCustodyLoss(); + else success.outcome().close(); + closed.complete(null); + } catch (Throwable failure) { + closed.completeExceptionally(failure); + } + }); + try { + awaitWaiting(closingThread); + assertThat(closed).isNotDone(); + attemptLifecycle.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + closed.get(5, TimeUnit.SECONDS); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } finally { + attemptLifecycle.countDown(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("Test gate timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Test gate interrupted", failure); + } + } + + private static void awaitWaiting(AtomicReference thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.get() == null || thread.get().getState() != Thread.State.WAITING) { + if (System.nanoTime() >= deadline) throw new IllegalStateException("Lifecycle did not drain"); + Thread.sleep(1); + } + } + 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)); + var result = new AtomicReference(); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) .thenAnswer( invocation -> { fixture.accountRequest = invocation.getArgument(0); - return result; + var retained = spy(controlledPrivateResult(fixture.coordinates)); + result.set(retained); + return retained; }); when(fixture.contexts.createPending(any())) .thenAnswer( @@ -137,7 +476,23 @@ private static SuccessfulOutcome successfulOutcome() { when(fixture.cleanup.abandonAndRetire(any())) .thenAnswer(invocation -> held(invocation.getArgument(0))); - return new SuccessfulOutcome(fixture, fixture.owner.receive(credentials), result, secret); + var outcome = fixture.owner.receive(credentials); + return new SuccessfulOutcome(fixture, outcome, result.get(), secret); + } + + /** Controlled private bytes only: this unit fixture supplies no authenticated Account origin. */ + private static CanonicalGameplayLoginResult controlledPrivateResult( + InitialGameplayLoginAttemptCoordinates coordinates) { + try { + var constructor = + CanonicalGameplayLoginResult.class.getDeclaredConstructor( + byte[].class, NonSecretEvidence.class); + constructor.setAccessible(true); + return constructor.newInstance( + "controlled-private-token".getBytes(StandardCharsets.US_ASCII), evidence(coordinates)); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Controlled result fixture unavailable", failure); + } } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java new file mode 100644 index 0000000000..a07611335c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.gamesession.websocket; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; +import net.firedevops.firemud.gamesession.command.text.TextCommand; +import net.firedevops.firemud.gamesession.command.text.TextCommandPayload; +import net.firedevops.firemud.gamesession.command.text.TextCommandType; +import net.firedevops.firemud.gamesession.config.PresentationProperties; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.web.socket.WebSocketSession; + +/** Wire-selector routing with controlled owners, not source qualification or admission proof. */ +class AuthenticatedDirectTextCommandReceiverTest { + @Test + void authenticatedLoginWithoutOwnerRefusesBeforeDispatch() { + var fixture = fixture(); + var command = + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret"); + assertThat(command.credentialsPayload()).isPresent(); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); + } + + @Test + @SuppressWarnings("unchecked") + void emailNormalizationRejectionReturnsUsageBeforeProtectedOwnerLookup() { + var socket = mock(WebSocketSession.class); + var sessions = mock(AuthenticatedDirectTextSessions.class); + var connection = mock(AuthenticatedDirectTextSessions.Connection.class); + when(sessions.require(socket)).thenReturn(connection); + ObjectProvider logins = mock(ObjectProvider.class); + ObjectProvider selections = mock(ObjectProvider.class); + ObjectProvider lobbies = mock(ObjectProvider.class); + var receiver = + new AuthenticatedDirectTextCommandReceiver(sessions, logins, selections, lobbies); + var malformedEmail = " \u0000 "; + var command = + new TextCommand( + TextCommandType.LOGIN, + List.of(malformedEmail, "secret"), + "LOGIN malformed secret", + "LOGIN", + new TextCommandPayload.Credentials(malformedEmail, "secret")); + + var result = receiver.receive(socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Usage: LOGIN "); + verify(logins, never()).getIfAvailable(); + verifyNoInteractions(connection); + } + + @Test + void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { + var fixture = fixture(); + when(fixture.lobby.join(null, null, fixture.connection)) + .thenReturn( + new DirectTextAuthenticatedLobbyOwner.Observation( + UUID.randomUUID(), + UUID.randomUUID(), + DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING, + Optional.of(JoinPublicProductionMembershipResponse.getDefaultInstance()))); + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + assertThat(result.commandResult().accepted()).isTrue(); + verify(fixture.selections).resolve(fixture.connection.menu, "demo"); + verify(fixture.lobby).join(null, null, fixture.connection); + } + + @Test + void unknownRealmSelectorReturnsActionableInvalidArgument() { + var fixture = fixture(); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "missing")) + .thenThrow(new UnknownWorldSelectorException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("missing"), "REALMS missing")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); + } + + @Test + void unknownJoinSelectorReturnsActionableInvalidArgumentBeforeLobbyDispatch() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "missing")) + .thenThrow(new UnknownWorldSelectorException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.JOIN, List.of("missing"), "JOIN missing")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); + verifyNoInteractions(fixture.lobby); + } + + @Test + void expiredRealmMenuReturnsActionableInvalidArgumentAfterTheGuardedLobbyCall() { + var fixture = fixture(); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "demo")) + .thenThrow(new ExpiredWorldSelectionException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("World menu expired. Run WORLDS and choose a listed selector again."); + verify(fixture.lobby).realms(null, null, fixture.connection, fixture.connection.menu, "demo"); + } + + @Test + void expiredJoinMenuReturnsActionableInvalidArgumentBeforeLobbyDispatch() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "demo")) + .thenThrow(new ExpiredWorldSelectionException()); + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("World menu expired. Run WORLDS and choose a listed selector again."); + verifyNoInteractions(fixture.lobby); + } + + @Test + void refusedJoinReportsTheExactInvalidArgumentOrUnavailableError() { + var fixture = fixture(); + var empty = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of(), "JOIN")); + assertThat(empty.commandResult().accepted()).isFalse(); + assertThat(empty.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(empty.commandResult().errorMessage()).isEqualTo("Usage: JOIN "); + + var excessive = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.JOIN, List.of("demo", "production"), "JOIN")); + assertThat(excessive.commandResult().accepted()).isFalse(); + assertThat(excessive.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(excessive.commandResult().errorMessage()).isEqualTo("Usage: JOIN "); + + var unresolved = fixture(); + when(unresolved.selections.resolve(unresolved.connection.menu, "demo")) + .thenReturn(Optional.empty()); + var unresolvedResult = + unresolved.receiver.receive( + unresolved.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + assertThat(unresolvedResult.commandResult().accepted()).isFalse(); + assertThat(unresolvedResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(unresolvedResult.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + verifyNoInteractions(unresolved.lobby); + } + + @Test + void loginAndLobbyObservationsNeverSubstituteForCanonicalPlayAdmission() { + var fixture = fixture(); + var command = + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "production", "hero"), + "PLAY demo production hero"); + var result = fixture.receiver.receive(fixture.socket, command); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_UNAVAILABLE"); + var wireResponse = + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs()); + assertThat(wireResponse) + .isEqualTo("ERROR ADMISSION_UNAVAILABLE Canonical gameplay admission unavailable") + .doesNotContain("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + + @ParameterizedTest + @MethodSource("malformedCommands") + void malformedCommandsReturnUsageBeforeOwnerOrLoginDispatch(TextCommand command) { + var fixture = fixture(); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).startsWith("Usage: " + command.type()); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs())) + .startsWith("ERROR INVALID_ARGUMENT Usage: " + command.type()); + verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); + } + + private static Stream malformedCommands() { + return Stream.of( + new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of("player@example.test"), "LOGIN"), + new TextCommand( + TextCommandType.LOGIN, List.of("player@example.test", "secret", "extra"), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of(" ", "secret"), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of("player@example.test", ""), "LOGIN"), + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "secret"), + "LOGIN", + "LOGIN", + new TextCommandPayload.Credentials(null, "secret")), + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "secret"), + "LOGIN", + "LOGIN", + new TextCommandPayload.Credentials("player@example.test", null)), + new TextCommand(TextCommandType.REALMS, List.of(), "REALMS"), + new TextCommand(TextCommandType.REALMS, List.of("demo", "extra"), "REALMS"), + new TextCommand(TextCommandType.REALMS, List.of(" "), "REALMS"), + new TextCommand(TextCommandType.JOIN, List.of(), "JOIN"), + new TextCommand(TextCommandType.JOIN, List.of("demo", "extra"), "JOIN"), + new TextCommand(TextCommandType.JOIN, List.of(" "), "JOIN")); + } + + @Test + void realmsBeforeWorldsExplainsTheRequiredLocalSequence() { + var fixture = fixture(); + fixture.connection.menu = null; + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Run WORLDS before REALMS "); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + + @Test + void joinBeforeRealmsExplainsTheRequiredLocalSequence() { + var fixture = fixture(); + fixture.connection.selectedScope = null; + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Run WORLDS and REALMS before JOIN "); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + + @Test + void differentResolvedWorldRequiresItsOwnRealmsSelection() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "other")) + .thenReturn(Optional.of(mock(CanonicalPlayableTarget.class))); + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("other"), "JOIN other")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).contains("REALMS "); + verifyNoInteractions(fixture.lobby); + } + + @Test + void protectedOwnerAndSelectionFailuresRemainUnavailableRatherThanUsageErrors() { + for (RuntimeException failure : + List.of( + new IllegalArgumentException("private-source"), + new IllegalStateException("private-custody"))) { + var realms = fixture(); + when(realms.lobby.realms(null, null, realms.connection, realms.connection.menu, "demo")) + .thenThrow(failure); + var realmResult = + realms.receiver.receive( + realms.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + assertThat(realmResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(realmResult.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + + var join = fixture(); + when(join.selections.resolve(join.connection.menu, "demo")).thenThrow(failure); + var joinResult = + join.receiver.receive( + join.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + assertThat(joinResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(joinResult.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + verifyNoInteractions(join.lobby); + } + } + + private Fixture fixture() { + var socket = mock(WebSocketSession.class); + var sessions = mock(AuthenticatedDirectTextSessions.class); + var connection = mock(AuthenticatedDirectTextSessions.Connection.class); + when(sessions.require(socket)).thenReturn(connection); + when(connection.withLogin(any())) + .thenAnswer( + invocation -> { + BiFunction< + InitialGameplayLoginAttemptCoordinates, CanonicalGameplayLoginResult, Object> + action = invocation.getArgument(0); + return action.apply(null, null); + }); + connection.menu = mock(DirectTextWorldSelectionService.SelectionSnapshot.class); + connection.selectedScope = mock(DirectTextAuthenticatedLobbyScope.class); + var target = mock(CanonicalPlayableTarget.class); + when(connection.selectedScope.publicTarget()).thenReturn(target); + var selections = mock(DirectTextWorldSelectionService.class); + when(selections.resolve(connection.menu, "demo")).thenReturn(Optional.of(target)); + var lobby = mock(DirectTextAuthenticatedLobbyOwner.class); + var beans = new StaticListableBeanFactory(Map.of("lobby", lobby, "selections", selections)); + var receiver = + new AuthenticatedDirectTextCommandReceiver( + sessions, + beans.getBeanProvider(InitialGameplayLoginOwner.class), + beans.getBeanProvider(DirectTextWorldSelectionService.class), + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + return new Fixture(socket, connection, selections, lobby, receiver); + } + + private record Fixture( + WebSocketSession socket, + AuthenticatedDirectTextSessions.Connection connection, + DirectTextWorldSelectionService selections, + DirectTextAuthenticatedLobbyOwner lobby, + AuthenticatedDirectTextCommandReceiver receiver) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java new file mode 100644 index 0000000000..f5601452a6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -0,0 +1,523 @@ +package net.firedevops.firemud.gamesession.websocket; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +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.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.TextCommand; +import net.firedevops.firemud.gamesession.command.text.TextCommandType; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketSession; + +/** Process-local custody proof with controlled Account result/cleanup sources, not admission. */ +class AuthenticatedDirectTextSessionsTest { + private final AuthenticatedDirectTextSessions sessions = new AuthenticatedDirectTextSessions(); + + @ParameterizedTest + @CsvSource({ + "AUTH_INVALID_CREDENTIALS, INVALID_CREDENTIALS", + "AUTH_ACCOUNT_LOCKED, ACCOUNT_LOCKED", + "AUTH_RETRY_LATER, RETRY_LATER", + "IDEMPOTENCY_CONFLICT, IDEMPOTENCY_CONFLICT", + "RESPONSE_RECOVERY_EXPIRED, RESPONSE_RECOVERY_EXPIRED", + "AUTH_UNAVAILABLE, UNAVAILABLE", + "CUSTODY_LOST, UNAVAILABLE", + "LOGIN_UNAVAILABLE, UNAVAILABLE", + "DEADLINE_EXCEEDED, UNAVAILABLE", + "untrusted-owner-diagnostic, UNAVAILABLE", + ", UNAVAILABLE" + }) + void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( + String ownerCode, String publicCode) throws Exception { + var socket = socket(); + sessions.open(socket); + var outcome = mock(InitialGameplayLoginOwner.Outcome.class); + when(outcome.status()).thenReturn(InitialGameplayLoginOwner.Status.CLEANUP_ACCOUNT_NO_TOKEN); + when(outcome.failureCode()).thenReturn(Optional.ofNullable(ownerCode)); + var owner = mock(InitialGameplayLoginOwner.class); + when(owner.receive(any())).thenReturn(outcome); + var beans = new StaticListableBeanFactory(Map.of("login", owner)); + var receiver = + new AuthenticatedDirectTextCommandReceiver( + sessions, + beans.getBeanProvider(InitialGameplayLoginOwner.class), + beans.getBeanProvider(DirectTextWorldSelectionService.class), + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + + var result = + receiver.receive( + socket, + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo(publicCode); + assertThat(result.commandResult().errorMessage()) + .doesNotContain("transient-secret", "untrusted-owner-diagnostic"); + if ("UNAVAILABLE".equals(publicCode)) { + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + } + verify(outcome, never()).withOwnedPrivateResult(any()); + var laterBorrow = + receiver.receive( + socket, new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + assertThat(laterBorrow.commandResult().errorCode()).isEqualTo("LOGIN_REQUIRED"); + verify(outcome).close(); + sessions.close(socket, CloseStatus.NORMAL); + } + + @ParameterizedTest + @EnumSource( + value = TextCommandType.class, + names = {"REALMS", "JOIN"}) + void missingLoginIsActionableButClosedCustodyRemainsUnavailable(TextCommandType type) + throws Exception { + var socket = socket(); + sessions.open(socket); + var beans = new StaticListableBeanFactory(); + var receiver = + new AuthenticatedDirectTextCommandReceiver( + sessions, + beans.getBeanProvider(InitialGameplayLoginOwner.class), + beans.getBeanProvider(DirectTextWorldSelectionService.class), + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + var command = new TextCommand(type, List.of("demo"), type + " demo"); + + var missingLogin = receiver.receive(socket, command); + + assertThat(missingLogin.commandResult().errorCode()).isEqualTo("LOGIN_REQUIRED"); + assertThat(missingLogin.commandResult().errorMessage()).contains("LOGIN "); + sessions.close(socket, CloseStatus.NORMAL); + + var closedCustody = receiver.receive(socket, command); + + assertThat(closedCustody.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(closedCustody.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + } + + @Test + void rejectedLoginErasesCredentialsAndRetainsCleanupOwnership() throws Exception { + var socket = socket(); + sessions.open(socket); + var outcome = mock(InitialGameplayLoginOwner.Outcome.class); + when(outcome.status()).thenReturn(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + when(outcome.failureCode()).thenReturn(Optional.of("AUTH_INVALID_CREDENTIALS")); + var owner = mock(InitialGameplayLoginOwner.class); + when(owner.receive(any())).thenReturn(outcome); + char[] secret = "transient-private-secret".toCharArray(); + + assertThatThrownBy(() -> sessions.require(socket).login(owner, "player@example.test", secret)) + .isInstanceOf(AuthenticatedDirectTextSessions.LoginRejectedException.class) + .hasMessage("Authenticated gameplay LOGIN was rejected"); + + assertThat(secret).containsOnly('\0'); + verify(outcome).close(); + sessions.close(socket, CloseStatus.NORMAL); + verify(outcome, org.mockito.Mockito.times(1)).close(); + } + + @Test + void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + char[] secret = "transient-private-secret".toCharArray(); + connection.login(fixture.owner(), "player@example.test", secret); + assertThat(secret).containsOnly('\0'); + assertThat( + connection.withLogin( + (original, result) -> { + assertThat(result).isSameAs(fixture.result()); + assertThatThrownBy(() -> sessions.close(socket, CloseStatus.NORMAL)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(sessions::closeAll).isInstanceOf(IllegalStateException.class); + assertThat(sessions.require(socket)).isSameAs(connection); + return connection.withCurrent( + original, result, transport -> transport.transportSessionId().equals("42")); + })) + .isTrue(); + assertThatThrownBy( + () -> connection.withCurrent(fixture.original(), fixture.result(), transport -> true)) + .isInstanceOf(IllegalStateException.class); + sessions.close(socket, CloseStatus.NORMAL); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + assertThatThrownBy(fixture.result()::compactJwtBytes).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> sessions.require(socket)).isInstanceOf(IllegalStateException.class); + } + + @Test + void selectionFailuresPropagateThroughCustodyWithoutDiscardingExactLogin() throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + + var unknown = new DirectTextWorldSelectionService.UnknownWorldSelectorException(); + assertThatThrownBy( + () -> + connection.withLogin( + (original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw unknown; + }))) + .isSameAs(unknown); + + var expired = new DirectTextWorldSelectionService.ExpiredWorldSelectionException(); + assertThatThrownBy( + () -> + connection.withLogin( + (original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw expired; + }))) + .isSameAs(expired); + + assertThat( + connection.withLogin( + (original, result) -> { + assertThat(result).isSameAs(fixture.result()); + return connection.withCurrent( + original, result, transport -> transport.transportSessionId().equals("42")); + })) + .isTrue(); + + sessions.close(socket, CloseStatus.NORMAL); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + } + + @Test + void disconnectRevokesBeforeDrainingAndCleansOnlyAfterBorrowReturns() throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrower = + executor.submit( + () -> + connection.withLogin( + (original, result) -> { + entered.countDown(); + await(release); + return true; + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var closer = executor.submit(() -> sessions.close(socket, CloseStatus.NORMAL)); + for (int i = 0; i < 1000 && connection.isCurrent(); i++) Thread.sleep(1); + assertThat(connection.isCurrent()).isFalse(); + assertThat(closer.isDone()).isFalse(); + verify(fixture.cleanup(), never()).abandonAndRetire(any()); + verify(socket, never()).close(any()); + release.countDown(); + assertThatThrownBy(() -> borrower.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class); + closer.get(5, TimeUnit.SECONDS); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + verify(socket).close(CloseStatus.NORMAL); + } finally { + release.countDown(); + } + } + + @Test + void replacementCannotActivateBeforeOldGenerationDrainsOrReconstructOldLogin() throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var replacement = socket(); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrower = + executor.submit( + () -> + connection.withLogin( + (original, result) -> { + entered.countDown(); + await(release); + return true; + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var replacing = executor.submit(() -> sessions.open(replacement)); + for (int i = 0; i < 1000 && connection.isCurrent(); i++) Thread.sleep(1); + assertThat(connection.isCurrent()).isFalse(); + assertThatThrownBy(() -> sessions.require(replacement)) + .isInstanceOf(IllegalStateException.class); + assertThat(replacing.isDone()).isFalse(); + release.countDown(); + assertThatThrownBy(() -> borrower.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class); + replacing.get(5, TimeUnit.SECONDS); + var current = sessions.require(replacement); + assertThatThrownBy(() -> current.withLogin((original, result) -> true)) + .isInstanceOf(IllegalStateException.class); + verify(socket).close(new CloseStatus(1012, "backend_generation_closed")); + sessions.close(socket, CloseStatus.NORMAL); + assertThat(sessions.require(replacement)).isSameAs(current); + sessions.close(replacement, CloseStatus.NORMAL); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + } finally { + release.countDown(); + } + } + + @Test + void overlappingReplacementsDrainTheWholePredecessorChainBeforeActivation() throws Exception { + var originalSocket = socket(); + sessions.open(originalSocket); + var fixture = fixture(); + var originalConnection = sessions.require(originalSocket); + originalConnection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var middle = socket(); + var latest = socket(); + try (var executor = Executors.newFixedThreadPool(3)) { + var borrower = + executor.submit( + () -> + originalConnection.withLogin( + (coordinates, result) -> { + entered.countDown(); + await(release); + return true; + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var firstReplacement = executor.submit(() -> sessions.open(middle)); + for (int i = 0; i < 1000 && originalConnection.isCurrent(); i++) Thread.sleep(1); + assertThat(originalConnection.isCurrent()).isFalse(); + var secondReplacement = executor.submit(() -> sessions.open(latest)); + for (int i = 0; + i < 1000 + && !latest + .getAttributes() + .containsKey(AuthenticatedDirectTextSessions.class.getName()); + i++) Thread.sleep(1); + assertThat(latest.getAttributes()) + .containsKey(AuthenticatedDirectTextSessions.class.getName()); + assertThatThrownBy(() -> sessions.require(latest)).isInstanceOf(IllegalStateException.class); + assertThat(firstReplacement.isDone()).isFalse(); + assertThat(secondReplacement.isDone()).isFalse(); + verify(fixture.cleanup(), never()).abandonAndRetire(any()); + release.countDown(); + assertThatThrownBy(() -> borrower.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class); + firstReplacement.get(5, TimeUnit.SECONDS); + secondReplacement.get(5, TimeUnit.SECONDS); + var current = sessions.require(latest); + assertThatThrownBy(() -> sessions.require(middle)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> current.withLogin((coordinates, result) -> true)) + .isInstanceOf(IllegalStateException.class); + sessions.closeAll(); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + } finally { + release.countDown(); + } + } + + @Test + void shutdownRevokesEveryGenerationBeforeDrainingAndRefusesNewConnections() throws Exception { + var first = socket("42"); + var second = socket("43"); + sessions.open(first); + sessions.open(second); + var firstFixture = fixture(); + var secondFixture = fixture(); + var firstConnection = sessions.require(first); + var secondConnection = sessions.require(second); + firstConnection.login(firstFixture.owner(), "player@example.test", "secret".toCharArray()); + secondConnection.login(secondFixture.owner(), "player@example.test", "secret".toCharArray()); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrower = + executor.submit( + () -> + firstConnection.withLogin( + (original, result) -> { + entered.countDown(); + await(release); + return true; + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var shutdown = executor.submit(sessions::closeAll); + for (int i = 0; i < 1000 && firstConnection.isCurrent(); i++) Thread.sleep(1); + assertThat(firstConnection.isCurrent()).isFalse(); + assertThat(secondConnection.isCurrent()).isFalse(); + assertThat(shutdown.isDone()).isFalse(); + var newSocket = socket("44"); + assertThatThrownBy(() -> sessions.open(newSocket)).isInstanceOf(IllegalStateException.class); + assertThat(newSocket.getAttributes()) + .doesNotContainKey(AuthenticatedDirectTextSessions.class.getName()); + release.countDown(); + assertThatThrownBy(() -> borrower.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class); + shutdown.get(5, TimeUnit.SECONDS); + verify(firstFixture.cleanup()).abandonAndRetire(firstFixture.original()); + verify(secondFixture.cleanup()).abandonAndRetire(secondFixture.original()); + verify(first).close(new CloseStatus(1012, "backend_generation_closed")); + verify(second).close(new CloseStatus(1012, "backend_generation_closed")); + assertThatThrownBy(() -> sessions.open(newSocket)).isInstanceOf(IllegalStateException.class); + } finally { + release.countDown(); + } + } + + @ParameterizedTest + @CsvSource({"1000, logout", "1011, internal_error"}) + void callerCloseStatusIsRetainedAfterExactOriginalCleanup(int code, String reason) + throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + var status = new CloseStatus(code, reason); + + sessions.close(socket, status); + sessions.close(socket, new CloseStatus(1012, "backend_generation_closed")); + + var order = inOrder(fixture.cleanup(), socket); + order.verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + order.verify(socket).close(status); + verify(socket, org.mockito.Mockito.times(1)).close(any()); + assertThat(connection.isCurrent()).isFalse(); + assertThatThrownBy(fixture.result()::compactJwtBytes).isInstanceOf(IllegalStateException.class); + } + + private static WebSocketSession socket() throws Exception { + return socket("42"); + } + + private static WebSocketSession socket(String sessionId) throws Exception { + var certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/test/sa/spring-cloud-gateway"))); + when(certificate.getExtendedKeyUsage()).thenReturn(List.of("1.3.6.1.5.5.7.3.2")); + var request = new MockHttpServletRequest("GET", "/ws/game/tcp"); + request.setSecure(true); + request.setLocalPort(8444); + request.setAttribute( + "jakarta.servlet.request.X509Certificate", new X509Certificate[] {certificate}); + request.addHeader("X-Client-IP", "203.0.113.7"); + request.addHeader("X-Proxy-Connection-Id", "99999999-9999-4999-8999-999999999999"); + request.addHeader("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + var ingress = + AuthenticatedDirectTextIngress.authenticate( + new ServletServerHttpRequest(request), 8444, "test", sessionId); + var socket = mock(WebSocketSession.class); + var attributes = new java.util.concurrent.ConcurrentHashMap(); + attributes.put(AuthenticatedDirectTextIngress.ATTRIBUTE, ingress); + when(socket.getAttributes()).thenReturn(attributes); + when(socket.isOpen()).thenReturn(true); + return socket; + } + + private static Fixture fixture() throws Exception { + var original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 1); + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + UUID.randomUUID(), + original.requestId(), + original.callerContextId(), + UUID.randomUUID(), + "a".repeat(64), + "game-session-account-delegation/v1", + 1000, + 1000, + 1200, + "1", + "3", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY); + var resultConstructor = + CanonicalGameplayLoginResult.class.getDeclaredConstructor( + byte[].class, CanonicalGameplayLoginResult.NonSecretEvidence.class); + resultConstructor.setAccessible(true); + var result = + resultConstructor.newInstance( + "controlled-private-token".getBytes(StandardCharsets.US_ASCII), evidence); + var cleanup = mock(InitialGameplayLoginCleanupOwner.class); + when(cleanup.abandonAndRetire(original)) + .thenReturn( + new InitialGameplayLoginCleanupOwner.CleanupObservation( + original, + InitialGameplayLoginCleanupOwner.Status.HELD, + Optional.empty(), + Optional.empty())); + var installed = + InitialGameplayLoginOwner.Outcome.class.getDeclaredMethod( + "installed", + InitialGameplayLoginAttemptCoordinates.class, + CanonicalGameplayLoginResult.class, + InitialGameplayLoginCleanupOwner.class); + installed.setAccessible(true); + var outcome = + (InitialGameplayLoginOwner.Outcome) installed.invoke(null, original, result, cleanup); + var owner = mock(InitialGameplayLoginOwner.class); + when(owner.receive(any())).thenReturn(outcome); + return new Fixture(owner, original, result, cleanup); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("Timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Fixture( + InitialGameplayLoginOwner owner, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult result, + InitialGameplayLoginCleanupOwner cleanup) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java new file mode 100644 index 0000000000..840e613c65 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.gamesession.websocket; + +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 jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslStoreBundle; +import org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory; +import org.springframework.http.server.ServletServerHttpRequest; + +/** Physical connector and authenticated receiving proof, independent of Account admission. */ +class AuthenticatedGameplayListenerConfigurationTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Gameplay listener test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "session", "spiffe://firemud/ns/test/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "gateway", "spiffe://firemud/ns/test/sa/spring-cloud-gateway", false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/account-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/spring-cloud-gateway", false)); + } + + @Test + void physicalDedicatedConnectorRequiresClientTlsAndExactGatewayIdentity() throws Exception { + int port; + try (var reserved = new ServerSocket(0)) { + port = reserved.getLocalPort(); + } + var config = new AuthenticatedGameplayListenerConfiguration(); + var bundles = mock(SslBundles.class); + KeyStore keys = KeyStore.getInstance("PKCS12"); + keys.load(null, null); + var server = pki.identity("session"); + keys.setKeyEntry( + "session", + server.privateKey(), + "test-only".toCharArray(), + new X509Certificate[] {server.certificate(), pki.caCertificate()}); + KeyStore trust = KeyStore.getInstance("PKCS12"); + trust.load(null, null); + trust.setCertificateEntry("ca", pki.caCertificate()); + when(bundles.getBundle("firemud-grpc")) + .thenReturn(SslBundle.of(SslStoreBundle.of(keys, "test-only", trust))); + var factory = new TomcatServletWebServerFactory(0); + config.authenticatedGameplayConnector(bundles, port, 0).customize(factory); + var received = new AtomicInteger(); + var filter = config.authenticatedGameplayPathFilter(port); + var web = + factory.getWebServer( + context -> { + var servlet = + context.addServlet( + "custody", + new HttpServlet() { + @Override + protected void doGet( + HttpServletRequest request, HttpServletResponse response) + throws java.io.IOException, jakarta.servlet.ServletException { + filter.doFilter( + request, + response, + (incoming, outgoing) -> { + try { + AuthenticatedDirectTextIngress.authenticate( + new ServletServerHttpRequest((HttpServletRequest) incoming), + port, + "test", + "42"); + received.incrementAndGet(); + ((HttpServletResponse) outgoing).setStatus(200); + } catch (IllegalArgumentException rejected) { + ((HttpServletResponse) outgoing).setStatus(403); + } + }); + } + }); + servlet.addMapping("/*"); + }); + web.start(); + try { + assertThat(call("gateway", port, "/ws/game/tcp").statusCode()).isEqualTo(200); + assertThat(call("wrong-service", port, "/ws/game/tcp").statusCode()).isEqualTo(403); + assertThat(call("wrong-namespace", port, "/ws/game/tcp").statusCode()).isEqualTo(403); + assertThat(call("gateway", port, "/actuator/health").statusCode()).isEqualTo(404); + assertThatThrownBy(() -> call(null, port, "/ws/game/tcp")) + .isInstanceOf(java.io.IOException.class); + try (var publicClient = HttpClient.newHttpClient()) { + assertThat( + publicClient + .send( + HttpRequest.newBuilder( + URI.create("http://localhost:" + web.getPort() + "/ws/game/tcp")) + .timeout(Duration.ofSeconds(5)) + .header("X-Firemud-Connection-Mode", "trusted_tcp_proxy") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") + .header("X-Client-IP", "203.0.113.7") + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode()) + .isEqualTo(403); + } + assertThat(received).hasValue(1); + } finally { + web.stop(); + web.destroy(); + } + } + + private HttpResponse call(String identity, int port, String path) throws Exception { + SSLContext tls = SSLContext.getInstance("TLS"); + tls.init( + identity == null ? null : pki.keyManagerFactory(pki.identity(identity)).getKeyManagers(), + pki.trustManagerFactory().getTrustManagers(), + null); + try (var client = + HttpClient.newBuilder().sslContext(tls).connectTimeout(Duration.ofSeconds(3)).build()) { + return client.send( + HttpRequest.newBuilder(URI.create("https://localhost:" + port + path)) + .timeout(Duration.ofSeconds(5)) + .header("X-Firemud-Connection-Mode", "trusted_tcp_proxy") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") + .header("X-Client-IP", "203.0.113.7") + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + } + } +} 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 a29da50a36..ecbbdab0dd 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 @@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; @@ -133,6 +134,150 @@ private GameSessionWebSocketHandler handlerWithMetadata( textCommandMetadataResolver); } + @Test + void authenticatedLogoutClosesCustodyAfterResponseDelivery() throws Exception { + var authenticatedSessions = authenticatedLogoutReceiving(); + + handler.handleMessage(session, new TextMessage("LOGOUT")); + + InOrder order = Mockito.inOrder(session, authenticatedSessions); + order.verify(session).sendMessage(argThat(message -> "OK LOGOUT".equals(message.getPayload()))); + order.verify(authenticatedSessions).close(session, new CloseStatus(1000, "logout")); + Mockito.verifyNoInteractions(interpreter); + } + + @ParameterizedTest + @CsvSource({"8, fr-CA", "8,", ", fr-CA", ","}) + void authenticatedResponseUsesOnlyHandshakeLocaleWithoutReadingRetainedContext( + String tenantId, String localeTag) throws Exception { + var authenticatedSessions = Mockito.mock(AuthenticatedDirectTextSessions.class); + var receiver = Mockito.mock(AuthenticatedDirectTextCommandReceiver.class); + handler.authenticatedDirectTextReceiving(authenticatedSessions, receiver); + var attributes = new java.util.HashMap(); + attributes.put(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41"); + attributes.put( + AuthenticatedDirectTextIngress.ATTRIBUTE, + Mockito.mock(AuthenticatedDirectTextIngress.class)); + if (tenantId != null) + attributes.put(GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, tenantId); + if (localeTag != null) + attributes.put(GameSessionWebSocketHandshakeInterceptor.LOCALE_ATTR, localeTag); + when(session.getAttributes()).thenReturn(attributes); + var unavailable = new SessionContextUnavailableException("retained context unavailable", null); + when(sessionAuthenticationService.resolveUnverifiedSessionContext(Mockito.anyString())) + .thenThrow(unavailable); + when(sessionAuthenticationService.resolveUnverifiedSessionContext( + Mockito.anyLong(), Mockito.anyLong())) + .thenThrow(unavailable); + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret"); + var interpretation = + new TextCommandInterpretationResult( + CommandEnqueueResult.failure("INVALID_CREDENTIALS", "Invalid credentials"), + List.of(PlayerOutput.error("INVALID_CREDENTIALS", "Invalid credentials"))); + var presentation = new PresentationProperties(); + when(settingsResolver.presentation(null)).thenReturn(presentation); + when(parser.parse(command.rawLine())).thenReturn(command); + when(receiver.receive(session, command)).thenReturn(interpretation); + when(outputProjector.projectCommandResponse( + session, + command, + interpretation, + interpretation.outputs(), + localeTag, + presentation, + null)) + .thenReturn("ERROR INVALID_CREDENTIALS Invalid credentials"); + + handler.handleMessage(session, new TextMessage(command.rawLine())); + + verify(receiver).receive(session, command); + verify(outputProjector) + .projectCommandResponse( + session, + command, + interpretation, + interpretation.outputs(), + localeTag, + presentation, + null); + verify(session) + .sendMessage( + argThat( + message -> + "ERROR INVALID_CREDENTIALS Invalid credentials".equals(message.getPayload()))); + verify(session, never()).close(any()); + Mockito.verifyNoInteractions( + interpreter, sessionAuthenticationService, sessionContextService, authenticatedSessions); + } + + @Test + void authenticatedLogoutClosesCustodyWhenResponseSendFails() throws Exception { + var authenticatedSessions = authenticatedLogoutReceiving(); + var failure = new IOException("response-send failed"); + Mockito.doThrow(failure).when(session).sendMessage(any()); + + assertThatThrownBy(() -> handler.handleMessage(session, new TextMessage("LOGOUT"))) + .isSameAs(failure); + + InOrder order = Mockito.inOrder(session, authenticatedSessions); + order.verify(session).sendMessage(argThat(message -> "OK LOGOUT".equals(message.getPayload()))); + order.verify(authenticatedSessions).close(session, new CloseStatus(1000, "logout")); + Mockito.verifyNoInteractions(interpreter); + } + + @Test + void authenticatedTransportErrorUsesInternalErrorInsteadOfRestart() throws Exception { + var authenticatedSessions = authenticatedLogoutReceiving(); + + handler.handleTransportError(session, new IOException("transport failed")); + + verify(authenticatedSessions).close(session, new CloseStatus(1011, "internal_error")); + Mockito.verifyNoInteractions(interpreter, sessionAuthenticationService); + } + + @Test + void authenticatedConnectionClosedPreservesObservedStatus() { + var authenticatedSessions = authenticatedLogoutReceiving(); + var status = new CloseStatus(1001, "idle_timeout"); + + handler.afterConnectionClosed(session, status); + + verify(authenticatedSessions).close(session, status); + Mockito.verifyNoInteractions(interpreter, sessionAuthenticationService); + } + + private AuthenticatedDirectTextSessions authenticatedLogoutReceiving() { + var authenticatedSessions = Mockito.mock(AuthenticatedDirectTextSessions.class); + var receiver = Mockito.mock(AuthenticatedDirectTextCommandReceiver.class); + handler.authenticatedDirectTextReceiving(authenticatedSessions, receiver); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + AuthenticatedDirectTextIngress.ATTRIBUTE, + Mockito.mock(AuthenticatedDirectTextIngress.class))); + TextCommand command = new TextCommand(TextCommandType.LOGOUT, List.of(), "LOGOUT"); + var interpretation = new TextCommandInterpretationResult(CommandEnqueueResult.success()); + when(parser.parse("LOGOUT")).thenReturn(command); + when(receiver.receive(session, command)).thenReturn(interpretation); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.empty()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + eq(interpretation), + eq(List.of()), + Mockito.nullable(String.class), + any(PresentationProperties.class), + Mockito.isNull())) + .thenReturn("OK LOGOUT"); + return authenticatedSessions; + } + @Test void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected() throws Exception { 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 2b71cd2638..c7ee9d146b 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 @@ -1,8 +1,12 @@ package net.firedevops.firemud.gamesession.websocket; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.security.cert.X509Certificate; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; @@ -82,20 +86,24 @@ void firstPartyHandoffDoesNotTreatRawRoutingHeadersAsLogicalAuthority() { } @Test - void preservesCanonicalProxyConnectionIdOnlyForTrustedProxyMode() { + void preservesCanonicalProxyConnectionIdOnlyForAuthenticatedGatewayOnDedicatedListener() + throws Exception { String proxyConnectionId = "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"; - MockHttpServletRequest servlet = new MockHttpServletRequest("GET", "/ws/game"); - servlet.addHeader( - GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); - servlet.addHeader( - GameSessionWebSocketHandshakeInterceptor.PROXY_CONNECTION_HEADER, proxyConnectionId); + MockHttpServletRequest servlet = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); Map attributes = new HashMap<>(); - interceptor.beforeHandshake( - new ServletServerHttpRequest(servlet), - new ServletServerHttpResponse(new MockHttpServletResponse()), - null, - attributes); + boolean accepted = + new GameSessionWebSocketHandshakeInterceptor(true, 8444, "test") + .beforeHandshake( + new ServletServerHttpRequest(servlet), + new ServletServerHttpResponse(new MockHttpServletResponse()), + null, + attributes); + + assertThat(accepted).isTrue(); + assertThat(attributes.get(AuthenticatedDirectTextIngress.ATTRIBUTE)) + .isInstanceOf(AuthenticatedDirectTextIngress.class); ObservedDirectTextTransport observed = (ObservedDirectTextTransport) @@ -104,9 +112,109 @@ void preservesCanonicalProxyConnectionIdOnlyForTrustedProxyMode() { assertThat(observed.proxyConnectionId()).isEqualTo(UUID.fromString(proxyConnectionId)); assertThat(observed.transportSessionId()) .isEqualTo(attributes.get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR)); + assertThat(observed.transportSessionId()).matches("\\d+"); assertThat(observed.transportSessionId()).isNotEqualTo(proxyConnectionId); } + @Test + void canonicalizesLiteralIpv6WithoutAddressResolution() throws Exception { + var request = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + request.removeHeader("X-Client-IP"); + request.addHeader("X-Client-IP", "2001:db8::7"); + Map attributes = new HashMap<>(); + assertThat( + new GameSessionWebSocketHandshakeInterceptor(true, 8444, "test") + .beforeHandshake( + new ServletServerHttpRequest(request), + new ServletServerHttpResponse(new MockHttpServletResponse()), + null, + attributes)) + .isTrue(); + var ingress = + (AuthenticatedDirectTextIngress) attributes.get(AuthenticatedDirectTextIngress.ATTRIBUTE); + assertThat(ingress.clientAddress()).isEqualTo("2001:db8:0:0:0:0:0:7"); + } + + @Test + void rejectsSpoofedHeadersWrongWorkloadsNamespacesAndPublicListener() throws Exception { + for (String peer : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/spring-cloud-gateway")) { + var request = authenticatedRequest(peer); + assertRejected(request); + } + var plain = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + plain.setSecure(false); + assertRejected(plain); + var publicPort = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + publicPort.setLocalPort(8080); + assertRejected(publicPort); + var duplicate = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + duplicate.addHeader("X-Client-IP", "198.51.100.9"); + assertRejected(duplicate); + var duplicateMode = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + duplicateMode.addHeader("X-Firemud-Connection-Mode", "first_party_web"); + assertRejected(duplicateMode); + var transportOverride = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + transportOverride.addHeader( + GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, "999999"); + assertRejected(transportOverride); + } + + @Test + void rejectsMissingCertificateClientAuthEkuAndSpiffeSan() throws Exception { + var missingCertificate = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + missingCertificate.removeAttribute("jakarta.servlet.request.X509Certificate"); + assertRejected(missingCertificate); + + assertRejected( + authenticatedRequest( + List.of(List.of(6, "spiffe://firemud/ns/test/sa/spring-cloud-gateway")), + "1.3.6.1.5.5.7.3.1")); + assertRejected(authenticatedRequest(List.of(), "1.3.6.1.5.5.7.3.2")); + } + + private void assertRejected(MockHttpServletRequest request) { + var attributes = new HashMap(); + var response = new MockHttpServletResponse(); + assertThat( + new GameSessionWebSocketHandshakeInterceptor(true, 8444, "test") + .beforeHandshake( + new ServletServerHttpRequest(request), + new ServletServerHttpResponse(response), + null, + attributes)) + .isFalse(); + assertThat(response.getStatus()).isEqualTo(403); + assertThat(attributes) + .doesNotContainKeys( + AuthenticatedDirectTextIngress.ATTRIBUTE, + GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + } + + private static MockHttpServletRequest authenticatedRequest(String peer) throws Exception { + return authenticatedRequest(List.of(List.of(6, peer)), "1.3.6.1.5.5.7.3.2"); + } + + private static MockHttpServletRequest authenticatedRequest( + List> subjectAlternativeNames, String keyUsage) throws Exception { + var request = new MockHttpServletRequest("GET", "/ws/game/tcp"); + request.setSecure(true); + request.setLocalPort(8444); + var certificate = mock(X509Certificate.class); + when(certificate.getExtendedKeyUsage()).thenReturn(List.of(keyUsage)); + when(certificate.getSubjectAlternativeNames()).thenReturn(subjectAlternativeNames); + request.setAttribute( + "jakarta.servlet.request.X509Certificate", new X509Certificate[] {certificate}); + request.addHeader("X-Client-IP", "203.0.113.7"); + request.addHeader("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + request.addHeader("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + return request; + } + @Test void omitsObservationForMalformedProxyIdOrNonProxyMode() { assertNoObservation("trusted_tcp_proxy", "not-a-uuid"); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java index c2775dd835..db256f692f 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java @@ -69,6 +69,8 @@ public final class HostedIdentityContract { public static final String GRPC_GAME_SESSION_ROLE = "grpc-game-session-service"; public static final String GRPC_SOCIAL_GROUPS_WORKLOAD = "social-groups-service"; public static final String GRPC_SOCIAL_GROUPS_ROLE = "grpc-social-groups-service"; + public static final String GRPC_GATEWAY_WORKLOAD = "spring-cloud-gateway"; + public static final String GRPC_GATEWAY_CLIENT_ROLE = "grpc-spring-cloud-gateway"; public static final List GRPC_PUBLICATION_WORKLOADS = List.of( "game-design-service", @@ -107,9 +109,17 @@ public static boolean isGrpcWorkloadIdentityRole(String role) { return GRPC_ACCOUNT_ROLE.equals(role) || GRPC_GAME_SESSION_ROLE.equals(role) || GRPC_SOCIAL_GROUPS_ROLE.equals(role) + || GRPC_GATEWAY_CLIENT_ROLE.equals(role) || isGrpcPublicationRole(role); } + /** + * Gateway's workload identity is client-only; the other workload identity roles also serve TLS. + */ + public static boolean grpcWorkloadIdentityServesTls(String role) { + return !GRPC_GATEWAY_CLIENT_ROLE.equals(role); + } + public static boolean isGrpcPublicationRole(String role) { return role != null && GRPC_PUBLICATION_WORKLOADS.stream() diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java index 7ca52f52a8..a3dde2ad68 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java @@ -231,6 +231,17 @@ private RoleMaterial grpcSocialGroups( batch); } + private RoleMaterial grpcGatewayClient( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + HostedIdentityContract.GRPC_GATEWAY_WORKLOAD, + plan.grpcGatewayClientCertificateName(), + batch); + } + private RoleMaterial grpcWorkloadIdentity( KubernetesClient client, EnvironmentIdentityPlan plan, @@ -243,7 +254,7 @@ private RoleMaterial grpcWorkloadIdentity( new RoleExpectation( plan.grpcWorkloadIdentityDnsNames(workload), List.of(plan.grpcWorkloadIdentityUriSan(workload)), - true, + HostedIdentityContract.grpcWorkloadIdentityServesTls(role), true, "kubernetes.io/tls", properties.getGrpcTrustAnchorSha256()); @@ -406,6 +417,9 @@ private RotationSnapshot rotationSnapshot(KubernetesClient client, EnvironmentId observations.put( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, rotationObservation(client, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); + observations.put( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)); String selectedRole = selectSerializedRole( observations.values().stream().map(RotationObservation::state).toList()); @@ -1293,6 +1307,10 @@ public RoleMaterial grpcSocialGroups() { return CertificateMaterialService.this.grpcSocialGroups(client, plan, this); } + public RoleMaterial grpcGatewayClient() { + return CertificateMaterialService.this.grpcGatewayClient(client, plan, this); + } + private List certificateRequests() { if (certificateRequests == null) { certificateRequests = diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java index 2bd9d9f1c7..58696f1d4e 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java @@ -125,6 +125,18 @@ public GenericKubernetesResource grpcSocialGroups( renewBefore); } + /** Builds Gateway's client-only identity for its authenticated Game Session WebSocket hop. */ + public GenericKubernetesResource grpcGatewayClient( + EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + HostedIdentityContract.GRPC_GATEWAY_WORKLOAD, + plan.grpcGatewayClientCertificateName(), + plan.grpcGatewayClientSourceSecretName(), + renewBefore); + } + GenericKubernetesResource grpcWorkloadIdentity( EnvironmentIdentityPlan plan, String role, @@ -140,7 +152,9 @@ GenericKubernetesResource grpcWorkloadIdentity( plan.grpcIssuer(), plan.grpcWorkloadIdentityDnsNames(workload), List.of(plan.grpcWorkloadIdentityUriSan(workload)), - List.of("digital signature", "key encipherment", "server auth", "client auth"), + HostedIdentityContract.grpcWorkloadIdentityServesTls(role) + ? List.of("digital signature", "key encipherment", "server auth", "client auth") + : List.of("digital signature", "key encipherment", "client auth"), HostedIdentityProperties.INTERNAL_CERTIFICATE_DURATION, renewBefore); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java index decd481f6b..af05c36980 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java @@ -116,7 +116,12 @@ public RolloutResult sync( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, "social-groups-leaf", - "Social Groups gRPC workload identity revision is required"))) { + "Social Groups gRPC workload identity revision is required"), + new RequiredGrpcWorkloadRevision( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + HostedIdentityContract.GRPC_GATEWAY_WORKLOAD, + "gateway-client-leaf", + "Gateway client workload identity revision is required"))) { String revision = grpcWorkloadIdentityRevisions.get(workloadRevision.role()); if (revision == null) { throw new IllegalArgumentException(workloadRevision.missingRevisionMessage()); @@ -146,6 +151,7 @@ public RolloutResult sync( requiredGrpcConsumers.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); requiredGrpcConsumers.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); requiredGrpcConsumers.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + requiredGrpcConsumers.add(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD); } boolean grpcReady = requiredGrpcConsumers.stream() diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java index f6da572281..aaf073bfe0 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java @@ -184,6 +184,8 @@ public static List identitySecretNames(EnvironmentIdentityPlan plan) { names.add(plan.grpcGameSessionSourceSecretName() + "-previous"); names.add(plan.grpcSocialGroupsSourceSecretName()); names.add(plan.grpcSocialGroupsSourceSecretName() + "-previous"); + names.add(plan.grpcGatewayClientSourceSecretName()); + names.add(plan.grpcGatewayClientSourceSecretName() + "-previous"); return List.copyOf(names); } @@ -244,6 +246,7 @@ public static List requiredCertificateNames(EnvironmentIdentityPlan plan names.add(plan.grpcAccountCertificateName()); names.add(plan.grpcGameSessionCertificateName()); names.add(plan.grpcSocialGroupsCertificateName()); + names.add(plan.grpcGatewayClientCertificateName()); return List.copyOf(names); } @@ -263,6 +266,7 @@ static List runtimeSecretNames(EnvironmentIdentityPlan plan) { names.add(plan.grpcAccountSecretName()); names.add(plan.grpcGameSessionSecretName()); names.add(plan.grpcSocialGroupsSecretName()); + names.add(plan.grpcGatewayClientSecretName()); return List.copyOf(names); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java index 3c2f761f80..aac7258f1e 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java @@ -46,7 +46,8 @@ public record EnvironmentIdentityPlan( Stream.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)) .collect(Collectors.toUnmodifiableSet()); if (!grpcWorkloadIdentityCertificateNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) || !grpcWorkloadIdentitySecretNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) @@ -141,6 +142,20 @@ public String grpcSocialGroupsSourceSecretName() { HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); } + public String grpcGatewayClientCertificateName() { + return grpcWorkloadIdentityCertificateNames.get( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); + } + + public String grpcGatewayClientSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); + } + + public String grpcGatewayClientSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); + } + public String grpcPublicationUriSan(String workload) { return grpcWorkloadIdentityUriSan(workload); } @@ -154,6 +169,9 @@ public String grpcWorkloadIdentityUriSan(String workload) { } public List grpcWorkloadIdentityDnsNames(String workload) { + if (HostedIdentityContract.GRPC_GATEWAY_WORKLOAD.equals(workload)) { + return List.of(); + } return List.of( workload, workload + "." + runtimeNamespace, diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java index 745e77d546..1970135daf 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java @@ -17,6 +17,7 @@ public class HostedEnvironmentIdentityStatus { private RoleStatus grpcAccountService; private RoleStatus grpcGameSessionService; private RoleStatus grpcSocialGroupsService; + private RoleStatus grpcGatewayClient; private Map grpcPublication; private RuntimeProfile profile; @@ -113,6 +114,14 @@ public void setGrpcSocialGroupsService(RoleStatus grpcSocialGroupsService) { this.grpcSocialGroupsService = copyRole(grpcSocialGroupsService); } + public RoleStatus getGrpcGatewayClient() { + return copyRole(grpcGatewayClient); + } + + public void setGrpcGatewayClient(RoleStatus grpcGatewayClient) { + this.grpcGatewayClient = copyRole(grpcGatewayClient); + } + public Map getGrpcPublication() { if (grpcPublication == null) { return null; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java index a9fb3eb6e4..da3836b682 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java @@ -30,6 +30,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; @@ -776,9 +777,7 @@ private static boolean websocketUpgrade(SSLSocket socket, String hostname, int p byte[] nonceBytes = new byte[16]; WEBSOCKET_NONCE_SOURCE.nextBytes(nonceBytes); String nonce = Base64.getEncoder().encodeToString(nonceBytes); - byte[] connectionIdBytes = new byte[16]; - WEBSOCKET_NONCE_SOURCE.nextBytes(connectionIdBytes); - String connectionId = Base64.getUrlEncoder().withoutPadding().encodeToString(connectionIdBytes); + String connectionId = UUID.randomUUID().toString(); String expectedAccept = websocketAccept(nonce); OutputStream output = socket.getOutputStream(); output.write( diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 88707e8363..e5447bfe97 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -175,6 +175,9 @@ public UpdateControl reconcile( materialRequests.add( new RoleMaterialRequest( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, materialization::grpcSocialGroups)); + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, materialization::grpcGatewayClient)); List rolePipeline = new ArrayList<>(); for (RoleMaterialRequest request : materialRequests) { CertificateMaterialService.RoleMaterial material = request.material().get(); @@ -255,6 +258,9 @@ public UpdateControl reconcile( workloadIdentityRevisions.put( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, projections.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE).revision()); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + projections.get(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE).revision()); DeploymentRolloutService.RolloutResult rollout = deploymentRolloutService.sync( client, @@ -552,7 +558,8 @@ private boolean workloadIdentityEvidenceComplete() { .allMatch(this::roleReady) && roleReady(HostedIdentityContract.GRPC_ACCOUNT_ROLE) && roleReady(HostedIdentityContract.GRPC_GAME_SESSION_ROLE) - && roleReady(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + && roleReady(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE) + && roleReady(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); } private boolean roleReady(String role) { @@ -1059,7 +1066,7 @@ private UpdateControl status( phase = HostedEnvironmentIdentityStatus.Phase.Verifying; reason = "WorkloadIdentityEvidenceIncomplete"; message = - "all five protected publication projections and the exact Account, Game Session, and Social Groups workload identities are required for readiness; readiness does not authorize publication methods"; + "all five protected publication projections and the exact Account, Game Session, Social Groups, and Gateway client workload identities are required for readiness; readiness does not authorize publication methods"; } HostedEnvironmentIdentityStatus updatedStatus = statusService.status( @@ -1096,6 +1103,10 @@ private UpdateControl status( roleStatus( materials.material(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), previousRole(resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE))); + updatedStatus.setGrpcGatewayClient( + roleStatus( + materials.material(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE))); updatedStatus.setGrpcPublication(publicationRoleStatus(resource, materials)); resource.setStatus(updatedStatus); return UpdateControl.patchStatus(resource).rescheduleAfter(properties.getReconcileInterval()); @@ -1162,6 +1173,8 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( resource.getStatus().getGrpcGameSessionService(); case HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE -> resource.getStatus().getGrpcSocialGroupsService(); + case HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE -> + resource.getStatus().getGrpcGatewayClient(); default -> throw new IllegalArgumentException("unsupported identity role: " + role); }; } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java index 03ed3cd322..e16638fc96 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java @@ -76,7 +76,10 @@ public EnvironmentIdentityPlan plan(String name) { HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD), Map.entry( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD))) { + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD), + Map.entry( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + HostedIdentityContract.GRPC_GATEWAY_WORKLOAD))) { String role = workloadIdentity.getKey(); String workload = workloadIdentity.getValue(); String certificateAndSourceName = materialPrefix + "-grpc-" + workload; diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java index 39ae3f8dd2..b4e98dcc23 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java @@ -80,6 +80,37 @@ @ExtendWith(OutputCaptureExtension.class) class CertificateMaterialServiceTest { + @Test + void gatewayClientUnacceptedProjectionValidatesOnlyClientAuthAndExactUri() { + StableBatchFixture fixture = stableBatchFixture(); + Secret projection = + fixture + .secretClient() + .runtimeSecrets() + .withName(fixture.plan().grpcGatewayClientSecretName()) + .get(); + projection + .getMetadata() + .getAnnotations() + .remove(HostedIdentityContract.ACCEPTED_REVISION_ANNOTATION); + + CertificateMaterialService.RoleMaterial material = fixture.batch().grpcGatewayClient(); + + assertEquals(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, material.role()); + assertEquals(SERIALIZED_IN_FLIGHT, material.state()); + verify(fixture.validator()) + .validateIdentity( + org.mockito.ArgumentMatchers.any(Secret.class), + org.mockito.ArgumentMatchers.eq(List.of()), + org.mockito.ArgumentMatchers.eq( + List.of("spiffe://firemud/ns/pr-42/sa/spring-cloud-gateway")), + org.mockito.ArgumentMatchers.eq("kubernetes.io/tls"), + org.mockito.ArgumentMatchers.eq(false), + org.mockito.ArgumentMatchers.eq(true), + org.mockito.ArgumentMatchers.eq(fixture.properties().getGrpcTrustAnchorSha256())); + verifyNoInteractions(fixture.grpcGenerator()); + } + @Test void roleMaterialStatesRetainCanonicalStatusValues() { assertEquals("source-ready", SOURCE_READY.statusValue()); @@ -457,7 +488,8 @@ void materializationBatchReusesOneRotationSelectionSnapshot() { plan.grpcPublicationSecretName("automation-scripting-service"), plan.grpcAccountSecretName(), plan.grpcGameSessionSecretName(), - plan.grpcSocialGroupsSecretName()), + plan.grpcSocialGroupsSecretName(), + plan.grpcGatewayClientSecretName()), java.util.Set.copyOf(read.getAllValues())); clearInvocations(runtimeSecrets); @@ -2011,6 +2043,26 @@ void grpcUsesTheAcceptedProjectionWithoutRereadingTheDeferredSource() { .thenReturn(socialGroupsSourceResource); when(socialGroupsSourceResource.get()) .thenReturn(certManagerSource(plan, socialGroupsRole, socialGroupsSourceName, data)); + String gatewayClientRole = HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE; + String gatewayClientName = plan.grpcGatewayClientSecretName(); + String gatewayClientSourceName = plan.grpcGatewayClientSourceSecretName(); + String gatewayClientRevision = SecretProjectionService.revisionForRole(gatewayClientRole, data); + Resource gatewayClientProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(gatewayClientName)) + .thenReturn(gatewayClientProjectionResource); + when(gatewayClientProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + gatewayClientRole, + gatewayClientName, + data, + acceptedAnnotations(gatewayClientRevision, "1".repeat(64)))); + Resource gatewayClientSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(gatewayClientSourceName)) + .thenReturn(gatewayClientSourceResource); + when(gatewayClientSourceResource.get()) + .thenReturn(certManagerSource(plan, gatewayClientRole, gatewayClientSourceName, data)); Secret ownedGrpc = ownedSecret(plan, HostedIdentityContract.GRPC_ROLE, plan.grpcSecretName(), data, Map.of()); Resource grpcSourceResource = mock(Resource.class); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java index 9a3fed3895..916e83d7c1 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.Map; @@ -14,6 +15,20 @@ import org.junit.jupiter.api.Test; class CertificateResourceFactoryTest { + @Test + void onlyGatewayWorkloadIdentityRoleIsClientOnly() { + var plan = new EnvironmentIdentityPlanner(new HostedIdentityProperties()).plan("pr-42"); + + assertFalse( + HostedIdentityContract.grpcWorkloadIdentityServesTls( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)); + for (String role : plan.grpcWorkloadIdentityCertificateNames().keySet()) { + if (!HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + assertTrue(HostedIdentityContract.grpcWorkloadIdentityServesTls(role), role); + } + } + } + @Test void ingressCertificateUsesPublicServerMaterialContract() { var plan = new EnvironmentIdentityPlanner(new HostedIdentityProperties()).plan("pr-42"); @@ -216,6 +231,29 @@ void socialGroupsCertificateUsesExactStableWorkloadIdentity() { assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); } + @Test + void gatewayClientHasOnlyClientAuthAndItsExactNamespaceUri() { + var properties = new HostedIdentityProperties(); + for (String environment : java.util.List.of("pr-42", "dev-demo")) { + var plan = new EnvironmentIdentityPlanner(properties).plan(environment); + var certificate = + new CertificateResourceFactory().grpcGatewayClient(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + assertEquals(plan.grpcGatewayClientCertificateName(), certificate.getMetadata().getName()); + assertEquals(plan.grpcGatewayClientSourceSecretName(), certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of( + "spiffe://firemud/ns/" + plan.runtimeNamespace() + "/sa/spring-cloud-gateway"), + certificateSpec.get("uris")); + assertEquals(null, certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); + } + } + @Test void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { var declaredMethods = @@ -227,7 +265,7 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { .filter(method -> java.lang.reflect.Modifier.isPublic(method.getModifiers())) .toList(); - assertEquals(8, publicMethods.size()); + assertEquals(9, publicMethods.size()); assertEquals( java.util.Set.of( "ingress", @@ -237,7 +275,8 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { "grpcPublication", "grpcAccount", "grpcGameSession", - "grpcSocialGroups"), + "grpcSocialGroups", + "grpcGatewayClient"), publicMethods.stream() .map(java.lang.reflect.Method::getName) .collect(java.util.stream.Collectors.toUnmodifiableSet())); @@ -250,6 +289,7 @@ void internalCertificatesDefensivelyRejectInvalidRenewalWindows() { assertInvalidRenewalWindow(() -> factory.gatewayInternalWs(plan, null)); assertInvalidRenewalWindow(() -> factory.tcpProxyBridge(plan, null)); + assertInvalidRenewalWindow(() -> factory.grpcGatewayClient(plan, null)); assertInvalidRenewalWindow(() -> factory.grpcPublication(plan, "game-design-service", null)); for (Duration invalidRenewBefore : diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java index 6a571ae977..c44e189106 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java @@ -71,6 +71,7 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( "account-service", "game-session-service", "social-groups-service", + "spring-cloud-gateway", "game-design-service", "world-management-service", "entity-management-service", @@ -82,6 +83,15 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( "tcp-proxy-service", Map.of(HostedIdentityContract.TELNET_REVISION_ANNOTATION, "telnet-current"), 3L)); + when(graph.resources().get("spring-cloud-gateway").get()) + .thenReturn( + readyDeployment( + "spring-cloud-gateway", + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision( + "grpc-current", "gateway-client-current", "gateway-client-leaf")), + 3L)); ArgumentCaptor accountReplacement = ArgumentCaptor.forClass(Deployment.class); ArgumentCaptor gameSessionReplacement = ArgumentCaptor.forClass(Deployment.class); ArgumentCaptor socialGroupsReplacement = ArgumentCaptor.forClass(Deployment.class); @@ -160,6 +170,8 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "game-session-current"); workloadIdentityRevisions.put( HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "social-groups-current"); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, "gateway-client-current"); DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -261,13 +273,14 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( } @Test - void sharedGrpcRevisionRollsAllEightDistinctConsumersAndLeavesUnrelatedWorkloadUntouched() { + void sharedGrpcRevisionRollsAllNineIdentityConsumersAndLeavesUnrelatedWorkloadUntouched() { EnvironmentIdentityPlan plan = planWithConsumers(); List grpcWorkloads = new java.util.ArrayList<>(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); grpcWorkloads.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + grpcWorkloads.add(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD); String[] deploymentNames = java.util.stream.Stream.concat( java.util.stream.Stream.of("tcp-proxy-service", "logging-admin-service"), @@ -349,6 +362,7 @@ void declaredWorkloadIdentityConsumersReceiveCombinedTrustAndLeafRevision() { grpcWorkloads.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + grpcWorkloads.add(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD); String[] deploymentNames = java.util.stream.Stream.concat( java.util.stream.Stream.of("tcp-proxy-service"), grpcWorkloads.stream()) @@ -383,7 +397,7 @@ void declaredWorkloadIdentityConsumersReceiveCombinedTrustAndLeafRevision() { lockedResources.put(workload, locked); } - assertEquals(8, workloadIdentityRevisions.size()); + assertEquals(9, workloadIdentityRevisions.size()); DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -424,6 +438,7 @@ void dedicatedLeafRolloutsGateReadinessOutsideThePlanConsumerList() { grpcWorkloads.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + grpcWorkloads.add(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD); Map> pendingReplacements = new LinkedHashMap<>(); Map> workloadLocks = new LinkedHashMap<>(); @@ -431,7 +446,8 @@ void dedicatedLeafRolloutsGateReadinessOutsideThePlanConsumerList() { List.of( HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)) { + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + HostedIdentityContract.GRPC_GATEWAY_WORKLOAD)) { EnvironmentIdentityPlan plan = planWithConsumers(); String[] deploymentNames = java.util.stream.Stream.concat( @@ -1262,6 +1278,9 @@ private static String grpcRoleForWorkload(String workload) { if (HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD.equals(workload)) { return HostedIdentityContract.GRPC_GAME_SESSION_ROLE; } + if (HostedIdentityContract.GRPC_GATEWAY_WORKLOAD.equals(workload)) { + return HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE; + } if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD.equals(workload)) { return HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE; } @@ -1275,6 +1294,9 @@ private static String leafKindForRole(String role) { if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { return "game-session-leaf"; } + if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + return "gateway-client-leaf"; + } if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { return "social-groups-leaf"; } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java index ff8128ad4e..9219701a37 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java @@ -237,7 +237,8 @@ void identityRoleNamesOnlyCoverCertManagerCertificates() { "pr-42-grpc-automation-scripting-service", "pr-42-grpc-account-service", "pr-42-grpc-game-session-service", - "pr-42-grpc-social-groups-service"), + "pr-42-grpc-social-groups-service", + "pr-42-grpc-spring-cloud-gateway"), HostedIdentityScopeService.requiredCertificateNames(plan)); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java index 47b6195d43..9a57ad1b93 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java @@ -413,6 +413,20 @@ static StableBatchFixture stableBatchFixture() { .getMetadata() .getAnnotations() .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); SecretMaterialValidator validator = mock(SecretMaterialValidator.class); SecretMaterialValidator.MaterialSummary summary = new SecretMaterialValidator.MaterialSummary( @@ -532,6 +546,9 @@ static String secretName(EnvironmentIdentityPlan plan, String role) { if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { yield plan.grpcSocialGroupsSecretName(); } + if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + yield plan.grpcGatewayClientSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { yield plan.grpcPublicationSecretName( role.substring(HostedIdentityContract.GRPC_PUBLICATION_ROLE_PREFIX.length())); @@ -551,6 +568,9 @@ static String sourceSecretName(EnvironmentIdentityPlan plan, String role) { if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { return plan.grpcSocialGroupsSourceSecretName(); } + if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + return plan.grpcGatewayClientSourceSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { return plan.grpcPublicationSourceSecretName(grpcPublicationWorkload(role)); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java index 928da2e43a..19d4d1c78e 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java @@ -1407,7 +1407,8 @@ void caRotationValidatesOnlyTheSelectedNewSourceAndPinsOtherSharedRoles() { List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)) { stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); } stubCertificate( @@ -1589,7 +1590,8 @@ private static DriftSelectionFixture driftSelectionFixture(boolean sourceAdvance List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)) { stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); } stubCertificate( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java index 832187b658..f05eef0094 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java @@ -18,6 +18,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.KeyPairGenerator; import java.security.MessageDigest; @@ -31,6 +32,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -564,10 +566,11 @@ void internalBridgeProbeRequiresAWebSocketUpgradeAndSendsTrustedProxyIdentity() String connectionId = requestHeader(fixture.request(), "X-Proxy-Connection-Id"); String nonce = requestHeader(fixture.request(), "Sec-WebSocket-Key"); assertNotNull(connectionId); - assertTrue(connectionId.matches("[A-Za-z0-9_-]{22}")); + assertCanonicalTcpProxyConnectionId(connectionId); + assertEquals(16, Base64.getDecoder().decode(nonce).length); assertFalse( java.util.Arrays.equals( - Base64.getDecoder().decode(nonce), Base64.getUrlDecoder().decode(connectionId))); + Base64.getDecoder().decode(nonce), uuidBytes(UUID.fromString(connectionId)))); } @Test @@ -589,8 +592,11 @@ void successiveInternalBridgeProbesUseDistinctConnectionIds() throws Exception { assertNotNull(firstConnectionId); assertNotNull(secondConnectionId); assertNotEquals(firstConnectionId, secondConnectionId); - assertTrue(firstConnectionId.matches("[A-Za-z0-9_-]{22}")); - assertTrue(secondConnectionId.matches("[A-Za-z0-9_-]{22}")); + assertCanonicalTcpProxyConnectionId(firstConnectionId); + assertCanonicalTcpProxyConnectionId(secondConnectionId); + assertNotEquals( + requestHeader(first.request(), "Sec-WebSocket-Key"), + requestHeader(second.request(), "Sec-WebSocket-Key")); } @Test @@ -838,6 +844,20 @@ private static String requestHeader(String request, String name) { return null; } + private static void assertCanonicalTcpProxyConnectionId(String connectionId) { + UUID parsed = UUID.fromString(connectionId); + assertEquals(parsed.toString(), connectionId); + assertEquals(4, parsed.version()); + assertEquals(2, parsed.variant()); + } + + private static byte[] uuidBytes(UUID uuid) { + return ByteBuffer.allocate(16) + .putLong(uuid.getMostSignificantBits()) + .putLong(uuid.getLeastSignificantBits()) + .array(); + } + private static String websocketAccept(String nonce) throws Exception { byte[] digest = MessageDigest.getInstance("SHA-1") diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 16e18a534b..85ccd905a5 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -244,7 +244,7 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { status.getGrpcPublication().keySet()); assertTrue(status.getGrpcPublication().values().stream().allMatch(java.util.Objects::nonNull)); assertEquals( - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 8, + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 9, acknowledgedProjections.size()); assertEquals( "awaiting-acceptance", @@ -1651,7 +1651,8 @@ record SourceProgressCase( List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, - HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)) { for (SourceProgressCase rollbackCase : rollbackCases) { DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture( @@ -1689,6 +1690,8 @@ record SourceProgressCase( when(fixture.batch.grpcAccount()).thenReturn(olderSource); } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { when(fixture.batch.grpcGameSession()).thenReturn(olderSource); + } else if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + when(fixture.batch.grpcGatewayClient()).thenReturn(olderSource); } else { when(fixture.batch.grpcSocialGroups()).thenReturn(olderSource); } @@ -1734,6 +1737,9 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { assertNull( HostedIdentityReconciler.previousRole( resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); + assertNull( + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)); HostedEnvironmentIdentityStatus.RoleStatus account = roleStatus("account-revision", 4L, 2L, "a".repeat(64)); @@ -1744,6 +1750,9 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { status.setGrpcAccountService(account); status.setGrpcGameSessionService(gameSession); status.setGrpcSocialGroupsService(socialGroups); + HostedEnvironmentIdentityStatus.RoleStatus gatewayClient = + roleStatus("gateway-client-revision", 7L, 5L, "d".repeat(64)); + status.setGrpcGatewayClient(gatewayClient); resource.setStatus(status); HostedEnvironmentIdentityStatus.RoleStatus accountReadback = @@ -1754,6 +1763,16 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { HostedEnvironmentIdentityStatus.RoleStatus socialGroupsReadback = HostedIdentityReconciler.previousRole( resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + HostedEnvironmentIdentityStatus.RoleStatus gatewayClientReadback = + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE); + assertNotSame(gatewayClient, gatewayClientReadback); + assertEquals(gatewayClient.getRevision(), gatewayClientReadback.getRevision()); + assertEquals(gatewayClient.getSourceGeneration(), gatewayClientReadback.getSourceGeneration()); + assertEquals( + gatewayClient.getSourceObjectGeneration(), + gatewayClientReadback.getSourceObjectGeneration()); + assertEquals(gatewayClient.getSpkiSha256(), gatewayClientReadback.getSpkiSha256()); assertNotSame(account, accountReadback); assertNotSame(gameSession, gameSessionReadback); assertEquals(account.getRevision(), accountReadback.getRevision()); @@ -1976,6 +1995,7 @@ private static boolean crdSchemaAccepts(Map propertySchema, Object value) assertEquals(consumerSchema, statusProperties.get("grpcAccountService")); assertEquals(consumerSchema, statusProperties.get("grpcGameSessionService")); assertEquals(consumerSchema, statusProperties.get("grpcSocialGroupsService")); + assertEquals(consumerSchema, statusProperties.get("grpcGatewayClient")); assertEquals( consumerSchema, publicationSchema.get("additionalProperties"), @@ -2363,6 +2383,8 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { assertEquals(1L, status.getGrpcAccountService().getSourceGeneration()); assertEquals(1L, status.getGrpcGameSessionService().getSourceGeneration()); assertEquals(1L, status.getGrpcSocialGroupsService().getSourceGeneration()); + assertEquals("e".repeat(64), status.getGrpcGatewayClient().getSpkiSha256()); + assertEquals(1L, status.getGrpcGatewayClient().getSourceGeneration()); ArgumentCaptor gatewayRevision = ArgumentCaptor.forClass(String.class); ArgumentCaptor> workloadIdentityRevisions = ArgumentCaptor.forClass(Map.class); @@ -2394,7 +2416,9 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "revision-" + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, - "revision-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), + "revision-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, + "revision-" + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE), workloadIdentityRevisions.getValue()); verify(fixture.runtime, times(2)) .validateTcpProxyService(fixture.client, fixture.plan, expected); @@ -2490,6 +2514,8 @@ private static void setGrpcWorkloadRoleStatus( status.setGrpcAccountService(roleStatus); } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { status.setGrpcGameSessionService(roleStatus); + } else if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + status.setGrpcGatewayClient(roleStatus); } else if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { status.setGrpcSocialGroupsService(roleStatus); } else { @@ -2505,6 +2531,9 @@ private static HostedEnvironmentIdentityStatus.RoleStatus grpcWorkloadRoleStatus if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { return status.getGrpcGameSessionService(); } + if (HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + return status.getGrpcGatewayClient(); + } if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { return status.getGrpcSocialGroupsService(); } @@ -2597,6 +2626,8 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr .thenReturn(material(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "c")); when(batch.grpcSocialGroups()) .thenReturn(material(plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "d")); + when(batch.grpcGatewayClient()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, "e")); when(batch.grpcPublication(anyString())) .thenAnswer( invocation -> { diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java index 35ebee8251..dca31f20b2 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java @@ -82,6 +82,18 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { assertEquals( plan.grpcSocialGroupsSecretName(), plan.secretName(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); + assertEquals("pr-42-grpc-spring-cloud-gateway", plan.grpcGatewayClientCertificateName()); + assertEquals("pr-42-grpc-spring-cloud-gateway", plan.grpcGatewayClientSourceSecretName()); + assertEquals("firemud-grpc-spring-cloud-gateway", plan.grpcGatewayClientSecretName()); + assertEquals(9, plan.grpcWorkloadIdentitySecretNames().size()); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/spring-cloud-gateway", + plan.grpcWorkloadIdentityUriSan(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD)); + assertEquals( + List.of(), plan.grpcWorkloadIdentityDnsNames(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD)); + assertEquals( + plan.grpcGatewayClientSecretName(), + plan.secretName(HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { assertEquals("pr-42-grpc-" + workload, plan.grpcPublicationSourceSecretName(workload)); assertEquals("firemud-grpc-" + workload, plan.grpcPublicationSecretName(workload)); @@ -90,6 +102,33 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { } } + @Test + void workloadDnsNamesUseWorkloadNamesAndKeepGatewayClientWithoutServerNames() { + List serverWorkloads = + new ArrayList<>(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); + serverWorkloads.addAll( + List.of( + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)); + + for (String environment : List.of("pr-42", "dev-demo")) { + var plan = planner.plan(environment); + assertEquals( + List.of(), + plan.grpcWorkloadIdentityDnsNames(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD)); + for (String workload : serverWorkloads) { + assertEquals( + List.of( + workload, + workload + "." + plan.runtimeNamespace(), + workload + "." + plan.runtimeNamespace() + ".svc", + workload + "." + plan.runtimeNamespace() + ".svc.cluster.local"), + plan.grpcWorkloadIdentityDnsNames(workload)); + } + } + } + @Test void derivesDevDemoWithoutAcceptingUserSuppliedTopology() { var plan = planner.plan("dev-demo"); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java index c65c51c9ac..3b33943730 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java @@ -3,21 +3,35 @@ import io.netty.channel.ChannelOption; import java.time.Duration; import java.util.Map; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; +import net.firedevops.firemud.springcloudgateway.websocket.AuthenticatedGameplayWebSocketClient; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketBridgeHandler; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.util.StringUtils; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; +import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; +import org.springframework.web.server.WebHandler; import reactor.netty.http.client.HttpClient; @Configuration public class GameplayWebSocketBridgeConfig { + private static final String AUTHENTICATED_UPSTREAM_URL_PROPERTY = + "firemud.gateway.gameplay.bridge.authenticated-upstream-url"; @Bean @Primary @@ -34,9 +48,36 @@ GameplayWebSocketBridgeHandler gameplayWebSocketBridgeHandler( ReactorNettyWebSocketClient gameplayWebSocketClient, GameplayWebSocketBridgeProperties properties, RuntimeIdentity runtimeIdentity, - GameplayWebSocketObservability gameplayWebSocketObservability) { + GameplayWebSocketObservability gameplayWebSocketObservability, + ObjectProvider authenticatedClient) { return new GameplayWebSocketBridgeHandler( - gameplayWebSocketClient, properties, runtimeIdentity, gameplayWebSocketObservability); + gameplayWebSocketClient, + properties, + runtimeIdentity, + gameplayWebSocketObservability, + authenticatedClient.getIfAvailable()); + } + + @Bean(initMethod = "initialize", destroyMethod = "close") + @Conditional(AuthenticatedUpstreamConfigured.class) + AuthenticatedGameplayWebSocketClient authenticatedGameplayWebSocketClient( + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${firemud.gateway.gameplay.bridge.authenticated-upstream-url}") String upstream, + @Value( + "${firemud.gateway.gameplay.bridge.tls.cert-chain:${FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH:}}") + String certificate, + @Value( + "${firemud.gateway.gameplay.bridge.tls.private-key:${FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH:}}") + String privateKey, + @Value( + "${firemud.gateway.gameplay.bridge.tls.ca-cert:${FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH:}}") + String caCertificate) { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return new AuthenticatedGameplayWebSocketClient(tls, namespace, upstream); } @Bean @@ -44,12 +85,12 @@ HandlerMapping gameplayWebSocketBridgeMapping( GameplayWebSocketBridgeHandler gameplayWebSocketBridgeHandler) { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(-1); - mapping.setUrlMap( - Map.of( - "/ws/game", - gameplayWebSocketBridgeHandler, - "/ws/game/**", - gameplayWebSocketBridgeHandler)); + HandshakeWebSocketService upgrade = new HandshakeWebSocketService(); + WebHandler bridge = + exchange -> + upgrade.handleRequest( + exchange, VerifiedTcpProxyOrigin.bind(exchange, gameplayWebSocketBridgeHandler)); + mapping.setUrlMap(Map.of("/ws/game", bridge, "/ws/game/**", bridge)); return mapping; } @@ -58,4 +99,12 @@ HandlerMapping gameplayWebSocketBridgeMapping( WebSocketHandlerAdapter gameplayWebSocketHandlerAdapter() { return new WebSocketHandlerAdapter(); } + + static final class AuthenticatedUpstreamConfigured implements Condition { + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + String upstream = context.getEnvironment().getProperty(AUTHENTICATED_UPSTREAM_URL_PROPERTY); + return StringUtils.hasText(upstream) && !"false".equalsIgnoreCase(upstream.trim()); + } + } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java index a2093f9821..4a0d2b9135 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java @@ -115,6 +115,15 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { final RoutingBundle canonicalRoutingBundle = incomingRoutingBundle; final String canonicalLocale = canonicalLocale(exchange.getRequest().getHeaders()); + if (trustedTcpProxy && isGameplayRoute && tcpProxyTrustPolicy.requiresClientCertificate()) { + try { + VerifiedTcpProxyOrigin.retain(exchange, canonicalClientIp, incomingProxyConnectionId); + } catch (RuntimeException malformed) { + exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); + return exchange.getResponse().setComplete(); + } + } + ServerWebExchange mutated = exchange .mutate() diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java new file mode 100644 index 0000000000..e8ccaaef12 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.springcloudgateway.filter; + +import java.util.UUID; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.WebSocketSession; +import org.springframework.web.server.ServerWebExchange; + +/** Process-private proof produced only after this Gateway authenticates the TCP Proxy hop. */ +public final class VerifiedTcpProxyOrigin { + private static final String ATTRIBUTE = VerifiedTcpProxyOrigin.class.getName(); + private final String clientAddress; + private final UUID proxyConnectionId; + + private VerifiedTcpProxyOrigin(String clientAddress, UUID proxyConnectionId) { + this.clientAddress = clientAddress; + this.proxyConnectionId = proxyConnectionId; + } + + static void retain(ServerWebExchange exchange, String address, String connectionId) { + UUID id = UUID.fromString(connectionId); + if (!id.toString().equals(connectionId) || id.version() != 4 || id.variant() != 2) + throw new IllegalArgumentException("Canonical TCP Proxy connection UUID required"); + exchange.getAttributes().put(ATTRIBUTE, new VerifiedTcpProxyOrigin(address, id)); + } + + /** Carries the private proof across upgrade without interpreting any request header as proof. */ + public static WebSocketHandler bind(ServerWebExchange exchange, WebSocketHandler handler) { + Object proof = exchange.getAttributes().get(ATTRIBUTE); + return session -> { + session.getAttributes().remove(ATTRIBUTE); + if (proof instanceof VerifiedTcpProxyOrigin origin) + session.getAttributes().put(ATTRIBUTE, origin); + return handler.handle(session); + }; + } + + public static VerifiedTcpProxyOrigin from(WebSocketSession session) { + Object value = session.getAttributes().get(ATTRIBUTE); + return value instanceof VerifiedTcpProxyOrigin origin ? origin : null; + } + + public String clientAddress() { + return clientAddress; + } + + public UUID proxyConnectionId() { + return proxyConnectionId; + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java new file mode 100644 index 0000000000..b1d0e4d719 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.springcloudgateway.websocket; + +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslHandler; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Path; +import java.util.List; +import javax.net.ssl.SSLParameters; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import org.springframework.http.HttpHeaders; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; +import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClient; + +/** Dedicated Gateway-to-Game Session mTLS transport using the existing workload TLS material. */ +public final class AuthenticatedGameplayWebSocketClient implements AutoCloseable { + private final CommonGrpcClientProperties tls; + private final String expectedPeer; + private final String expectedClient; + private final URI upstream; + private final Object publicationLock = new Object(); + private final Runnable beforePublish; + private volatile ReactorNettyWebSocketClient client; + private TlsCertificateWatcher watcher; + private boolean closed; + + public AuthenticatedGameplayWebSocketClient( + CommonGrpcClientProperties properties, String namespace, String upstreamUrl) { + this(properties, namespace, upstreamUrl, () -> {}); + } + + AuthenticatedGameplayWebSocketClient( + CommonGrpcClientProperties properties, + String namespace, + String upstreamUrl, + Runnable beforePublish) { + this.beforePublish = beforePublish; + tls = properties.copy(); + FileBackedGrpcMtlsPolicy.require( + tls, + "Authenticated gameplay WebSocket", + "Workload TLS material required", + "Authenticated gameplay requires mutual TLS"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Exact gameplay workload namespace required"); + upstream = URI.create(upstreamUrl); + if (!"wss".equals(upstream.getScheme()) + || upstream.getHost() == null + || upstream.getUserInfo() != null + || upstream.getQuery() != null + || upstream.getFragment() != null + || !"/ws/game/tcp".equals(upstream.getPath())) + throw new IllegalArgumentException("Dedicated authenticated gameplay wss endpoint required"); + expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + expectedClient = "spiffe://firemud/ns/" + namespace + "/sa/spring-cloud-gateway"; + } + + public void initialize() throws IOException { + reload(); + if (isClosed()) return; + TlsCertificateWatcher newWatcher = + TlsCertificateWatcher.createAndStart( + List.of( + Path.of(tls.getCertChain()), + Path.of(tls.getPrivateKey()), + Path.of(tls.getCaCert())), + () -> { + try { + reload(); + } catch (IOException failure) { + throw new IllegalStateException( + "Authenticated gameplay TLS reload failed", failure); + } + }); + boolean discardWatcher; + synchronized (publicationLock) { + discardWatcher = closed; + if (!discardWatcher) watcher = newWatcher; + } + if (discardWatcher) newWatcher.close(); + } + + void reload() throws IOException { + if (isClosed()) return; + try (var input = java.nio.file.Files.newInputStream(Path.of(tls.getCertChain()))) { + var certificate = + (java.security.cert.X509Certificate) + java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(input); + certificate.checkValidity(); + if (certificate.getExtendedKeyUsage() == null + || !certificate.getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.2") + || GrpcPeerIdentity.fromCertificate(certificate) + .filter(peer -> expectedClient.equals(peer.uri())) + .isEmpty()) + throw new IllegalArgumentException("Exact Gateway workload client identity required"); + } catch (java.security.cert.CertificateException invalid) { + throw new IOException("Invalid Gateway workload TLS certificate", invalid); + } + var context = + SslContextBuilder.forClient() + .keyManager(Path.of(tls.getCertChain()).toFile(), Path.of(tls.getPrivateKey()).toFile()) + .trustManager(Path.of(tls.getCaCert()).toFile()) + .protocols("TLSv1.3", "TLSv1.2") + .build(); + HttpClient http = + HttpClient.newConnection() + .secure( + spec -> + spec.sslContext(context) + .handlerConfigurator( + handler -> { + SSLParameters parameters = handler.engine().getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + handler.engine().setSSLParameters(parameters); + })) + .doOnRequest( + (request, connection) -> { + SslHandler handler = connection.channel().pipeline().get(SslHandler.class); + if (handler == null + || GrpcPeerIdentity.fromSslSession(handler.engine().getSession()) + .filter(identity -> expectedPeer.equals(identity.uri())) + .isEmpty()) + throw new IllegalStateException("Authenticated Game Session peer required"); + }); + ReactorNettyWebSocketClient newClient = new ReactorNettyWebSocketClient(http); + beforePublish.run(); + synchronized (publicationLock) { + if (!closed) client = newClient; + } + } + + private boolean isClosed() { + synchronized (publicationLock) { + return closed; + } + } + + public Mono execute(HttpHeaders headers, WebSocketHandler handler) { + return Mono.defer( + () -> { + ReactorNettyWebSocketClient current = client; + if (current == null) { + return Mono.error( + new IllegalStateException("Authenticated gameplay client unavailable")); + } + return current.execute(upstream, headers, handler); + }); + } + + public URI upstream() { + return upstream; + } + + @Override + public void close() throws IOException { + TlsCertificateWatcher currentWatcher; + synchronized (publicationLock) { + if (closed) return; + closed = true; + client = null; + currentWatcher = watcher; + watcher = null; + } + if (currentWatcher != null) currentWatcher.close(); + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 806f70dd32..569d8fbd30 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.runtime.RuntimeLoggingContext; import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; @@ -59,26 +60,39 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi TRANSPORT_SESSION_HEADER); private final ReactorNettyWebSocketClient client; + private final AuthenticatedGameplayWebSocketClient authenticatedClient; private final GameplayWebSocketBridgeProperties properties; private final RuntimeIdentity runtimeIdentity; private final GameplayWebSocketObservability gameplayWebSocketObservability; private final Set activeBridges = ConcurrentHashMap.newKeySet(); private final AtomicBoolean shuttingDown = new AtomicBoolean(); + private final AtomicBoolean missingAuthenticatedClientWarningLogged = new AtomicBoolean(); private final Object lifecycleMonitor = new Object(); private volatile Mono shutdownCompletion; + public GameplayWebSocketBridgeHandler( + ReactorNettyWebSocketClient client, + GameplayWebSocketBridgeProperties properties, + RuntimeIdentity runtimeIdentity, + GameplayWebSocketObservability gameplayWebSocketObservability) { + this(client, properties, runtimeIdentity, gameplayWebSocketObservability, null); + } + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "Injected client, properties, and runtime identity remain internal.") + justification = + "Injected clients, properties, runtime identity, and observability remain internal.") public GameplayWebSocketBridgeHandler( ReactorNettyWebSocketClient client, GameplayWebSocketBridgeProperties properties, RuntimeIdentity runtimeIdentity, - GameplayWebSocketObservability gameplayWebSocketObservability) { + GameplayWebSocketObservability gameplayWebSocketObservability, + AuthenticatedGameplayWebSocketClient authenticatedClient) { this.client = client; this.properties = properties; this.runtimeIdentity = runtimeIdentity; this.gameplayWebSocketObservability = gameplayWebSocketObservability; + this.authenticatedClient = authenticatedClient; } GameplayWebSocketBridgeHandler( @@ -98,8 +112,38 @@ public Mono handle(WebSocketSession downstream) { .doFinally(signal -> activeBridges.remove(state)); } } + var origin = + net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin.from(downstream); + if ("trusted_tcp_proxy" + .equals(downstream.getHandshakeInfo().getHeaders().getFirst(CONNECTION_MODE_HEADER)) + && origin == null + && authenticatedClient != null) { + return closeDownstream(state, gameplayWebSocketObservability.authenticatedTcpOriginRequired()) + .doFinally(signal -> activeBridges.remove(state)); + } + if (origin != null && authenticatedClient == null) { + // This configuration cannot change during the handler's lifetime; do not log every retry. + if (missingAuthenticatedClientWarningLogged.compareAndSet(false, true)) { + LOG.warn( + "Verified TCP Proxy gameplay origin rejected: no authenticated gameplay upstream client is configured; set firemud.gateway.gameplay.bridge.authenticated-upstream-url (logged once per handler)"); + } + return closeDownstream(state, gameplayWebSocketObservability.classify(BACKEND_UNAVAILABLE)) + .doFinally(signal -> activeBridges.remove(state)); + } HttpHeaders upstreamHeaders = buildUpstreamHeaders(downstream); - URI upstreamUri = URI.create(properties.upstreamUrl()); + Function> upstreamConnector; + if (origin == null) { + URI upstreamUri = URI.create(properties.upstreamUrl()); + upstreamConnector = + upstreamHandler -> client.execute(upstreamUri, upstreamHeaders, upstreamHandler); + } else { + upstreamHeaders.remove(TRANSPORT_SESSION_HEADER); + upstreamHeaders.set("X-Client-IP", origin.clientAddress()); + upstreamHeaders.set("X-Proxy-Connection-Id", origin.proxyConnectionId().toString()); + upstreamHeaders.set(CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); + upstreamConnector = + upstreamHandler -> authenticatedClient.execute(upstreamHeaders, upstreamHandler); + } Mono downstreamSend = downstream.send(state.outboundToClient.asFlux().map(text -> downstream.textMessage(text))); @@ -120,7 +164,7 @@ public Mono handle(WebSocketSession downstream) { state.outboundToClient.tryEmitComplete(); }); - Mono upstreamLoop = connectWithRetry(downstream, upstreamUri, upstreamHeaders, state, 0); + Mono upstreamLoop = connectWithRetry(downstream, upstreamConnector, state, 0); return Mono.when(downstreamSend, downstreamReceive, upstreamLoop) .then() .doFinally(signal -> activeBridges.remove(state)); @@ -174,22 +218,19 @@ private Mono getOrCreateShutdownCompletion() { private Mono connectWithRetry( WebSocketSession downstream, - URI upstreamUri, - HttpHeaders upstreamHeaders, + Function> upstreamConnector, BridgeState state, int attempt) { if (state.downstreamClosed.get()) { return Mono.empty(); } Sinks.One connected = Sinks.one(); - Mono sessionLifecycle = - client.execute( - upstreamUri, - upstreamHeaders, - upstream -> { - connected.tryEmitEmpty(); - return bridgeUpstreamSession(downstream, upstream, state); - }); + WebSocketHandler upstreamHandler = + upstream -> { + connected.tryEmitEmpty(); + return bridgeUpstreamSession(downstream, upstream, state); + }; + Mono sessionLifecycle = upstreamConnector.apply(upstreamHandler); return Mono.when(connected.asMono().timeout(UPSTREAM_CONNECT_TIMEOUT), sessionLifecycle) .onErrorResume( GameplayBridgeReconnectException.class, @@ -214,9 +255,9 @@ private Mono connectWithRetry( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then( - connectWithRetry( - downstream, upstreamUri, upstreamHeaders, state, attempt + 1)); + .flatMap( + ignored -> + connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); }) .onErrorResume( GameplayBridgeTerminalCloseException.class, @@ -227,14 +268,12 @@ private Mono connectWithRetry( return closeDownstream(state, terminal.closeClassification()); }) .onErrorResume( - transportError -> - retryTransportFailure(downstream, upstreamUri, upstreamHeaders, state, attempt)); + transportError -> retryTransportFailure(downstream, upstreamConnector, state, attempt)); } private Mono retryTransportFailure( WebSocketSession downstream, - URI upstreamUri, - HttpHeaders upstreamHeaders, + Function> upstreamConnector, BridgeState state, int attempt) { if (state.downstreamClosed.get()) { @@ -256,7 +295,7 @@ private Mono retryTransportFailure( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then(connectWithRetry(downstream, upstreamUri, upstreamHeaders, state, attempt + 1)); + .flatMap(ignored -> connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); } private Mono bridgeUpstreamSession( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java index 501c6e7bb6..7361fc734d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java @@ -100,6 +100,15 @@ public CloseClassification classify(CloseStatus upstreamStatus) { }; } + CloseClassification authenticatedTcpOriginRequired() { + return new CloseClassification( + new CloseStatus(1008, "authenticated_tcp_origin_required"), + POLICY_VIOLATION, + NO_SUBREASON, + false, + UNATTRIBUTED_FAILURE); + } + public CloseClassification slowClientClose() { return close(POLICY_VIOLATION, EDGE_BACKPRESSURE, true, UNATTRIBUTED_FAILURE); } 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 9436e1439c..6c191efea1 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 @@ -54,6 +54,8 @@ class TcpProxyTlsListenerAdmissionIntegrationTest { private static final String TCP_PROXY_URI = "spiffe://firemud/ns/firemud/sa/tcp-proxy-service"; + private static final String PROXY_CONNECTION_ID = "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"; + private static final String NO_FRAME_PROXY_CONNECTION_ID = "7c507311-b226-4d26-8f34-1bbb4159fd33"; @Test void productionConfigurationMapsHealthAndReadinessWhenInternalTlsIsDisabled() { @@ -138,9 +140,8 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception session -> { admittedHeaders.set(session.getHandshakeInfo().getHeaders()); admittedConnections.incrementAndGet(); - if ("no-frame" - .equals( - session.getHandshakeInfo().getHeaders().getFirst("X-Proxy-Connection-Id"))) { + if (NO_FRAME_PROXY_CONNECTION_ID.equals( + session.getHandshakeInfo().getHeaders().getFirst("X-Proxy-Connection-Id"))) { return reactor.core.publisher.Mono.never(); } return session.send( @@ -163,7 +164,8 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception assertThat(admittedConnections).hasValue(1); assertThat(admittedHeaders.get().getFirst("X-Client-IP")).isEqualTo("203.0.113.99"); assertThat(admittedHeaders.get().getFirst("X-Proxy-Client-IP")).isNull(); - assertThat(admittedHeaders.get().getFirst("X-Proxy-Connection-Id")).isEqualTo("conn-123"); + assertThat(admittedHeaders.get().getFirst("X-Proxy-Connection-Id")) + .isEqualTo(PROXY_CONNECTION_ID); assertThat(admittedHeaders.get().getFirst("X-Tenant-Id")).isEqualTo("7"); assertThat(admittedHeaders.get().getFirst("X-Game-Instance-Id")).isEqualTo("42"); assertThat(admittedHeaders.get().getFirst("X-Firemud-Connection-Mode")) @@ -187,7 +189,7 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception .hasValue(2); HttpHeaders noFrameHeaders = bridgeHeaders(); - noFrameHeaders.set("X-Proxy-Connection-Id", "no-frame"); + noFrameHeaders.set("X-Proxy-Connection-Id", NO_FRAME_PROXY_CONNECTION_ID); assertThatThrownBy( () -> connect( @@ -348,7 +350,7 @@ private static Stream enabledTrustProfiles() { private static HttpHeaders bridgeHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("X-Proxy-Client-IP", "203.0.113.99"); - headers.set("X-Proxy-Connection-Id", "conn-123"); + headers.set("X-Proxy-Connection-Id", PROXY_CONNECTION_ID); headers.set("X-Proxy-Tenant-Id", "7"); headers.set("X-Proxy-Game-Instance-Id", "42"); headers.set("X-Firemud-Connection-Mode", "first_party_web"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java index d69547f164..91ff0d08db 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java @@ -1,20 +1,52 @@ package net.firedevops.firemud.springcloudgateway.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; +import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; +import net.firedevops.firemud.springcloudgateway.websocket.AuthenticatedGameplayWebSocketClient; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketBridgeHandler; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedConstruction; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.MapPropertySource; +import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.WebSocketSession; +import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; +import org.springframework.web.server.WebHandler; +import reactor.core.publisher.Mono; class GameplayWebSocketBridgeConfigTest { @@ -40,17 +72,65 @@ void gameplayWebSocketPathIsOwnedByGatewayCode() { SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); assertThat(mapping.getUrlMap()).containsKeys("/ws/game", "/ws/game/**"); assertThat(mapping.getUrlMap().get("/ws/game")) - .isSameAs(context.getBean(GameplayWebSocketBridgeHandler.class)); + .isInstanceOf(WebHandler.class) + .isSameAs(mapping.getUrlMap().get("/ws/game/**")); }); } + @Test + void authenticatedGameplayClientIsOmittedForUnsetBlankOrExplicitFalseEndpoint() { + contextRunner.run( + context -> assertThat(context).doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); + + for (String endpoint : new String[] {"", " \t ", "false"}) { + contextRunner + .withInitializer( + applicationContext -> + applicationContext + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test-authenticated-upstream", + Map.of( + "firemud.gateway.gameplay.bridge.authenticated-upstream-url", + endpoint)))) + .run( + context -> + assertThat(context) + .as("endpoint=%s", endpoint) + .doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); + } + } + + @Test + void malformedNonblankAuthenticatedEndpointFailsFast(@TempDir Path dir) throws Exception { + Path certificate = Files.createFile(dir.resolve("client.pem")); + Path privateKey = Files.createFile(dir.resolve("client.key")); + Path caCertificate = Files.createFile(dir.resolve("ca.pem")); + + contextRunner + .withPropertyValues( + "firemud.grpc.workload-namespace=test", + "firemud.gateway.gameplay.bridge.authenticated-upstream-url=http://game-session:8444/ws/game/tcp", + "firemud.gateway.gameplay.bridge.tls.cert-chain=" + certificate, + "firemud.gateway.gameplay.bridge.tls.private-key=" + privateKey, + "firemud.gateway.gameplay.bridge.tls.ca-cert=" + caCertificate) + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasRootCauseMessage("Dedicated authenticated gameplay wss endpoint required")); + } + @Test void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { contextRunner.run( context -> { SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); - GameplayWebSocketBridgeHandler handler = - context.getBean(GameplayWebSocketBridgeHandler.class); + Object handler = mapping.getUrlMap().get("/ws/game"); + assertThat(handler).isInstanceOf(WebHandler.class); for (String path : new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { @@ -74,6 +154,84 @@ void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { }); } + @Test + void mappedWebHandlerBindsOnlyVerifiedTcpProxyOriginBeforeDelegatingUpgrade() throws Exception { + GameplayWebSocketBridgeHandler handler = mock(GameplayWebSocketBridgeHandler.class); + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()).thenReturn(new HashMap<>()); + AtomicReference received = new AtomicReference<>(); + when(handler.handle(session)) + .thenAnswer( + invocation -> { + received.set(VerifiedTcpProxyOrigin.from(session)); + return Mono.empty(); + }); + X509Certificate certificate; + try (InputStream input = + Objects.requireNonNull(getClass().getResourceAsStream("/certs/tcp-proxy-client.pem"))) { + certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + long notBefore = certificate.getNotBefore().getTime(); + long notAfter = certificate.getNotAfter().getTime(); + Clock clock = + Clock.fixed(Instant.ofEpochMilli(notBefore + (notAfter - notBefore) / 2), ZoneOffset.UTC); + GatewayTcpProxyListenerProperties listener = new GatewayTcpProxyListenerProperties(); + listener.setEnabled(true); + listener.setPort(8443); + listener.setCertificateChainPath("server.crt"); + listener.setPrivateKeyPath("server.key"); + listener.setTrustedClientCaPath("client-ca.crt"); + listener.setEnvironment("production"); + listener.setTrustProfile("production_uri"); + listener.getProductionUri().setUriSan("spiffe://firemud/ns/firemud/sa/tcp-proxy-service"); + GatewayHeaderTrustProperties headers = new GatewayHeaderTrustProperties(); + HeaderTrustFilter trust = + new HeaderTrustFilter( + headers, new TcpProxyTrustPolicy(listener, headers, 8080, clock, Set.of("test"))); + // SslInfo models the authenticated TLS peer; the actual trust policy and filter + // qualify it and produce the private origin carried by the mapping's upgrade wrapper. + SslInfo peer = mock(SslInfo.class); + when(peer.getPeerCertificates()).thenReturn(new X509Certificate[] {certificate}); + MockServerHttpRequest request = + MockServerHttpRequest.get("/ws/game") + .localAddress(new InetSocketAddress("127.0.0.1", 8443)) + .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) + .sslInfo(peer) + .header("X-Proxy-Client-IP", "203.0.113.99") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") + .build(); + + try (MockedConstruction upgrades = + mockConstruction( + HandshakeWebSocketService.class, + (upgrade, construction) -> + when(upgrade.handleRequest(any(), any())) + .thenAnswer( + invocation -> + invocation.getArgument(1).handle(session)))) { + SimpleUrlHandlerMapping mapping = + (SimpleUrlHandlerMapping) + new GameplayWebSocketBridgeConfig().gameplayWebSocketBridgeMapping(handler); + WebHandler bridge = (WebHandler) mapping.getUrlMap().get("/ws/game"); + + trust.filter(MockServerWebExchange.from(request), bridge::handle).block(); + assertThat(received.get()).isNotNull(); + assertThat(received.get().clientAddress()).isEqualTo("203.0.113.99"); + assertThat(received.get().proxyConnectionId().toString()) + .isEqualTo("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + + // Identical headers without the filter's private proof cannot inherit the prior + // upgraded session's origin, even when the same controlled session is reused. + bridge.handle(MockServerWebExchange.from(request)).block(); + assertThat(received.get()).isNull(); + assertThat(VerifiedTcpProxyOrigin.from(session)).isNull(); + assertThat(upgrades.constructed()).hasSize(1); + verify(upgrades.constructed().getFirst(), times(2)).handleRequest(any(), any()); + verify(handler, times(2)).handle(session); + } + } + @Configuration static class TestRuntimeIdentityConfig { @Bean diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java index 87093e6e80..198499fe11 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java @@ -301,7 +301,7 @@ void promotesTcpProxyHeadersWhenInsecureTrustEnabledAndRemoteMatches() { 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-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Game-Instance-Id", "42") .header("X-Proxy-Tenant-Id", "7") .header("X-Game-Instance-Id", "spoofed-game-instance") @@ -321,7 +321,7 @@ void promotesTcpProxyHeadersWhenInsecureTrustEnabledAndRemoteMatches() { assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Client-IP")) .isEqualTo("203.0.113.99"); assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Proxy-Connection-Id")) - .isEqualTo("conn-123"); + .isEqualTo("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Game-Instance-Id")) .isEqualTo("42"); assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Tenant-Id")).isEqualTo("7"); @@ -364,7 +364,7 @@ void promotesProxyHeadersOnlyOnAuthenticatedDedicatedTlsListener() throws Except .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) .sslInfo(authenticatedPeer) .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .build(); ServerWebExchange promoted = @@ -372,7 +372,23 @@ void promotesProxyHeadersOnlyOnAuthenticatedDedicatedTlsListener() throws Except assertThat(promoted.getRequest().getHeaders().getFirst("X-Client-IP")) .isEqualTo("203.0.113.99"); assertThat(promoted.getRequest().getHeaders().getFirst("X-Proxy-Connection-Id")) - .isEqualTo("conn-123"); + .isEqualTo("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + var socket = + org.mockito.Mockito.mock(org.springframework.web.reactive.socket.WebSocketSession.class); + org.mockito.Mockito.when(socket.getAttributes()).thenReturn(new java.util.HashMap<>()); + var origin = new java.util.concurrent.atomic.AtomicReference(); + VerifiedTcpProxyOrigin.bind( + promoted, + upgraded -> { + origin.set(VerifiedTcpProxyOrigin.from(upgraded)); + return Mono.empty(); + }) + .handle(socket) + .block(); + assertThat(origin.get()).isNotNull(); + assertThat(origin.get().clientAddress()).isEqualTo("203.0.113.99"); + assertThat(origin.get().proxyConnectionId().toString()) + .isEqualTo("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); MockServerHttpRequest untrustedListenerRequest = MockServerHttpRequest.get("/ws/game/test") @@ -380,7 +396,7 @@ void promotesProxyHeadersOnlyOnAuthenticatedDedicatedTlsListener() throws Except .remoteAddress(new InetSocketAddress("192.0.2.1", 50001)) .sslInfo(authenticatedPeer) .header("X-Proxy-Client-IP", "203.0.113.99") - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .build(); MockServerWebExchange untrustedListenerExchange = MockServerWebExchange.from(untrustedListenerRequest); @@ -409,7 +425,7 @@ void rejectsAuthenticatedSessionWhenProxyClientIpIsMissingOrMalformed() throws E .localAddress(new InetSocketAddress("127.0.0.1", 8443)) .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) .sslInfo(authenticatedPeer) - .header("X-Proxy-Connection-Id", "conn-123"); + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); if (clientIp != null) { requestBuilder.header("X-Proxy-Client-IP", clientIp); } @@ -418,6 +434,42 @@ void rejectsAuthenticatedSessionWhenProxyClientIpIsMissingOrMalformed() throws E } } + @Test + void rejectsNonCanonicalProxyConnectionIdsOnAuthenticatedListener() throws Exception { + GatewayHeaderTrustProperties headerProperties = new GatewayHeaderTrustProperties(); + GatewayTcpProxyListenerProperties listenerProperties = certificateListenerProperties(); + TcpProxyTrustPolicy policy = + new TcpProxyTrustPolicy( + listenerProperties, + headerProperties, + 8080, + TCP_PROXY_CERTIFICATE_CLOCK, + Set.of("test")); + HeaderTrustFilter filter = new HeaderTrustFilter(headerProperties, policy); + SslInfo authenticatedPeer = authenticatedTcpProxyPeer(); + + for (String connectionId : + new String[] { + null, + "opaque", + "9FB38C88-2F1D-42AA-8E0B-7EB69CAF8814", + "9fb38c88-2f1d-12aa-8e0b-7eb69caf8814", + "9fb38c88-2f1d-42aa-ce0b-7eb69caf8814" + }) { + MockServerHttpRequest.BaseBuilder requestBuilder = + MockServerHttpRequest.get("/ws/game/test") + .localAddress(new InetSocketAddress("127.0.0.1", 8443)) + .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) + .sslInfo(authenticatedPeer) + .header("X-Proxy-Client-IP", "203.0.113.99"); + if (connectionId != null) { + requestBuilder.header("X-Proxy-Connection-Id", connectionId); + } + MockServerWebExchange exchange = MockServerWebExchange.from(requestBuilder.build()); + assertForbiddenWithoutDelegation(filter, exchange, "connectionId=" + connectionId); + } + } + @Test void rejectsLegacyTrustedProxyWhenProxyClientIpIsMissingOrMalformed() { GatewayHeaderTrustProperties properties = new GatewayHeaderTrustProperties(); @@ -429,7 +481,7 @@ void rejectsLegacyTrustedProxyWhenProxyClientIpIsMissingOrMalformed() { MockServerHttpRequest.BaseBuilder requestBuilder = MockServerHttpRequest.get("/ws/game/test") .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Game-Instance-Id", "42") .header("X-Proxy-Tenant-Id", "7"); if (clientIp != null) { @@ -466,7 +518,7 @@ void doesNotEmitLegacySessionId() { 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-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Game-Instance-Id", "42") .header("X-Proxy-Tenant-Id", "7") .build(); @@ -488,7 +540,7 @@ void rejectsSessionRouteWhenTrustedProxyTenantIdIsMalformed() { MockServerHttpRequest request = MockServerHttpRequest.get("/ws/game/test") .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Game-Instance-Id", "42") .header("X-Proxy-Tenant-Id", "bad-id") .build(); @@ -510,7 +562,7 @@ void rejectsSessionRouteWhenTrustedProxyGameInstanceIdIsNonPositive() { MockServerHttpRequest request = MockServerHttpRequest.get("/ws/game/test") .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Game-Instance-Id", "0") .header("X-Proxy-Tenant-Id", "1") .build(); @@ -532,7 +584,7 @@ void rejectsSessionRouteWhenTrustedProxyIdentityIsPartial() { MockServerHttpRequest request = MockServerHttpRequest.get("/ws/game/test") .remoteAddress(new InetSocketAddress("10.1.2.3", 0)) - .header("X-Proxy-Connection-Id", "conn-123") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") .header("X-Proxy-Tenant-Id", "1") .build(); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java new file mode 100644 index 0000000000..1c233e2a11 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.springcloudgateway.websocket; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.netty.handler.ssl.ClientAuth; +import io.netty.handler.ssl.SslContextBuilder; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.http.HttpHeaders; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.reactive.socket.CloseStatus; +import org.springframework.web.reactive.socket.HandshakeInfo; +import org.springframework.web.reactive.socket.WebSocketMessage; +import org.springframework.web.reactive.socket.WebSocketSession; +import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.netty.http.server.HttpServer; +import reactor.test.StepVerifier; + +class AuthenticatedGameplayWebSocketClientTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Authenticated gameplay test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "gateway", "spiffe://firemud/ns/test/sa/spring-cloud-gateway", false), + new LoopbackMtlsTestPki.IdentitySpec( + "session", "spiffe://firemud/ns/test/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-client", "spiffe://firemud/ns/test/sa/account-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-client", "spiffe://firemud/ns/other/sa/spring-cloud-gateway", false)); + } + + @Test + void exactGameSessionPeerCompletesRealMutualTlsWebSocketUpgrade() throws Exception { + var requests = new AtomicInteger(); + exchange("session", requests, true); + assertThat(requests).hasValue(1); + } + + @Test + void wrongWorkloadOrNamespaceReceivesNoUpgradeOrOriginHeaders() throws Exception { + for (String identity : java.util.List.of("wrong-service", "wrong-namespace")) { + var requests = new AtomicInteger(); + exchange(identity, requests, false); + assertThat(requests).hasValue(0); + } + } + + @Test + void localClientRequiresItsDedicatedGatewayIdentityAndClientUsage() throws Exception { + for (String identity : java.util.List.of("session", "wrong-client", "foreign-client")) { + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity(identity)), + "test", + "wss://localhost:8444/ws/game/tcp")) { + assertThatThrownBy(client::initialize).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client + .execute(new HttpHeaders(), socket -> Mono.empty()) + .block(Duration.ofSeconds(5))) + .isInstanceOf(IllegalStateException.class); + } + } + } + + @Test + void executionSignalsUnavailableWhenClosedBeforeOrAfterAssembly() throws Exception { + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp")) { + client.initialize(); + Mono assembled = client.execute(new HttpHeaders(), socket -> Mono.empty()); + client.close(); + + for (Mono execution : + List.of(assembled, client.execute(new HttpHeaders(), socket -> Mono.empty()))) { + StepVerifier.create(execution) + .expectErrorMatches( + error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .verify(Duration.ofSeconds(5)); + } + } + } + + @Test + void lateReloadCannotRepublishClientAfterClose() throws Exception { + CountDownLatch candidateBuilt = new CountDownLatch(1); + CountDownLatch finishReload = new CountDownLatch(1); + AtomicInteger reloads = new AtomicInteger(); + Runnable beforePublish = + () -> { + if (reloads.incrementAndGet() == 2) { + candidateBuilt.countDown(); + try { + finishReload.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + }; + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp", + beforePublish)) { + client.initialize(); + AtomicReference reloadFailure = new AtomicReference<>(); + Thread lateReload = + new Thread( + () -> { + try { + client.reload(); + } catch (Exception failure) { + reloadFailure.set(failure); + } + }); + lateReload.start(); + try { + assertThat(candidateBuilt.await(5, TimeUnit.SECONDS)).isTrue(); + client.close(); + assertThat(lateReload.isAlive()).isTrue(); + } finally { + finishReload.countDown(); + lateReload.join(Duration.ofSeconds(5).toMillis()); + } + + assertThat(lateReload.isAlive()).isFalse(); + assertThat(reloadFailure.get()).isNull(); + StepVerifier.create(client.execute(new HttpHeaders(), socket -> Mono.empty())) + .expectErrorMatches( + error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .verify(Duration.ofSeconds(5)); + } + } + + @Test + void closedClientFollowsBridgeCloseAndReleasesActiveRegistration() throws Exception { + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp")) { + client.initialize(); + client.close(); + ReactorNettyWebSocketClient ordinaryClient = mock(ReactorNettyWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + when(origin.clientAddress()).thenReturn("203.0.113.99"); + when(origin.proxyConnectionId()) + .thenReturn(UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814")); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getId()).thenReturn("closed-client-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + Sinks.Empty closed = Sinks.empty(); + when(downstream.send(any())).thenReturn(closed.asMono()); + when(downstream.receive()) + .thenReturn(closed.asMono().thenMany(Flux.empty())); + when(downstream.close(any(CloseStatus.class))) + .thenAnswer( + invocation -> { + closed.tryEmitEmpty(); + return Mono.empty(); + }); + GameplayWebSocketBridgeHandler bridge = + new GameplayWebSocketBridgeHandler( + ordinaryClient, + new GameplayWebSocketBridgeProperties(null, 1, 1L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + client); + + StepVerifier.withVirtualTime(() -> bridge.handle(downstream)) + .thenAwait(Duration.ofMillis(2)) + .expectComplete() + .verify(Duration.ofSeconds(5)); + + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + assertThat(ReflectionTestUtils.getField(bridge, "activeBridges")).isEqualTo(Set.of()); + verifyNoInteractions(ordinaryClient); + } + } + + private void exchange(String identity, AtomicInteger requests, boolean accepted) + throws Exception { + var serverIdentity = pki.identity(identity); + var tls = + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate(), pki.caCertificate()) + .trustManager(pki.trustManagerFactory()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + var server = + HttpServer.create() + .host("127.0.0.1") + .port(0) + .secure(spec -> spec.sslContext(tls)) + .handle( + (request, response) -> { + requests.incrementAndGet(); + return response.sendWebsocket( + (inbound, outbound) -> + outbound.sendString(reactor.core.publisher.Mono.just("ready"))); + }) + .bindNow(); + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:" + server.port() + "/ws/game/tcp")) { + client.initialize(); + var headers = new HttpHeaders(); + headers.set("X-Client-IP", "203.0.113.7"); + Runnable call = + () -> + client + .execute(headers, socket -> socket.receive().next().then()) + .block(Duration.ofSeconds(5)); + if (accepted) call.run(); + else assertThatThrownBy(call::run).isInstanceOf(RuntimeException.class); + } finally { + server.disposeNow(); + } + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 6017efe5b7..a64b873ac1 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -2,7 +2,9 @@ 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.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -11,18 +13,27 @@ import java.net.URI; import java.time.Duration; import java.time.Instant; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import org.slf4j.MDC; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpHeaders; import org.springframework.web.reactive.socket.CloseStatus; import org.springframework.web.reactive.socket.HandshakeInfo; @@ -112,6 +123,282 @@ void bridgeGeneratesTransportSessionIdWhenTrustedAdmissionProvidesNone() { .isNotEqualTo("9001"); } + @ParameterizedTest + @ValueSource(strings = {"ws", "wss"}) + void ordinaryUpstreamKeepsItsClientWhenAuthenticatedUpstreamIsConfigured(String scheme) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + URI ordinaryUpstream = URI.create(scheme + "://game-session-service:8080/ws/game"); + when(authenticated.upstream()) + .thenReturn(URI.create("wss://game-session-service:8444/ws/game/tcp")); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("ordinary-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + when(downstream.send(any())).thenReturn(Mono.never()); + when(downstream.receive()).thenReturn(Flux.never()); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenReturn(Mono.never()); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties(ordinaryUpstream.toString(), 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectSubscription().thenCancel().verify(); + + verify(client) + .execute(eq(ordinaryUpstream), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + } + + @Test + void ordinaryUpstreamRetryKeepsItsClientWhenUrisMatchAuthenticatedUpstream() { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + URI upstream = URI.create("wss://game-session-service:8444/ws/game/tcp"); + when(authenticated.upstream()).thenReturn(upstream); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenReturn(Mono.error(new IllegalStateException("connection failed"))); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("ordinary-retry-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + Sinks.Empty closed = Sinks.empty(); + when(downstream.send(any())).thenReturn(Mono.empty()); + when(downstream.receive()).thenReturn(closed.asMono().thenMany(Flux.empty())); + when(downstream.close(any(CloseStatus.class))) + .thenReturn(Mono.fromRunnable(closed::tryEmitEmpty)); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties(upstream.toString(), 1, 0L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectComplete().verify(Duration.ofSeconds(5)); + + verify(client, times(2)) + .execute(eq(upstream), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void downstreamClosureDuringReconnectBackoffSkipsNextUpstreamExecution( + boolean failAfterTransportConnect) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + WebSocketSession upstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + Sinks.Empty downstreamClosed = Sinks.empty(); + + when(downstream.getId()).thenReturn("reconnect-backoff-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + when(downstream.send(any())).thenReturn(Mono.empty()); + when(downstream.receive()) + .thenReturn(downstreamClosed.asMono().thenMany(Flux.empty())); + when(upstream.send(any())).thenReturn(Mono.never()); + when(upstream.receive()).thenReturn(Flux.empty()); + when(upstream.closeStatus()).thenReturn(Mono.empty()); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenAnswer( + invocation -> { + if (!failAfterTransportConnect) { + return Mono.error(new IllegalStateException("connection failed")); + } + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); + + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 1_000L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); + + StepVerifier.withVirtualTime(() -> handler.handle(downstream)) + .then( + () -> { + verify(client) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + downstreamClosed.tryEmitEmpty(); + }) + .thenAwait(Duration.ofSeconds(2)) + .expectComplete() + .verify(Duration.ofSeconds(5)); + + verify(client).execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + } + + @Test + void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + when(authenticated.upstream()) + .thenReturn(URI.create("wss://game-session-service:8444/ws/game/tcp")); + when(authenticated.execute(any(), any())).thenReturn(Mono.never()); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + UUID connectionId = UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + when(origin.clientAddress()).thenReturn("203.0.113.99"); + when(origin.proxyConnectionId()).thenReturn(connectionId); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("tcp-downstream"); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Client-IP", "unverified"); + headers.set("X-Proxy-Connection-Id", "unverified"); + headers.set("X-Firemud-Transport-Session-Id", "9001"); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.send(any())).thenReturn(Mono.never()); + when(downstream.receive()).thenReturn(Flux.never()); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "wss://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectSubscription().thenCancel().verify(); + + ArgumentCaptor forwarded = ArgumentCaptor.forClass(HttpHeaders.class); + verify(authenticated).execute(forwarded.capture(), any()); + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + assertThat(forwarded.getValue().getFirst("X-Client-IP")).isEqualTo("203.0.113.99"); + assertThat(forwarded.getValue().getFirst("X-Proxy-Connection-Id")) + .isEqualTo(connectionId.toString()); + assertThat(forwarded.getValue().getFirst("X-Firemud-Connection-Mode")) + .isEqualTo("trusted_tcp_proxy"); + assertThat(forwarded.getValue().getFirst("X-Firemud-Transport-Session-Id")).isNull(); + } + + @Test + @ExtendWith(OutputCaptureExtension.class) + void missingAuthenticatedClientWarnsOnceWithoutConnectionDetailsAndKeepsFailClosed( + CapturedOutput output) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + headers.set("X-Firemud-Transport-Session-Id", "private-transport-session"); + headers.set("X-Firemud-Connect-Context", "private-connect-context"); + headers.set(HttpHeaders.AUTHORIZATION, "Bearer private-credential"); + headers.set(HttpHeaders.COOKIE, "private-cookie"); + + for (int attempt = 0; attempt < 10; attempt++) { + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("private-downstream-session"); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.empty()); + + StepVerifier.create(handler.handle(downstream)).verifyComplete(); + + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + verify(downstream, never()).send(any()); + verify(downstream, never()).receive(); + } + + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + assertThat(output.getAll()) + .containsOnlyOnce("no authenticated gameplay upstream client is configured") + .contains("firemud.gateway.gameplay.bridge.authenticated-upstream-url") + .doesNotContain( + "private-transport-session", + "private-connect-context", + "private-credential", + "private-cookie", + "private-downstream-session"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rejectedTcpOriginCloseIsBoundedAndRecorded(boolean verifiedOrigin) { + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + Map attributes = + verifiedOrigin + ? Map.of(VerifiedTcpProxyOrigin.class.getName(), mock(VerifiedTcpProxyOrigin.class)) + : Map.of(); + when(downstream.getId()).thenReturn("tcp-downstream"); + when(downstream.getAttributes()).thenReturn(attributes); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.never()); + + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + new GameplayWebSocketObservability(meterRegistry), + verifiedOrigin ? null : authenticated); + + StepVerifier.withVirtualTime(() -> handler.handle(downstream)) + .thenAwait(Duration.ofSeconds(2)) + .expectError(TimeoutException.class) + .verify(Duration.ofSeconds(5)); + + CloseStatus expected = + verifiedOrigin + ? new CloseStatus(1013, "backend_unavailable") + : new CloseStatus(1008, "authenticated_tcp_origin_required"); + verify(downstream).close(expected); + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + assertThat( + meterRegistry + .get("gateway.websocket.closes") + .tags( + "reason", verifiedOrigin ? "backend_unavailable" : "policy_violation", + "subreason", "none", + "bridge_shutdown_class", "unattributed_failure") + .counter() + .count()) + .isEqualTo(1.0); + } + @Test void actualLocalShutdownClosesEstablishedBridgeWithPlannedDrain() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry();