diff --git a/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md b/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md index 64e54937d4..9c6b3db1a2 100644 --- a/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md +++ b/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Kubernetes Secret mounts, cert-manager examples, expected-binding preflight, and secret-compliance evidence exist, but the repository does not satisfy the complete target. Base manifests mount JWT signing material beyond Account, gRPC workloads commonly share one TLS Secret, and production Secret encryption-at-rest/audit proof plus automated rotation/convergence remain incomplete. Hosted preview/dev-demo Helm currently uses the shared `firemud-grpc-tls` Secret across gRPC workloads; that proves encrypted transport only, not target per-workload identity or player-facing equivalence. The target remains distinct leaf Secrets per workload with a shared CA, with generic per-workload identity preflight proof still unimplemented. +Kubernetes Secret mounts, cert-manager examples, expected-binding preflight, and secret-compliance evidence exist, but the repository does not satisfy the complete target. Base manifests still mount JWT signing material beyond Account, three of the eleven hosted gRPC workloads still use shared leaf material, and production Secret encryption-at-rest/audit proof plus automated rotation/convergence remain incomplete. Hosted preview/dev-demo Helm now defines eight distinct gRPC workload leaf Secrets: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret remains for the common CA trust bundle and the three remaining shared-leaf workloads. Static render and controller-contract proof covers the eight distinct workload bindings and their readiness evidence; live certificate issuance, served-identity convergence, and production-promotion proof remain incomplete. The target remains distinct leaf Secrets for every workload with a shared CA. ## Decision Record diff --git a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md index 66ae28c763..c0a4c0110e 100644 --- a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md +++ b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md @@ -37,9 +37,9 @@ The controller establishes identity scope only through its one-time bootstrap/ad ### Runtime-first activation and explicit retirement -Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all five labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md) before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. +Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all thirteen labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md)—five shared-role projections and eight distinct gRPC workload projections—before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. -A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all five declared projection roles: (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](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle). Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. +A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all thirteen declared projections: the 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](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus eight distinct gRPC workload projections for the five publication services, Account, Game Session, and Social Groups. Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. If retirement observes a live runtime profile that differs from the profile already recorded in controller status, it reports `RuntimeIdentityChanged`, preserves the previously observed profile, and never refreshes retirement authority from the mismatched live values. Recovery belongs to the trusted lifecycle: it removes the whole disposable runtime namespace and obtains the runtime-first exact `NotFound` proof. A later retirement reconcile can then continue deleting the retained identity through the normal ownership-checked path. This recovery does not permit manual deletion of retained identity material and does not weaken the live-runtime bridge-shutdown or runtime-absence gates. @@ -53,7 +53,7 @@ All controller-owned certificate leaves use RSA-2048 keys. The cert-manager reso ### Generation-bound readiness and certificate convergence -The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and gRPC revisions are present. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. +The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty revisions are present for the five shared roles and eight distinct gRPC workload roles. Account, Game Session, and Social Groups must additionally serve their current projected leaves at the fixed gRPC endpoints; rollout counters alone are insufficient. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. Certificate issuance and replacement for one identity proceed through a serialized lifecycle. The controller and issuer path validate actual served certificates and keys, including validity, required SANs, key correspondence without exposing private material, expected issuer and trust chain, monotonic identity generation, and distinct SPKI for intentional replacement. After issuance, affected ingress, Telnet, and, where applicable, gRPC consumers must reload or restart and serve or accept the new identity. A consumer that has not converged leaves the lifecycle failed or pending and does not authorize removal of the prior usable identity solely because a new resource exists. diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 781efc69a9..562c9f6907 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 five per-workload gRPC publication leaves from `firemud-ca-issuer` and materializes and reconciles ten runtime Secret projections (the five shared-role projections plus five `firemud-grpc-` publication 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 five 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 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. - 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 five workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`). 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 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. 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 ten labeled, key-complete Secret projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`, plus the five `firemud-grpc-` publication Secrets), 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 ten 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 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. 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,19 +334,19 @@ 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 ten 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 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 `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 ten 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 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. 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 ten runtime Secret projections: the 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 five distinct per-workload gRPC publication projections (`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`). 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 five publication 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 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. -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 Account TCP/6565 selectors remain explicit. `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. +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. - Same-repo pull requests may deploy one Helm release into namespace `pr-` with matching hostname `https://pr-.preview.`. - The preview deployment uses the full application stack, including the gateway, TCP proxy, backend microservices, and stateful supporting services required for normal gameplay flows. diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index dc4585b15a..23cd54ce1d 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -102,7 +102,7 @@ Only an explicitly labelled one-shot test/CI stack may collapse roles into a sin ## 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. Current hosted Helm manifests for `pr-preview` and `dev-demo-cluster` use the shared `firemud-grpc-tls` Secret across gRPC workloads; that is evidence of encrypted mTLS transport only, not distinct workload leaf identity or player-facing equivalence. 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` currently uses the shared-secret mTLS boundary and remains non-player-facing/non-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. 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: - 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/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index baa1a7def2..6c162d5237 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 canonical target gives each workload a distinct leaf certificate/private-key Secret. Current hosted manifests give five publication services distinct leaf Secrets and project only `ca.crt` from the shared `firemud-grpc-tls` trust bundle into those Pods. The other gRPC workloads still use the shared leaf identity, so hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. +- 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). - 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 request distinct cert-manager-issued leaves for the five publication services. The checked-in `k8s/base/` Pod manifests only bind and mount the corresponding `firemud-grpc-` Secrets; 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 the five namespace-scoped publication 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). The remaining gRPC workloads continue to use the legacy shared leaf. Each publication Pod reads peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`; its private identity remains the service-specific `tls.crt` and `tls.key`. The shared CA bundle contains the legacy and current issuer trust anchors so these publication workloads can verify peers using either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical target provisions distinct per-workload leaf certificate/private-key Secrets so each service has a concrete private identity. These certificates secure: +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: - 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/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 2785a2c61f..515e0e3d9b 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -187,7 +187,7 @@ For both `standalone` and explicit `hosted-controller` preview modes, the previe On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. -Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for all five raw controller-projected Secrets before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. +Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret set—including the distinct Account, Game Session, and Social Groups workload leaves—before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index b3326d565a..ae47c6af91 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`. Each publication Secret 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 both that shared leaf's issuer and the issuer of each of the five distinct publication leaves. Runtime publication-reader Pods mount their own publication Secret for the client leaf and key, and use only the shared `firemud-grpc-tls` CA bundle for trust. Each 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. `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`. 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. 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/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 4245d17195..a998941ac4 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -122,7 +122,7 @@ World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeed ### Hosted Preview, Dev-Demo, and Deployment Delivery -Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all ten projections (five shared-role projections and five per-workload publication projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. +Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all thirteen runtime Secret projections (five shared-role projections and eight workload-specific projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. Preview allocation and reconciliation status: automatic eligibility, bounded two-slot first-come allocation, the maintainer-controlled priority exception, lifecycle serialization, cleanup, and bounded proof-retry controls have focused local/static contract evidence. Live hosted allocation, Actions-run query behavior, Namespace lifecycle, and proof-dispatch behavior remain unverified; normative behavior and the remaining proof boundary are owned by [Deployment Environments](../../architecture/infrastructure/deployment-environments.md#pr-preview-environment). @@ -142,11 +142,11 @@ The hosted credential boundary is now explicit: every secret-consuming preview, The recovery path is separate from routine hosted delivery: `.github/workflows/preview-ca-recovery.yml` runs only from `develop` in the protected GitHub Environment `trusted-preview-ca-recovery`, using `TRUSTED_PREVIEW_CA_RECOVERY_KUBECONFIG` and the protected `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret. Its fingerprint and context are non-secret Environment variables. This recovery-only workflow and credential bundle are distinct from the `trusted-hosted-cluster` deployment credentials and are not selected by PR-controlled or routine deployment jobs. -The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer now also owns five fixed gRPC workload Certificates in both preview and dev-demo; the runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller projections comprise those five workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle. +The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer owns eight fixed gRPC workload Certificates in both preview and dev-demo: the five publication workloads plus Account, Game Session, and Social Groups. The runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller runtime projections comprise those eight workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle, for thirteen total. Static/live boundary: `hosted-identity-controller-manifest-contract.sh`, `hosted-identity-controller-workflow-contract.sh`, `dev-demo-workflow-contract.sh`, and architecture-document checks are static or local prerequisite proof only. They do not establish a live controller deployment, exact NetworkPolicy allow/deny behavior, CNI post-DNAT behavior, issued certificate, runtime Namespace binding, Helm consumer activation, served-certificate probe, or consumer rollout. PO-3.2 remains incomplete until live allow/deny and served Gateway↔TCP Proxy bridge proof are available. -Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all ten key-complete projections (five shared-role projections and five per-workload publication projections) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. +Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all thirteen key-complete runtime projections (five shared-role projections and eight workload-specific projections, including Account, Game Session, and Social Groups) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. The fixed `develop` environment is a separate `dev-demo-cluster`, not a PR preview: namespace `dev`, release `dev`, hostname `dev.preview.firedevops.net`, and TCP port `32016`. Its workflow and scheduled reconciler deploy the current `develop` head, reset the namespace for reproducibility, and prove `LOGIN -> PLAY -> LOOK`; it is not a promotion source, rollback-evidence source, or DR-attestation source. PR janitor/capacity logic applies only to `pr-*` namespaces. Player-facing staging and production use the canonical Kustomize overlays, while hosted Helm retains preview/dev-demo ownership. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index e91e114763..9e8953a274 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only publication leaf with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. -- Standalone hosted runs retain the legacy shared bundle for non-publication workloads and consume only cert-manager's five runtime-facing `firemud-grpc-` leaf Secrets. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for the five publication services, Account, Game Session, or Social Groups with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index ccb53ee36b..0a31711bf9 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -27,10 +27,10 @@ if [[ "${1:-}" == "--workload" ]]; then exit 1 } case "$workload" in - game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) + account-service|game-session-service|social-groups-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) ;; *) - echo "unsupported gRPC publication workload: $workload" >&2 + echo "unsupported gRPC workload identity: $workload" >&2 exit 1 ;; esac @@ -71,7 +71,7 @@ EOF openssl x509 -req -in "$workload_request" -CA "$ca_cert" -CAkey "$ca_key" \ -CAserial "$workload_serial" -out "$output_cert" -days 365 -sha256 \ -extensions v3_req -extfile "$workload_config" >/dev/null || { - echo "failed to sign publication workload certificate: $workload" >&2 + echo "failed to sign gRPC workload identity certificate: $workload" >&2 exit 1 } chmod 644 "$output_cert" diff --git a/dev-tools/deploy/preflight.py b/dev-tools/deploy/preflight.py index e2168d3fd2..551b0a0538 100644 --- a/dev-tools/deploy/preflight.py +++ b/dev-tools/deploy/preflight.py @@ -146,7 +146,17 @@ def _hosted_bridge_secret_ready_attempts_for_timeout(timeout_seconds: int) -> in "game-logic-service", "automation-scripting-service", ) -PUBLICATION_GRPC_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} +ACCOUNT_GAME_SESSION_GRPC_WORKLOADS = ( + "account-service", + "game-session-service", +) +SHARED_TRUST_GRPC_WORKLOADS = ( + *PUBLICATION_GRPC_WORKLOADS, + "social-groups-service", + *ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, +) +GRPC_WORKLOAD_SECRET_CONSUMERS = SHARED_TRUST_GRPC_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"} BASE_SECRET_COMPLIANCE_CLASSES = frozenset( @@ -938,13 +948,13 @@ def publication_workload_secret_requirements( expected: dict[str, Any], documents: list[dict[str, Any]], ) -> tuple[tuple[str, str, set[str]], ...]: - """Resolve each publication leaf Secret and its shared CA trust Secret.""" + """Resolve workload leaf Secrets and the shared gRPC CA trust Secret.""" expected_namespace = secret_binding_namespace( get(expected, "internalBindings.postgres.credentialsRef") ) if expected_namespace is None: raise ValueError( - "Cannot resolve publication workload Secret namespace from internalBindings.postgres.credentialsRef" + "Cannot resolve gRPC workload Secret namespace from internalBindings.postgres.credentialsRef" ) workload_mtls_ref = parse_binding_ref( get(expected, "internalBindings.certificates.workloadMtlsRef") @@ -963,7 +973,11 @@ def publication_workload_secret_requirements( workload_mtls_secret_name = workload_mtls_ref[2][0] requirements: list[tuple[str, str, set[str]]] = [] leaf_secret_names: list[str] = [] - for workload in PUBLICATION_GRPC_WORKLOADS: + for workload in GRPC_WORKLOAD_SECRET_CONSUMERS: + is_publication_workload = workload in PUBLICATION_GRPC_WORKLOADS + workload_label = ( + "publication workload" if is_publication_workload else "gRPC workload" + ) deployments = [ document for document in documents @@ -973,25 +987,25 @@ def publication_workload_secret_requirements( ] if len(deployments) != 1: raise ValueError( - f"Expected exactly one rendered Deployment for publication workload {workload}; found {len(deployments)}" + f"Expected exactly one rendered Deployment for {workload_label} {workload}; found {len(deployments)}" ) deployment = deployments[0] metadata = deployment["metadata"] workload_namespace = metadata.get("namespace", expected_namespace) if not isinstance(workload_namespace, str) or not workload_namespace.strip(): raise ValueError( - f"Rendered publication workload {workload} has an invalid namespace" + f"Rendered {workload_label} {workload} has an invalid namespace" ) if workload_namespace != expected_namespace: raise ValueError( - f"Rendered publication workload {workload} namespace {workload_namespace} " + f"Rendered {workload_label} {workload} namespace {workload_namespace} " f"does not match expected Secret namespace {expected_namespace}" ) pod_spec = get(deployment, "spec.template.spec") volumes = pod_spec.get("volumes") if isinstance(pod_spec, dict) else None if not isinstance(volumes, list): raise TypeError( - f"Rendered publication workload {workload} has no valid pod volumes list" + f"Rendered {workload_label} {workload} has no valid pod volumes list" ) grpc_volumes = [ volume @@ -1005,17 +1019,34 @@ def publication_workload_secret_requirements( ] if len(grpc_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-tls volume for publication workload {workload}; found {len(grpc_volumes)}" + f"Expected exactly one grpc-tls volume for {workload_label} {workload}; found {len(grpc_volumes)}" ) if len(trust_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-trust volume for publication workload {workload}; found {len(trust_volumes)}" + f"Expected exactly one grpc-trust volume for {workload_label} {workload}; found {len(trust_volumes)}" ) grpc_volume = grpc_volumes[0] secret = grpc_volume.get("secret") secret_name = secret.get("secretName") if isinstance(secret, dict) else None expected_leaf_items = {("tls.crt", "tls.crt"), ("tls.key", "tls.key")} leaf_items = secret.get("items") if isinstance(secret, dict) else None + leaf_projection_is_valid = ( + isinstance(leaf_items, list) + and len(leaf_items) == len(expected_leaf_items) + and all( + isinstance(item, dict) + and set(item) == {"key", "path"} + and isinstance(item.get("key"), str) + and isinstance(item.get("path"), str) + for item in leaf_items + ) + and { + (item["key"], item["path"]) + for item in leaf_items + if isinstance(item, dict) + } + == expected_leaf_items + ) if ( not isinstance(secret, dict) or not isinstance(secret_name, str) @@ -1023,39 +1054,25 @@ def publication_workload_secret_requirements( or secret_name != secret_name.strip() or not set(secret).issubset({"secretName", "defaultMode", "items"}) or set(grpc_volume) != {"name", "secret"} - or not isinstance(leaf_items, list) - or len(leaf_items) != len(expected_leaf_items) - or any( - not isinstance(item, dict) - or set(item) != {"key", "path"} - or not isinstance(item.get("key"), str) - or not isinstance(item.get("path"), str) - for item in leaf_items - ) - or { - (item["key"], item["path"]) - for item in leaf_items - if isinstance(item, dict) - } - != expected_leaf_items + or not leaf_projection_is_valid ): raise ValueError( - f"Rendered publication workload {workload} has a malformed grpc-tls Secret volume" + f"Rendered {workload_label} {workload} has a malformed grpc-tls Secret volume" ) if secret_name == workload_mtls_secret_name: raise ValueError( - f"Rendered publication workload {workload} grpc-tls Secret must be distinct from " + f"Rendered {workload_label} {workload} grpc-tls 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 publication workload {workload} grpc-tls Secret must not use the " + f"Rendered {workload_label} {workload} grpc-tls 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 publication workload {workload} grpc-tls Secret must be " + f"Rendered {workload_label} {workload} grpc-tls Secret must be " f"{expected_leaf_secret_name}; found {secret_name}" ) @@ -1088,14 +1105,14 @@ def publication_workload_secret_requirements( != expected_trust_items ): raise ValueError( - f"Rendered publication workload {workload} requires the shared CA-only " + f"Rendered {workload_label} {workload} requires the shared CA-only " f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" ) containers = pod_spec.get("containers") if not isinstance(containers, list): raise TypeError( - f"Rendered publication workload {workload} has no valid pod containers list" + f"Rendered {workload_label} {workload} has no valid pod containers list" ) workload_containers = [ container @@ -1104,7 +1121,7 @@ def publication_workload_secret_requirements( ] if len(workload_containers) != 1: raise ValueError( - f"Expected exactly one owning container for publication workload {workload}; " + f"Expected exactly one owning container for {workload_label} {workload}; " f"found {len(workload_containers)}" ) container = workload_containers[0] @@ -1117,20 +1134,20 @@ def publication_workload_secret_requirements( ) if env_issues: raise ValueError( - f"Rendered publication workload {workload} has invalid gRPC TLS path environment: " + f"Rendered {workload_label} {workload} has invalid gRPC TLS path environment: " + "; ".join(env_issues) ) container_env = container.get("env", []) if not isinstance(container_env, list): raise TypeError( - f"Rendered publication workload {workload} has no valid container env list" + f"Rendered {workload_label} {workload} has no valid container env list" ) declared_grpc_path_names: list[str] = [] for entry in container_env: if not isinstance(entry, dict): raise TypeError( - f"Rendered publication workload {workload} has a malformed container env entry" + f"Rendered {workload_label} {workload} has a malformed container env entry" ) name = entry.get("name") if name not in GRPC_TLS_PATH_NAMES: @@ -1138,11 +1155,11 @@ def publication_workload_secret_requirements( declared_grpc_path_names.append(name) if not set(entry).issubset({"name", "value", "valueFrom"}): raise ValueError( - f"Rendered publication workload {workload} has a malformed {name} env entry" + f"Rendered {workload_label} {workload} has a malformed {name} env entry" ) if "value" in entry and "valueFrom" in entry: raise ValueError( - f"Rendered publication workload {workload} has an ambiguous {name} env entry" + f"Rendered {workload_label} {workload} has an ambiguous {name} env entry" ) if "valueFrom" in entry: value_from = entry.get("valueFrom") @@ -1152,11 +1169,11 @@ def publication_workload_secret_requirements( or not set(value_from).issubset({"configMapKeyRef", "secretKeyRef"}) ): raise ValueError( - f"Rendered publication workload {workload} has a malformed {name} env source" + f"Rendered {workload_label} {workload} has a malformed {name} env source" ) if len(declared_grpc_path_names) != len(set(declared_grpc_path_names)): raise ValueError( - f"Rendered publication workload {workload} has ambiguous gRPC TLS path env entries" + f"Rendered {workload_label} {workload} has ambiguous gRPC TLS path env entries" ) expected_grpc_paths = { @@ -1175,32 +1192,32 @@ def publication_workload_secret_requirements( or path != expected_grpc_paths[name] ): raise ValueError( - f"Rendered publication workload {workload} must configure {name} as {expected_grpc_paths[name]}" + f"Rendered {workload_label} {workload} must configure {name} as {expected_grpc_paths[name]}" ) grpc_paths[name] = path volume_mounts = container.get("volumeMounts") if not isinstance(volume_mounts, list): raise TypeError( - f"Rendered publication workload {workload} has no valid container volumeMounts list" + f"Rendered {workload_label} {workload} has no valid container volumeMounts list" ) for mount in volume_mounts: if not isinstance(mount, dict): raise TypeError( - f"Rendered publication workload {workload} has a malformed container volume mount" + f"Rendered {workload_label} {workload} has a malformed container volume mount" ) if not isinstance(mount.get("name"), str) or not mount["name"].strip(): raise ValueError( - f"Rendered publication workload {workload} has a volume mount with an invalid name" + f"Rendered {workload_label} {workload} has a volume mount with an invalid name" ) mount_path = mount.get("mountPath") if not isinstance(mount_path, str) or not mount_path.startswith("/"): raise ValueError( - f"Rendered publication workload {workload} has a volume mount with a non-absolute mountPath" + f"Rendered {workload_label} {workload} has a volume mount with a non-absolute mountPath" ) if "readOnly" in mount and not isinstance(mount["readOnly"], bool): raise ValueError( - f"Rendered publication workload {workload} has a malformed volume mount readOnly value" + f"Rendered {workload_label} {workload} has a malformed volume mount readOnly value" ) expected_mounts = { @@ -1212,7 +1229,7 @@ def publication_workload_secret_requirements( mounts = [mount for mount in volume_mounts if mount.get("name") == volume_name] if len(mounts) != 1: raise ValueError( - f"Expected exactly one {volume_name} mount for publication workload {workload}; found {len(mounts)}" + f"Expected exactly one {volume_name} mount for {workload_label} {workload}; found {len(mounts)}" ) mount = mounts[0] if ( @@ -1222,7 +1239,7 @@ def publication_workload_secret_requirements( or "subPathExpr" in mount ): raise ValueError( - f"Rendered publication workload {workload} requires a read-only {volume_name} mount at {mount_path} without subPath" + f"Rendered {workload_label} {workload} requires a read-only {volume_name} mount at {mount_path} without subPath" ) validated_mounts[volume_name] = mount @@ -1236,7 +1253,7 @@ def publication_workload_secret_requirements( grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], "/grpc-trust" ): raise ValueError( - f"Rendered publication workload {workload} gRPC TLS paths do not match the split leaf/trust mounts" + f"Rendered {workload_label} {workload} gRPC TLS paths do not match its leaf/trust mount layout" ) for mount in volume_mounts: @@ -1248,16 +1265,17 @@ def publication_workload_secret_requirements( continue if any(path_is_under_mount(path, mount_path) for path in grpc_paths.values()): raise ValueError( - f"Rendered publication workload {workload} has another volume mount covering a gRPC TLS path" + f"Rendered {workload_label} {workload} has another volume mount covering a gRPC TLS path" ) requirements.append( - (secret_name, workload_namespace, set(PUBLICATION_GRPC_LEAF_SECRET_KEYS)) + (secret_name, workload_namespace, set(GRPC_WORKLOAD_LEAF_SECRET_KEYS)) ) leaf_secret_names.append(secret_name) if len(set(leaf_secret_names)) != len(leaf_secret_names): raise ValueError( - "Rendered publication workloads must mount five distinct grpc-tls Secrets" + "Rendered gRPC workload consumers must mount " + f"{len(GRPC_WORKLOAD_SECRET_CONSUMERS)} distinct grpc-tls Secrets" ) requirements.append( ( @@ -1275,7 +1293,7 @@ def publication_workload_secret_issues( *, lookup_cluster_secrets: bool = True, ) -> list[str]: - """Validate publication Secret bindings and, optionally, their live data keys.""" + """Validate workload Secret bindings and, optionally, their live data keys.""" try: requirements = publication_workload_secret_requirements(expected, documents) except (TypeError, ValueError) as exc: @@ -7552,7 +7570,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "fail", - "Publication workload render: " + "; ".join(publication_secret_issues), + "gRPC workload render: " + "; ".join(publication_secret_issues), ) or has_required_failure secret_check_failed = True if not secret_check_failed: @@ -7561,7 +7579,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "pass", - "Rendered player-facing and publication workloads reference required Secret bindings", + "Rendered player-facing and gRPC workload consumers reference required Secret bindings", ) or has_required_failure else: for secret_name, secret_namespace, binding_path in expected_player_secret_bindings( @@ -7603,7 +7621,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "fail", - "Publication workload certificate: " + "; ".join(publication_secret_issues), + "gRPC workload certificate: " + "; ".join(publication_secret_issues), ) or has_required_failure ) @@ -7615,7 +7633,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "pass", - "Required player-facing and publication workload Secrets and keys exist in the target cluster", + "Required player-facing and gRPC workload Secrets and keys exist in the target cluster", ) or has_required_failure ) diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index c803a3f308..d38f4648e9 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -66,6 +66,15 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "game-logic-service", "automation-scripting-service", } +ACCOUNT_GRPC_WORKLOADS = {"account-service"} +GAME_SESSION_GRPC_WORKLOADS = {"game-session-service"} +SOCIAL_GROUPS_GRPC_WORKLOADS = {"social-groups-service"} +DISTINCT_GRPC_WORKLOADS = ( + PUBLICATION_GRPC_WORKLOADS + | ACCOUNT_GRPC_WORKLOADS + | GAME_SESSION_GRPC_WORKLOADS + | SOCIAL_GROUPS_GRPC_WORKLOADS +) EXPECTED_NAMES = { "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, "Service": SERVICE_IMAGES @@ -78,6 +87,8 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "internal-services", "internal-services-egress", "account-service-controller-ingress", + "game-session-service-controller-ingress", + "social-groups-service-controller-ingress", "spring-cloud-gateway-ingress", "spring-cloud-gateway-egress", "tcp-proxy-service-egress", @@ -134,8 +145,8 @@ def walk(value: object, path: str = "object"): "minio-credentials", "firemud-grpc-tls", } -PUBLICATION_GRPC_SECRET_OWNERS = { - f"firemud-grpc-{service}": service for service in PUBLICATION_GRPC_WORKLOADS +DISTINCT_GRPC_SECRET_OWNERS = { + f"firemud-grpc-{service}": service for service in DISTINCT_GRPC_WORKLOADS } CANONICAL_INGRESS_ISSUER = "letsencrypt-prod" ALLOCATED_TELNET_PORT_ANNOTATION = "firemud.dev/allocated-telnet-port" @@ -225,8 +236,12 @@ def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[st kind: set(names) for kind, names in EXPECTED_NAMES.items() } if certificate_identity_mode == "standalone": - expected_names["NetworkPolicy"].discard( - "account-service-controller-ingress" + expected_names["NetworkPolicy"].difference_update( + { + "account-service-controller-ingress", + "game-session-service-controller-ingress", + "social-groups-service-controller-ingress", + } ) return expected_names @@ -758,14 +773,14 @@ def _is_sanitized_secret_reference(value: object) -> bool: ) -def _is_publication_grpc_secret_volume_source( +def _is_distinct_grpc_secret_volume_source( document: object, path: str, value: object ) -> bool: - """Allow a publication TLS Secret only in its owning Deployment's grpc-tls volume.""" + """Allow each distinct workload TLS Secret only in its owning Deployment.""" if not isinstance(value, str) or not isinstance(document, dict): return False - owner = PUBLICATION_GRPC_SECRET_OWNERS.get(value) + owner = DISTINCT_GRPC_SECRET_OWNERS.get(value) if owner is None: return False metadata = document.get("metadata") @@ -991,7 +1006,7 @@ def _validate_sanitized_secret_refs( for key, child in value.items(): if key == "secretName" and not ( _is_sanitized_secret_reference(child) - or _is_publication_grpc_secret_volume_source( + or _is_distinct_grpc_secret_volume_source( root_document, f"{path}.{key}", child ) ): @@ -1550,7 +1565,7 @@ def validate_service_consumers( fail(f"Deployment/{service} has an unexpected container layout") container = containers[0] - if service in PUBLICATION_GRPC_WORKLOADS: + if service in DISTINCT_GRPC_WORKLOADS: workload_namespace_entries = [ entry for entry in container.get("env", []) @@ -1573,7 +1588,7 @@ def validate_service_consumers( "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", "FIREMUD_GRPC_CA_CERT_PATH": "/grpc-trust/ca.crt", } - if service in PUBLICATION_GRPC_WORKLOADS + if service in DISTINCT_GRPC_WORKLOADS else { "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", @@ -1593,14 +1608,14 @@ def validate_service_consumers( grpc_secret_name = ( f"firemud-grpc-{service}" - if service in PUBLICATION_GRPC_WORKLOADS + if service in DISTINCT_GRPC_WORKLOADS else "firemud-grpc-tls" ) expected_mounts = { "grpc-tls": ("/tls", grpc_secret_name), "jwt-signing-keys": ("/var/run/secrets/firemud/jwt", "jwt-signing-keys"), } - if service in PUBLICATION_GRPC_WORKLOADS: + if service in DISTINCT_GRPC_WORKLOADS: expected_mounts["grpc-trust"] = ("/grpc-trust", "firemud-grpc-tls") if service == "account-service": expected_mounts["jwt-jwks"] = ("/var/run/secrets/firemud/jwks", "jwt-jwks") @@ -1665,6 +1680,15 @@ def validate_service_consumers( f"Deployment/{service}.spec.template.spec.volumes[{volume_name}].secret", ) if source.get("secretName") != source_name: + if ( + service in DISTINCT_GRPC_WORKLOADS + and volume_name == "grpc-tls" + and source.get("secretName") == "firemud-grpc-tls" + ): + 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": expected_source = { @@ -1673,7 +1697,7 @@ def validate_service_consumers( } if source != expected_source: fail(f"Deployment/{service} has an unsafe grpc-trust projection") - if volume_name == "grpc-tls" and service in PUBLICATION_GRPC_WORKLOADS: + if volume_name == "grpc-tls" and service in DISTINCT_GRPC_WORKLOADS: expected_source = { "secretName": source_name, "items": [ @@ -1794,26 +1818,28 @@ def validate_network_policies( }, } if certificate_identity_mode == "hosted-controller": - controller_policy = policies["account-service-controller-ingress"] - spec = _require_mapping( - controller_policy.get("spec"), - "NetworkPolicy/account-service-controller-ingress.spec", - ) - if spec.get("podSelector") != {"matchLabels": {"app": "account-service"}}: - fail( - "NetworkPolicy/account-service-controller-ingress selects an unsafe workload" - ) - if spec.get("policyTypes") != ["Ingress"]: - fail( - "NetworkPolicy/account-service-controller-ingress must only govern ingress" - ) - expected_ingress = [ - {"from": [expected_from], "ports": [{"protocol": "TCP", "port": 6565}]} - ] - if spec.get("ingress") != expected_ingress: - fail( - "NetworkPolicy/account-service-controller-ingress has an unsafe exception" + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + policy_name = f"{workload}-controller-ingress" + spec = _require_mapping( + policies[policy_name].get("spec"), + f"NetworkPolicy/{policy_name}.spec", ) + if spec.get("podSelector") != {"matchLabels": {"app": workload}}: + fail(f"NetworkPolicy/{policy_name} selects an unsafe workload") + if spec.get("policyTypes") != ["Ingress"]: + fail(f"NetworkPolicy/{policy_name} must only govern ingress") + expected_ingress = [ + { + "from": [expected_from], + "ports": [{"protocol": "TCP", "port": 6565}], + } + ] + if spec.get("ingress") != expected_ingress: + fail(f"NetworkPolicy/{policy_name} has an unsafe exception") gateway_ingress = _require_mapping( policies["spring-cloud-gateway-ingress"].get("spec"), @@ -2062,7 +2088,7 @@ def validate_manifest( fail(f"{location} retains a PR-selected nodePort") if location.endswith(".secretName") and not ( _is_manifest_secret_reference(value, expected_namespace) - or _is_publication_grpc_secret_volume_source( + or _is_distinct_grpc_secret_volume_source( document, location, value ) ): diff --git a/dev-tools/hosted/preview/wait-for-hosted-identity.sh b/dev-tools/hosted/preview/wait-for-hosted-identity.sh index 09564b0363..268f892dd2 100644 --- a/dev-tools/hosted/preview/wait-for-hosted-identity.sh +++ b/dev-tools/hosted/preview/wait-for-hosted-identity.sh @@ -150,6 +150,11 @@ if [[ "${1:-}" == "--projections" ]]; then "firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt" ) done + projections+=( + "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" + ) initialize_wait_state "$timeout_seconds" all_projections_ready=true for projection in "${projections[@]}"; do diff --git a/dev-tools/hosted/shared/README.md b/dev-tools/hosted/shared/README.md index 7bfbbf389c..9871933959 100644 --- a/dev-tools/hosted/shared/README.md +++ b/dev-tools/hosted/shared/README.md @@ -20,10 +20,10 @@ These scripts are shared because they manage infrastructure or validation behavi - creates or updates the shared GHCR image-pull secret in the target namespace - `ensure-grpc-tls-secret.sh` - - preserves the shared bundle for non-publication workloads; in standalone mode it validates the five issuer-projected publication leaves, adds only their public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven + - preserves the shared bundle for the three remaining shared-leaf workloads; in standalone mode it validates eight issuer-projected workload leaves, adds their common public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven - `ensure-standalone-grpc-certificates.sh` - - uses the scoped certificate-writer credential to request the five fixed `firemud-ca-issuer` publication Certificates in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys + - uses the scoped certificate-writer credential to request eight fixed `firemud-ca-issuer` workload Certificates (five publication plus Account, Game Session, and Social Groups) in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys - `wait-for-runtime-images.sh` - for a pull request, waits for a `runtime-images.yml` run whose exact base, head, and test-merge identities match, then waits for the trusted publisher to publish the immutable `pr-merge-` tag diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index 1230911159..399c3fc851 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -48,6 +48,9 @@ workloads=( entity-management-service game-logic-service automation-scripting-service + account-service + game-session-service + social-groups-service ) secret_exists() { @@ -254,7 +257,7 @@ fi if ((shared_snapshot_status == 1)); then for workload in "${workloads[@]}"; do if secret_exists "firemud-grpc-${workload}"; then - echo "shared gRPC TLS Secret is missing while a cert-manager publication Secret exists; refusing fresh replacement" >&2 + echo "shared gRPC TLS Secret is missing while a distinct workload Secret exists; refusing fresh replacement" >&2 exit 1 fi done @@ -277,8 +280,8 @@ if ((shared_snapshot_status == 0)); then "${shared_rotation_resources[*]}" || exit 1 assert_key_matches_certificate "$shared_cert" "$shared_key" else - # The legacy shared bundle is still required by the six non-publication - # workloads. Generate it once, then preserve its leaf on every later run. + # The legacy shared bundle is still required by remaining shared-leaf workloads. + # Generate it once, then preserve its leaf on every later run. "$legacy_generator" "$cert_dir" for required_file in ca.crt client.crt client.key ca.key; do [[ -s "$cert_dir/$required_file" ]] || { @@ -351,7 +354,7 @@ for workload in "${workloads[@]}"; do "Secret/${namespace}/${secret_name}" ) assert_certificate_unexpired "$workload_cert" \ - "cert-manager publication certificate in Secret ${namespace}/${secret_name}" \ + "cert-manager workload certificate in Secret ${namespace}/${secret_name}" \ "${workload_rotation_resources[*]}" || exit 1 if ! ca_basic_constraints="$(openssl x509 -in "$workload_ca" -noout -ext basicConstraints 2>/dev/null)"; then echo "cert-manager CA projection basic constraints could not be read: ${namespace}/${secret_name}" >&2 @@ -365,12 +368,12 @@ for workload in "${workloads[@]}"; do "cert-manager CA projection in Secret ${namespace}/${secret_name}" \ "${workload_rotation_resources[*]}" || exit 1 openssl verify -CAfile "$workload_ca" "$workload_cert" >/dev/null || { - echo "cert-manager publication certificate does not chain to its projected CA: ${namespace}/${secret_name}" >&2 + echo "cert-manager workload certificate does not chain to its projected CA: ${namespace}/${secret_name}" >&2 exit 1 } current_issuer_fingerprint="$(openssl x509 -in "$workload_ca" -outform der | openssl sha256)" if [[ -n "$issuer_fingerprint" && "$issuer_fingerprint" != "$current_issuer_fingerprint" ]]; then - echo "cert-manager publication Secrets do not share one CA projection" >&2 + echo "cert-manager workload Secrets do not share one CA projection" >&2 exit 1 fi issuer_fingerprint="$current_issuer_fingerprint" @@ -378,11 +381,11 @@ for workload in "${workloads[@]}"; do fingerprint="$(openssl x509 -in "$workload_cert" -outform der | openssl sha256)" [[ "$fingerprint" != "$shared_fingerprint" ]] || { - echo "publication workload certificate must not reuse the shared gRPC leaf: $secret_name" >&2 + echo "workload certificate must not reuse the shared gRPC leaf: $secret_name" >&2 exit 1 } [[ -z "${fingerprints[$fingerprint]+present}" ]] || { - echo "publication workload certificates must have distinct leaf identities: $secret_name" >&2 + echo "workload certificates must have distinct leaf identities: $secret_name" >&2 exit 1 } fingerprints["$fingerprint"]="$workload" @@ -404,4 +407,4 @@ for workload in "${workloads[@]}"; do kubectl -n "$namespace" delete secret "${namespace}-grpc-${workload}" --ignore-not-found >/dev/null done -echo "cert-manager gRPC TLS material is ready in namespace ${namespace}: shared legacy bundle plus ${#fingerprints[@]} distinct publication leaves" +echo "cert-manager gRPC TLS material is ready in namespace ${namespace}: shared legacy bundle plus ${#fingerprints[@]} distinct workload leaves" diff --git a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh index facde3fd6d..dc56d74a5c 100644 --- a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh +++ b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh @@ -28,6 +28,9 @@ workloads=( entity-management-service game-logic-service automation-scripting-service + account-service + game-session-service + social-groups-service ) write_certificates() { diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index cd9599d2f9..b3203b830e 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -53,17 +53,19 @@ contains_literal "$certificate_generator" \ # These are literal source snippets; expansion would change what the contract checks. # shellcheck disable=SC2016 for required in \ + 'escaped_key="${key//./\\.}"' \ 'get secret "$secret_name" --ignore-not-found -o name' \ 'failed to look up Kubernetes Secret ${namespace}/${secret_name}' \ - "local jsonpath='{.metadata.name}'" \ 'jsonpath+="{\"|\"}{.data.${escaped_key}}"' \ + 'if read_secret_snapshot "$shared_secret"' \ + "local jsonpath='{.metadata.name}'" \ 'jsonpath=${jsonpath}' \ 'failed to fetch Kubernetes Secret snapshot ${namespace}/${secret_name}' \ 'if ((shared_snapshot_status == 0)); then' \ 'assert_certificate_unexpired "$shared_cert"' \ 'shared gRPC TLS client certificate in Secret ${namespace}/${shared_secret}' \ 'assert_certificate_unexpired "$workload_cert"' \ - 'cert-manager publication certificate in Secret' \ + 'cert-manager workload certificate in Secret' \ 'cert-manager CA projection' \ 'openssl verify -CAfile "$workload_ca" "$workload_cert"' \ 'kubectl -n "$namespace" delete secret firemud-grpc-ca --ignore-not-found' \ @@ -80,6 +82,9 @@ for required in \ ' world-management-service' \ ' entity-management-service' \ ' game-logic-service' \ + ' account-service' \ + ' game-session-service' \ + ' social-groups-service' \ ' automation-scripting-service'; do contains_literal "$standalone_grpc_tls" "$required" done @@ -359,6 +364,35 @@ openssl pkey -in "$certificate_fixture_dir/valid.key" -check -noout >/dev/null 2 echo "generated publication key failed OpenSSL key validation" >&2 exit 1 } +"$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$certificate_fixture_dir/ca.crt" "$certificate_fixture_dir/ca.key" \ + "$certificate_fixture_dir/social-groups.crt" "$certificate_fixture_dir/social-groups.key" \ + pr-42 social-groups-service +social_groups_sans="$(openssl x509 -in "$certificate_fixture_dir/social-groups.crt" \ + -noout -ext subjectAltName)" +grep -Fq 'URI:spiffe://firemud/ns/pr-42/sa/social-groups-service' \ + <<<"$social_groups_sans" || { + echo "generated Social Groups certificate is missing its exact SPIFFE identity" >&2 + exit 1 +} +grep -Fq 'DNS:social-groups-service.pr-42.svc.cluster.local' \ + <<<"$social_groups_sans" || { + echo "generated Social Groups certificate is missing its exact Service DNS SAN" >&2 + exit 1 +} +if "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$certificate_fixture_dir/ca.crt" "$certificate_fixture_dir/ca.key" \ + "$certificate_fixture_dir/unsupported.crt" "$certificate_fixture_dir/unsupported.key" \ + pr-42 unsupported-service >"$certificate_fixture_dir/unsupported.stdout" \ + 2>"$certificate_fixture_dir/unsupported.stderr"; then + echo "workload certificate helper accepted an unlisted service" >&2 + exit 1 +fi +grep -Fq 'unsupported gRPC workload identity: unsupported-service' \ + "$certificate_fixture_dir/unsupported.stderr" || { + echo "workload certificate helper rejected an unknown service without the expected diagnostic" >&2 + exit 1 +} echo "dev-demo certificate fixture: canonical workload certificate generated" >&2 make_profile_certificate() { @@ -1715,6 +1749,9 @@ for required in ( '"firemud-grpc-tls|grpc|tls.crt,tls.key,ca.crt,client.crt,client.key"', 'publication_workloads=(', 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt', + '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', ' game-design-service', ' world-management-service', ' entity-management-service', diff --git a/dev-tools/tests/ensure-grpc-tls-secret-contract.sh b/dev-tools/tests/ensure-grpc-tls-secret-contract.sh index 1514001604..6e16ffe71f 100644 --- a/dev-tools/tests/ensure-grpc-tls-secret-contract.sh +++ b/dev-tools/tests/ensure-grpc-tls-secret-contract.sh @@ -21,12 +21,15 @@ workloads=( entity-management-service game-logic-service automation-scripting-service + account-service + game-session-service + social-groups-service ) data_dir="$fixture_dir/data" mock_bin="$fixture_dir/bin" mkdir -p "$data_dir" "$mock_bin" -# Build one shared issuer and five distinct workload identities. The helper +# Build one shared issuer and eight distinct workload identities. The helper # validates the real X.509 extensions, SANs, key pairs, and issuer chains. openssl ecparam -genkey -name prime256v1 -noout -out "$fixture_dir/shared-issuer.key" openssl req -x509 -new -key "$fixture_dir/shared-issuer.key" -sha256 -days 30 \ @@ -287,8 +290,8 @@ if ! run_helper complete "$success_log" "$fixture_dir/success-state" "" 30 \ cat "$fixture_dir/success.out" "$fixture_dir/success.err" >&2 exit 1 fi -grep -Fq '5 distinct publication leaves' "$fixture_dir/success.out" || { - echo "the helper did not accept five valid cert-manager projections" >&2 +grep -Fq '8 distinct workload leaves' "$fixture_dir/success.out" || { + echo "the helper did not accept eight valid cert-manager projections" >&2 exit 1 } large_constraints_log="$fixture_dir/large-constraints.log" @@ -299,7 +302,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 '5 distinct publication leaves' "$fixture_dir/large-constraints.out" || { +grep -Fq '8 distinct workload leaves' "$fixture_dir/large-constraints.out" || { echo "the helper did not accept valid CA constraints with large extension output" >&2 exit 1 } @@ -320,7 +323,7 @@ for secret in firemud-grpc-tls "${workloads[@]/#/firemud-grpc-}"; do exit 1 } done -last_projection_line="$(grep -n '^snapshot dev/firemud-grpc-automation-scripting-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-social-groups-service 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" && \ @@ -338,7 +341,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 '5 distinct publication leaves' "$fixture_dir/warning-lookup.out" || { +grep -Fq '8 distinct workload leaves' "$fixture_dir/warning-lookup.out" || { echo "a warning on an absent Secret was treated as an existing Secret" >&2 exit 1 } @@ -475,8 +478,8 @@ if grep -q '^delete ' "$incomplete_log"; then exit 1 fi -# Each publication projection becomes ready on its second read, one simulated -# second later. The helper must apply one timeout to all five workloads rather +# Each workload projection becomes ready on its second read, one simulated +# second later. The helper must apply one timeout to all eight 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 d038d231e5..63a94ffbd8 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -348,28 +348,29 @@ if labelled_objects != {("Deployment", "tcp-proxy-service"), ("Service", "tcp-pr "certificate identity mode label rendered on an unexpected hosted object" ) -account_policy = named("NetworkPolicy", "account-service-controller-ingress")["spec"] -if account_policy != { - "podSelector": {"matchLabels": {"app": "account-service"}}, - "policyTypes": ["Ingress"], - "ingress": [{ - "from": [{ - "namespaceSelector": { - "matchLabels": {"kubernetes.io/metadata.name": "firemud-system"} - }, - "podSelector": { - "matchLabels": { - "app.kubernetes.io/name": "hosted-environment-identity-controller", - "app.kubernetes.io/component": "controller", - } - }, +for workload in ("account-service", "game-session-service", "social-groups-service"): + workload_policy = named("NetworkPolicy", f"{workload}-controller-ingress")["spec"] + if workload_policy != { + "podSelector": {"matchLabels": {"app": workload}}, + "policyTypes": ["Ingress"], + "ingress": [{ + "from": [{ + "namespaceSelector": { + "matchLabels": {"kubernetes.io/metadata.name": "firemud-system"} + }, + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "hosted-environment-identity-controller", + "app.kubernetes.io/component": "controller", + } + }, + }], + "ports": [{"protocol": "TCP", "port": 6565}], }], - "ports": [{"protocol": "TCP", "port": 6565}], - }], -}: - raise SystemExit( - "Hosted Account ingress policy must allow only the identity controller to TCP 6565" - ) + }: + raise SystemExit( + f"Hosted {workload} ingress policy must allow only the identity controller to TCP 6565" + ) gateway_policy = named("NetworkPolicy", "spring-cloud-gateway-ingress")["spec"] if gateway_policy["podSelector"] != {"matchLabels": {"app": "spring-cloud-gateway"}}: @@ -498,11 +499,16 @@ documents = [ ] if any( document.get("kind") == "NetworkPolicy" - and document.get("metadata", {}).get("name") == "account-service-controller-ingress" + and document.get("metadata", {}).get("name") + in { + "account-service-controller-ingress", + "game-session-service-controller-ingress", + "social-groups-service-controller-ingress", + } for document in documents ): raise SystemExit( - "standalone certificate identity mode unexpectedly rendered the hosted controller Account ingress policy" + "standalone certificate identity mode unexpectedly rendered a hosted controller gRPC ingress policy" ) for kind in ("Deployment", "Service"): matches = [ diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 70b049d6d8..804ce78ee1 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 grpcPublication; do +for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcSocialGroupsService 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") == 5 +assert source.count("*consumer_status_schema") == 8 crd = yaml.safe_load(source) schema = crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"] assert crd["spec"].get("preserveUnknownFields", False) is False @@ -458,6 +458,9 @@ consumer_schemas = [ for name in ("ingress", "telnet", "gatewayInternalWs", "tcpProxyBridge", "grpc") ] 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] publication_roles = consumer_properties["grpcPublication"] assert publication_roles["type"] == "object" assert publication_roles["maxProperties"] == 5 @@ -641,18 +644,18 @@ assert len(binding_policy_names) == len(policy_names) assert set(binding_policy_names) == policy_names identity_namespace_fragment = "pr-[1-9][0-9]{0,50}-identity" -publication_service_regex_group = ( +grpc_workload_service_regex_group = ( "(game-design-service|world-management-service|entity-management-service|" - "game-logic-service|automation-scripting-service)" + "game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)" ) admission_variable_contracts = { "firemud-hosted-identity-secret-boundary": { "hostedPreviewIdentityNamespacePattern": f"'{identity_namespace_fragment}'", - "publicationServiceRegexGroup": f"'{publication_service_regex_group}'", + "grpcWorkloadServiceRegexGroup": f"'{grpc_workload_service_regex_group}'", }, "firemud-hosted-identity-certificate-boundary": { "hostedPreviewIdentityNamespacePattern": f"'{identity_namespace_fragment}'", - "publicationServiceRegexGroup": f"'{publication_service_regex_group}'", + "grpcWorkloadServiceRegexGroup": f"'{grpc_workload_service_regex_group}'", }, "firemud-hosted-identity-scope-roles": { "hostedPreviewIdentityNamespacePattern": f"'{identity_namespace_fragment}'", @@ -692,10 +695,10 @@ def assert_admission_variable_contract(candidate_policies): assert identity_namespace_fragment in match_condition_expression, policy_name assert identity_namespace_fragment not in validation_expression, policy_name assert "variables.hostedPreviewIdentityNamespacePattern" in validation_expression, policy_name - if "publicationServiceRegexGroup" in expected_variables: - assert publication_service_regex_group in match_condition_expression, policy_name - assert publication_service_regex_group not in validation_expression, policy_name - assert "variables.publicationServiceRegexGroup" in validation_expression, policy_name + if "grpcWorkloadServiceRegexGroup" in expected_variables: + assert grpc_workload_service_regex_group in match_condition_expression, policy_name + assert grpc_workload_service_regex_group not in validation_expression, policy_name + assert "variables.grpcWorkloadServiceRegexGroup" in validation_expression, policy_name for variable_name in expected_variables: assert f"variables.{variable_name}" in validation_expression, ( policy_name, @@ -723,7 +726,7 @@ secret_variables = missing_publication_variable[ secret_variables[:] = [ variable for variable in secret_variables - if variable.get("name") != "publicationServiceRegexGroup" + if variable.get("name") != "grpcWorkloadServiceRegexGroup" ] assert_admission_variable_contract_rejects( missing_publication_variable, "a missing publication service variable" @@ -747,7 +750,7 @@ secret_variables = misplaced_publication_variable[ misplaced_variable = next( variable for variable in secret_variables - if variable.get("name") == "publicationServiceRegexGroup" + if variable.get("name") == "grpcWorkloadServiceRegexGroup" ) secret_variables.remove(misplaced_variable) misplaced_publication_variable["firemud-hosted-identity-main"]["spec"][ @@ -1371,10 +1374,10 @@ assert "request.operation != 'DELETE'" in secret_match assert "request.name == 'firemud-grpc-tls'" in secret_match assert "object.metadata.name == 'firemud-grpc-tls'" in secret_match for publication_secret_pattern in ( - "request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)$')", - "object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)$')", - "request.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))$')", - "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))$')", + "request.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)$')", + "request.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))$')", ): assert publication_secret_pattern in normalized_secret_match @@ -1396,9 +1399,14 @@ namespace_controller_secret_expression = next( normalized_namespace_controller_secret_expression = " ".join( namespace_controller_secret_expression.split() ) -assert "request.name.matches('^firemud-grpc-' + variables.publicationServiceRegexGroup + '(-previous)?$')" in normalized_namespace_controller_secret_expression +assert "request.name.matches('^firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '(-previous)?$')" in normalized_namespace_controller_secret_expression assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in controller_secret_expression +assert "'grpc-account-service'" in controller_secret_expression +assert "'grpc-game-session-service'" in controller_secret_expression +assert "'grpc-social-groups-service'" in controller_secret_expression assert "object.metadata.name == 'firemud-grpc-tls'" in controller_secret_expression +assert "object.metadata.name == 'firemud-grpc-account-service'" in controller_secret_expression +assert "object.metadata.name == 'firemud-grpc-game-session-service'" in controller_secret_expression assert normalized_controller_secret_expression.count("request.name.startsWith(") == 3 assert normalized_controller_secret_expression.count("object.metadata.name.startsWith(") == 2 assert "request.namespace.size() - 9" in normalized_controller_secret_expression @@ -1424,6 +1432,9 @@ def canonical_primary_name(namespace, name): "grpc-entity-management-service", "grpc-game-logic-service", "grpc-automation-scripting-service", + "grpc-account-service", + "grpc-game-session-service", + "grpc-social-groups-service", } @@ -1434,11 +1445,11 @@ def namespace_controller_secret_delete_is_allowed(namespace, name): return False if name in {"firemud-grpc-tls", "firemud-grpc-tls-previous"}: return True - fixed_publication_secret = re.fullmatch( - r"firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)(-previous)?", + 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)?", name, ) - return bool(fixed_publication_secret) or canonical_primary_name(namespace, name.removesuffix("-previous")) + return bool(fixed_workload_secret) or canonical_primary_name(namespace, name.removesuffix("-previous")) assert canonical_primary_name("dev-identity", "dev-tls") @@ -1481,7 +1492,7 @@ assert "request.operation in ['CREATE', 'UPDATE']" in controller_grants assert "object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller'" in controller_grants assert "object.metadata.labels['firemud.dev/retention'] == 'retained'" in controller_grants for workload in publication_workloads: - assert "request.name.matches('^firemud-grpc-' + variables.publicationServiceRegexGroup + '$')" in controller_grants + assert "request.name.matches('^firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '$')" in controller_grants assert ( f"object.metadata.name == 'firemud-grpc-{workload}' && " f"object.metadata.labels['firemud.dev/role'] == 'grpc-publication-{workload}'" @@ -1540,6 +1551,12 @@ assert "object.metadata.name == 'dev-telnet-tls'" in cert_manager_expression assert "object.metadata.name == 'dev-gateway-internal-ws'" in cert_manager_expression assert "object.metadata.name == 'dev-tcp-proxy-bridge'" in cert_manager_expression assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in cert_manager_expression +assert "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service'" in cert_manager_expression +assert "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service'" in cert_manager_expression +assert "object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service'" in cert_manager_expression +assert "object.metadata.name == 'dev-grpc-account-service'" in cert_manager_expression +assert "object.metadata.name == 'dev-grpc-game-session-service'" in cert_manager_expression +assert "object.metadata.name == 'dev-grpc-social-groups-service'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-telnet-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-gateway-internal-ws'" in cert_manager_expression @@ -1591,8 +1608,11 @@ assert "firemud-grpc-tls" not in controller_delete_expression assert "request.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']" 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 "grpc-publication-" in certificate_match +assert "grpc-account-service" in certificate_match +assert "grpc-game-session-service" in certificate_match +assert "grpc-social-groups-service" in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ @@ -1608,6 +1628,7 @@ controller_non_delete_expression = certificate_expressions[0].split( assert "firemud-grpc-tls" not in controller_non_delete_expression assert "'grpc'" not in controller_non_delete_expression assert "grpc-publication-" in controller_non_delete_expression +assert "grpc-account-service" in controller_non_delete_expression assert "has(object.spec.isCA)" in controller_non_delete_expression assert "object.spec.isCA == false" in controller_non_delete_expression assert "(!has(object.spec.commonName) || object.spec.commonName == '')" in controller_non_delete_expression @@ -1632,6 +1653,9 @@ profile_expression = next( normalized_profile_expression = " ".join(profile_expression.split()) assert "spring-cloud-gateway-mtls." in profile_expression assert ".svc.cluster.local" in profile_expression +assert "object.spec.uris == ['spiffe://firemud/ns/'" in profile_expression +assert "object.spec.dnsNames == ['account-service'" in profile_expression +assert "object.spec.dnsNames == ['game-session-service'" in profile_expression assert "spiffe://firemud/ns/" in profile_expression assert "/sa/tcp-proxy-service" in profile_expression assert "has(object.spec.encodeUsagesInRequest)" in profile_expression @@ -1648,24 +1672,59 @@ assert "object.spec.issuerRef.name == 'letsencrypt-prod'" in profile_expression assert "object.spec.issuerRef.name == 'firemud-ca-issuer'" in profile_expression assert "object.spec.issuerRef.kind == 'ClusterIssuer'" in profile_expression assert "object.spec.issuerRef.group == 'cert-manager.io'" in profile_expression -publication_issuer_profile = ( +internal_issuer_profile = ( "((object.metadata.labels['firemud.dev/role'] in " - "['gateway-internal-ws', 'tcp-proxy-bridge'] || " + "['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.spec.issuerRef.name == 'firemud-ca-issuer')" ) -assert publication_issuer_profile in normalized_profile_expression +assert internal_issuer_profile in normalized_profile_expression publication_san_guard = ( "object.spec.usages == ['digital signature', 'key encipherment', 'client auth'])) && " "(!object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') ||" ) assert publication_san_guard in normalized_profile_expression -publication_certificate_name_guard = ( - "object.metadata.name == (((request.namespace == 'dev-identity') ? 'dev' : " - "request.namespace.substring(0, request.namespace.size() - 9)) + '-grpc-' + " - "object.metadata.labels['firemud.dev/role'].substring(17))" +publication_secret_name_guards = ( + "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && " + "object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)", + "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && " + "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 == '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-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'", ) -assert publication_certificate_name_guard in normalized_profile_expression +for publication_secret_name_guard in publication_secret_name_guards: + assert publication_secret_name_guard in normalized_controller_secret_expression +namespace_service = "((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9))" +for role, service in ( + ("grpc-account-service", "account-service"), + ("grpc-game-session-service", "game-session-service"), + ("grpc-social-groups-service", "social-groups-service"), +): + service_profile = ( + f"(object.metadata.labels['firemud.dev/role'] != '{role}' || " + "(object.spec.secretName == object.metadata.name && " + f"object.spec.dnsNames == ['{service}', '{service}.' + {namespace_service}, " + f"'{service}.' + {namespace_service} + '.svc', " + f"'{service}.' + {namespace_service} + '.svc.cluster.local'] && " + f"object.spec.uris == ['spiffe://firemud/ns/' + {namespace_service} + '/sa/{service}'] && " + "object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))" + ) + assert service_profile in normalized_profile_expression assert_balanced_cel_delimiters(profile_expression, "publication Certificate profile") for required_publication_common_guard in ( "request.operation != 'DELETE'", @@ -2019,22 +2078,32 @@ tcp_proxy_rules = [ ] assert len(tcp_proxy_rules) == 1 assert tcp_proxy_rules[0]["ports"] == [{"protocol": "TCP", "port": 2323}] -grpc_targets = [ - target +grpc_rules = [ + rule for rule in policy["spec"]["egress"] if any(port.get("port") == 6565 for port in rule.get("ports", [])) - for target in rule.get("to", []) ] -assert grpc_targets, "controller gRPC egress rule is missing" -for target in grpc_targets: - assert target.get("namespaceSelector", {}).get("matchLabels", {}).get( - "firemud.dev/preview" - ) == "true" or target.get("namespaceSelector", {}).get("matchLabels", {}).get( - "firemud.dev/dev-demo" - ) == "true", target - assert target.get("podSelector", {}).get("matchLabels") == { - "app": "account-service" - }, target +assert len(grpc_rules) == 1, grpc_rules +assert grpc_rules[0]["ports"] == [{"protocol": "TCP", "port": 6565}] +grpc_targets = grpc_rules[0]["to"] +assert { + ( + tuple(sorted(target["namespaceSelector"]["matchLabels"].items())), + tuple(sorted(target["podSelector"]["matchLabels"].items())), + ) + for target in grpc_targets +} == { + (namespace, (("app", workload),)) + for namespace in ( + (("firemud.dev/preview", "true"),), + (("firemud.dev/dev-demo", "true"),), + ) + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ) +}, grpc_targets PY for text_value in \ FIREMUD_HOSTED_IDENTITY_TRUSTED_OPERATOR \ @@ -2129,7 +2198,12 @@ for portable_render_fragment in \ require_literal "$BOOTSTRAP" "$portable_render_fragment" done require_literal "$ADMISSION" "'firemud-grpc-tls-previous', " -require_literal "$ADMISSION" "'-grpc-automation-scripting-service-previous')] &&" +require_literal "$ADMISSION" "'firemud-grpc-account-service'" +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" "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. @@ -3807,13 +3881,7 @@ def service_consumer_documents(): "/tls", "secret", f"firemud-grpc-{service}" - if service in { - "game-design-service", - "world-management-service", - "entity-management-service", - "game-logic-service", - "automation-scripting-service", - } + if service in validator.DISTINCT_GRPC_WORKLOADS else "firemud-grpc-tls", ), "jwt-signing-keys": ( @@ -3822,14 +3890,8 @@ def service_consumer_documents(): "jwt-signing-keys", ), } - publication_workload = service in { - "game-design-service", - "world-management-service", - "entity-management-service", - "game-logic-service", - "automation-scripting-service", - } - if publication_workload: + distinct_workload = service in validator.DISTINCT_GRPC_WORKLOADS + if distinct_workload: sources["grpc-trust"] = ( "/grpc-trust", "secret", @@ -3872,7 +3934,7 @@ def service_consumer_documents(): {"key": "tls.key", "path": "tls.key"}, {"key": "ca.crt", "path": "ca.crt"}, ] - elif name == "grpc-tls" and publication_workload: + elif name == "grpc-tls" and distinct_workload: projection["items"] = [ {"key": "tls.crt", "path": "tls.crt"}, {"key": "tls.key", "path": "tls.key"}, @@ -3886,14 +3948,12 @@ def service_consumer_documents(): "name": service, "volumeMounts": mounts, } - if service in { - "game-design-service", - "world-management-service", - "entity-management-service", - "game-logic-service", - "automation-scripting-service", - }: + if service in validator.DISTINCT_GRPC_WORKLOADS: container["env"] = [ + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }, { "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", "value": "/tls/tls.crt", @@ -3906,10 +3966,6 @@ def service_consumer_documents(): "name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/grpc-trust/ca.crt", }, - { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, - }, ] elif service != "spring-cloud-gateway": container["env"] = [ @@ -4490,7 +4546,9 @@ if ! helm template hosted-identity-contract "$ROOT_DIR/k8s/helm/firemud" \ >"$helm_rendered"; then fail "Helm chart render failed for resolved hosted values fixture" fi -python3 - "$helm_rendered" "$base_rendered" <<'PY' +python3 - "$helm_rendered" "$base_rendered" "$ARTIFACT_VALIDATOR" <<'PY' +import copy +import importlib.util import sys from pathlib import Path @@ -4512,6 +4570,54 @@ documents = [ for document in yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8")) if isinstance(document, dict) ] +validator_spec = importlib.util.spec_from_file_location( + "preview_artifact_validator", sys.argv[3] +) +validator = importlib.util.module_from_spec(validator_spec) +validator_spec.loader.exec_module(validator) +network_policies = [ + document for document in documents if document.get("kind") == "NetworkPolicy" +] +validator.validate_network_policies(network_policies) +social_policy_name = "social-groups-service-controller-ingress" +assert any( + document.get("metadata", {}).get("name") == social_policy_name + for document in network_policies +) +without_social_controller_ingress = [ + document + for document in network_policies + if document.get("metadata", {}).get("name") != social_policy_name +] +try: + validator.validate_network_policies(without_social_controller_ingress) +except ValueError as error: + assert social_policy_name in str(error), str(error) +else: + raise AssertionError( + "preview validator accepted a missing Social Groups controller probe rule" + ) + +unsafe_social_controller_ingress = copy.deepcopy(network_policies) +social_policy = next( + document + for document in unsafe_social_controller_ingress + if document.get("metadata", {}).get("name") == social_policy_name +) +social_policy["spec"]["ingress"][0]["from"][0]["namespaceSelector"]["matchLabels"][ + "kubernetes.io/metadata.name" +] = "kube-system" +try: + validator.validate_network_policies(unsafe_social_controller_ingress) +except ValueError as error: + assert str(error) == ( + f"NetworkPolicy/{social_policy_name} has an unsafe exception" + ), str(error) +else: + raise AssertionError( + "preview validator accepted a widened Social Groups controller ingress" + ) + deployments = {} for document in documents: if document.get("kind") != "Deployment": @@ -4527,11 +4633,13 @@ publication_services = ( "game-logic-service", "automation-scripting-service", ) -shared_services = ( +distinct_workload_services = publication_services + ( "account-service", "game-session-service", - "logging-admin-service", "social-groups-service", +) +shared_services = ( + "logging-admin-service", "spring-cloud-gateway", "tcp-proxy-service", ) @@ -4604,7 +4712,7 @@ def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): fail(f"Deployment/{service} grpc-tls must mount read-only at /tls") -def assert_publication_service(service, deployment_map, source): +def assert_distinct_workload_service(service, deployment_map, source): deployment = deployment_for(service, deployment_map) container, pod_spec = workload_container(deployment, service) assert_paths_and_mount( @@ -4632,6 +4740,11 @@ def assert_publication_service(service, deployment_map, source): leaf_secret = leaf_volume.get("secret", {}) expected_secret = f"firemud-grpc-{service}" if leaf_secret.get("secretName") != expected_secret: + if leaf_secret.get("secretName") == "firemud-grpc-tls": + fail( + f"Deployment/{service} distinct workload falls back to " + "shared firemud-grpc-tls" + ) fail( f"{source} Deployment/{service} grpc-tls must use {expected_secret}, " f"found {leaf_secret.get('secretName')!r}" @@ -4673,8 +4786,8 @@ def assert_publication_service(service, deployment_map, source): ) -for service in publication_services: - assert_publication_service(service, deployments, "Helm") +for service in distinct_workload_services: + assert_distinct_workload_service(service, deployments, "Helm") for service in shared_services: deployment = deployment_for(service) @@ -4721,8 +4834,8 @@ for service in ( ).get("spec", {}).get("strategy", {}) if base_strategy.get("type") != "Recreate": fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") -for service in publication_services: - assert_publication_service(service, base_deployments, "Kustomize base") +for service in distinct_workload_services: + assert_distinct_workload_service(service, base_deployments, "Kustomize base") PY python3 - "$resolved_values" "$namespace_gate_values" <<'PY' diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 0f675f6c0f..82bdb6492b 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -630,6 +630,9 @@ contains "$waiter" 'tls.crt,tls.key,ca.crt,client.crt,client.key' contains "$waiter" 'publication_workloads=(' # shellcheck disable=SC2016 # Match literal shell source in the waiter. contains "$waiter" 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt' +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' for workload in \ game-design-service \ world-management-service \ @@ -5831,6 +5834,15 @@ if [[ "$1" == -n && "$2" == pr-42 && "$3" == get && "$4" == secret ]]; then firemud-grpc-automation-scripting-service) printf '%s' '{"metadata":{"name":"firemud-grpc-automation-scripting-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-publication-automation-scripting-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-account-service) + printf '%s' '{"metadata":{"name":"firemud-grpc-account-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-account-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; + firemud-grpc-game-session-service) + printf '%s' '{"metadata":{"name":"firemud-grpc-game-session-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-game-session-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; + 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"}}' + ;; *) printf 'unexpected projection Secret: %s\n' "$secret_name" >&2 exit 2 @@ -5946,19 +5958,20 @@ run_projection_waiter_fixture() { fi } -run_projection_waiter_fixture projection-absence 0 12 2 +# Successful two-retry fixtures read 13 canonical projections plus two retries. +run_projection_waiter_fixture projection-absence 0 15 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 12 2 +run_projection_waiter_fixture projection-transport-recovery 0 15 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 12 2 -run_projection_waiter_fixture projection-etcd-leader-recovery 0 12 2 -run_projection_waiter_fixture projection-overload-recovery 0 12 2 -run_projection_waiter_fixture projection-unavailable-recovery 0 12 2 -run_projection_waiter_fixture projection-currently-unavailable-recovery 0 12 2 -run_projection_waiter_fixture projection-apiserver-shutdown-recovery 0 12 2 +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_active_waiter_fixture() { local scenario="$1" diff --git a/dev-tools/tests/preflight-contract.sh b/dev-tools/tests/preflight-contract.sh index b2ad4d163f..97a03fe0a4 100644 --- a/dev-tools/tests/preflight-contract.sh +++ b/dev-tools/tests/preflight-contract.sh @@ -996,12 +996,25 @@ spec: containers: - name: account-service image: ghcr.io/benhook1013/account-service:latest + env: + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt envFrom: - secretRef: name: postgres-credentials - configMapRef: name: firemud-config volumeMounts: + - name: grpc-tls + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -1009,6 +1022,20 @@ spec: mountPath: /var/run/secrets/firemud/jwks readOnly: true volumes: + - name: grpc-tls + secret: + secretName: firemud-grpc-account-service + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt - name: jwt-signing-keys secret: secretName: jwt-signing-keys @@ -1018,6 +1045,46 @@ spec: --- apiVersion: apps/v1 kind: Deployment +metadata: + name: game-session-service +spec: + template: + spec: + containers: + - name: game-session-service + image: ghcr.io/benhook1013/game-session-service:latest + env: + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + volumeMounts: + - name: grpc-tls + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + volumes: + - name: grpc-tls + secret: + secretName: firemud-grpc-game-session-service + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt +--- +apiVersion: apps/v1 +kind: Deployment metadata: name: game-design-service spec: @@ -1213,6 +1280,7 @@ spec: YAML python3 - <<'PY' "$RENDERED_MANIFEST" +import copy import pathlib import sys @@ -1226,6 +1294,18 @@ documents = [ ] for document in documents: document.setdefault("metadata", {})["namespace"] = "firemud" +game_design = next( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "game-design-service" +) +social_groups = copy.deepcopy(game_design) +social_groups["metadata"]["name"] = "social-groups-service" +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) path.write_text(yaml.safe_dump_all(documents, sort_keys=False), encoding="utf-8") PY @@ -9889,30 +9969,44 @@ publication_documents = [ } }, } - for workload in module.PUBLICATION_GRPC_WORKLOADS + for workload in module.GRPC_WORKLOAD_SECRET_CONSUMERS ] +if module.PUBLICATION_GRPC_WORKLOADS != ( + "game-design-service", + "world-management-service", + "entity-management-service", + "game-logic-service", + "automation-scripting-service", +): + raise SystemExit("Account and Game Session changed the five publication-only workload set") +if module.SHARED_TRUST_GRPC_WORKLOADS != ( + *module.PUBLICATION_GRPC_WORKLOADS, + "social-groups-service", + *module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, +): + raise SystemExit("all eight distinct workloads must use the shared CA-only trust projection") publication_requirements = module.publication_workload_secret_requirements( publication_expected, publication_documents ) -expected_publication_names = { +expected_workload_secret_names = { f"firemud-grpc-{workload}" - for workload in module.PUBLICATION_GRPC_WORKLOADS + for workload in module.GRPC_WORKLOAD_SECRET_CONSUMERS } if {name for name, _, _ in publication_requirements} != ( - expected_publication_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} + expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): raise SystemExit( - "publication Secret requirements do not follow the five leaf bindings and shared trust binding" + "workload Secret requirements do not follow the eight 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): - raise SystemExit("publication Secret requirements did not use the expected-binding namespace") + raise SystemExit("workload Secret requirements did not use the expected-binding namespace") if any( - publication_keys[name] != {"tls.crt", "tls.key", "ca.crt"} - for name in expected_publication_names + publication_keys[name] != module.GRPC_WORKLOAD_LEAF_SECRET_KEYS + for name in expected_workload_secret_names ) or publication_keys[module.PUBLICATION_GRPC_TRUST_SECRET_NAME] != {"ca.crt"}: raise SystemExit( - "source publication Secret requirements omitted certificate-manager CA material" + "source workload Secret requirements omitted certificate-manager CA material" ) def publication_static_issues(documents): @@ -9935,6 +10029,106 @@ def expect_publication_static_failure(description, documents, expected_fragment= ) +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) +expect_publication_static_failure( + "a missing Social Groups workload identity", + missing_social_groups_documents, + "Expected exactly one rendered Deployment for gRPC workload social-groups-service", +) +wrong_social_groups_leaf_documents = copy.deepcopy(publication_documents) +wrong_social_groups_leaf_documents[social_groups_index]["spec"]["template"]["spec"]["volumes"][0][ + "secret" +]["secretName"] = "firemud-grpc-game-session-service" +expect_publication_static_failure( + "a reused Social Groups leaf Secret", + wrong_social_groups_leaf_documents, + "grpc-tls Secret must be firemud-grpc-social-groups-service", +) +missing_social_groups_trust_documents = copy.deepcopy(publication_documents) +missing_social_groups_trust_documents[social_groups_index]["spec"]["template"]["spec"][ + "volumes" +].pop() +expect_publication_static_failure( + "a missing Social Groups shared trust projection", + missing_social_groups_trust_documents, + "Expected exactly one grpc-trust volume", +) + + +for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: + workload_index = module.SHARED_TRUST_GRPC_WORKLOADS.index(workload) + wrong_leaf_documents = copy.deepcopy(publication_documents) + wrong_leaf_documents[workload_index]["spec"]["template"]["spec"]["volumes"][0][ + "secret" + ]["secretName"] = "wrong-workload-leaf" + expect_publication_static_failure( + f"a wrong {workload} leaf Secret reference", + wrong_leaf_documents, + f"grpc-tls Secret must be firemud-grpc-{workload}", + ) + + old_leaf_trust_documents = copy.deepcopy(publication_documents) + old_leaf_trust_spec = old_leaf_trust_documents[workload_index]["spec"]["template"][ + "spec" + ] + old_leaf_trust_spec["volumes"] = [ + volume for volume in old_leaf_trust_spec["volumes"] if volume["name"] != "grpc-trust" + ] + old_leaf_trust_spec["containers"][0]["volumeMounts"] = [ + mount + for mount in old_leaf_trust_spec["containers"][0]["volumeMounts"] + if mount["name"] != "grpc-trust" + ] + old_leaf_trust_spec["volumes"][0]["secret"].pop("items") + next( + entry + for entry in old_leaf_trust_spec["containers"][0]["env"] + if entry["name"] == "FIREMUD_GRPC_CA_CERT_PATH" + )["value"] = "/tls/ca.crt" + expect_publication_static_failure( + f"the obsolete {workload} leaf-CA-only trust layout", + old_leaf_trust_documents, + "Expected exactly one grpc-trust volume", + ) + + wrong_shared_trust_documents = copy.deepcopy(publication_documents) + wrong_shared_trust_spec = wrong_shared_trust_documents[workload_index]["spec"][ + "template" + ]["spec"] + wrong_shared_trust = next( + volume + for volume in wrong_shared_trust_spec["volumes"] + if volume["name"] == "grpc-trust" + ) + wrong_shared_trust["secret"]["secretName"] = f"firemud-grpc-{workload}" + expect_publication_static_failure( + f"a wrong {workload} shared trust Secret", + wrong_shared_trust_documents, + "requires the shared CA-only Secret firemud-grpc-tls", + ) + + for shared_private_key in ("client.key", "client.crt"): + private_shared_material_documents = copy.deepcopy(publication_documents) + private_shared_spec = private_shared_material_documents[workload_index]["spec"][ + "template" + ]["spec"] + private_shared_trust = next( + volume + for volume in private_shared_spec["volumes"] + if volume["name"] == "grpc-trust" + ) + private_shared_trust["secret"]["items"].append( + {"key": shared_private_key, "path": shared_private_key} + ) + expect_publication_static_failure( + f"a {workload} shared trust projection containing {shared_private_key}", + private_shared_material_documents, + "requires the shared CA-only Secret firemud-grpc-tls", + ) + + swapped_leaf_documents = copy.deepcopy(publication_documents) first_leaf = swapped_leaf_documents[0]["spec"]["template"]["spec"]["volumes"][0][ "secret" @@ -10171,8 +10365,8 @@ default_mode_publication_documents[0]["spec"]["template"]["spec"]["volumes"][0][ default_mode_requirements = module.publication_workload_secret_requirements( publication_expected, default_mode_publication_documents ) -if len(default_mode_requirements) != len(module.PUBLICATION_GRPC_WORKLOADS) + 1: - raise SystemExit("publication grpc-tls Secret defaultMode was not accepted") +if len(default_mode_requirements) != len(module.GRPC_WORKLOAD_SECRET_CONSUMERS) + 1: + raise SystemExit("workload grpc-tls Secret defaultMode was not accepted") for forbidden_secret_key in ("optional", "unexpected"): forbidden_secret_documents = copy.deepcopy(publication_documents) @@ -10305,7 +10499,7 @@ if not any( publication_expected, missing_workload_documents ) ): - raise SystemExit("missing publication workload did not fail closed") + raise SystemExit("missing gRPC workload did not fail closed") ambiguous_workload_documents = publication_documents + [ copy.deepcopy(publication_documents[0]) @@ -10376,7 +10570,7 @@ if not any( publication_expected, namespace_mismatch_documents ) ): - raise SystemExit("publication workload namespace mismatch did not fail closed") + raise SystemExit("gRPC workload namespace mismatch did not fail closed") publication_success_fixture = { name: keys for name, _, keys in publication_requirements @@ -10399,13 +10593,13 @@ with patch.object( if module.publication_workload_secret_issues( publication_expected, publication_documents ): - raise SystemExit("complete publication Secret fixture failed preflight") + raise SystemExit("complete eight-workload Secret fixture failed preflight") if {name for name, _, _ in queried_publication_secrets} != ( - expected_publication_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} + expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): - raise SystemExit("preflight did not query precisely the mounted publication Secrets") + raise SystemExit("preflight did not query precisely the mounted workload Secrets") if any(namespace != "firemud" for _, namespace, _ in queried_publication_secrets): - raise SystemExit("preflight queried a publication Secret in the wrong namespace") + raise SystemExit("preflight queried a workload Secret in the wrong namespace") missing_publication_name = publication_requirements[0][0] with patch.object( @@ -10459,6 +10653,58 @@ if len(missing_ca_issues) != 1 or "missing keys: ca.crt" not in missing_ca_issue f"publication Secret missing ca.crt did not fail closed: {missing_ca_issues}" ) +for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: + target_secret_name = f"firemud-grpc-{workload}" + with patch.object( + module, + "secret_keys_lookup_failure", + side_effect=lambda name, namespace, required, target=target_secret_name: ( + ( + f"Missing required Secret in cluster: {namespace}/{name}", + True, + False, + ) + if name == target + else (None, False, False) + ), + ): + missing_role_secret_issues = module.publication_workload_secret_issues( + publication_expected, publication_documents + ) + if ( + len(missing_role_secret_issues) != 1 + or target_secret_name not in missing_role_secret_issues[0] + or "Missing required Secret" not in missing_role_secret_issues[0] + ): + raise SystemExit( + f"missing {workload} leaf Secret did not fail closed: {missing_role_secret_issues}" + ) + + with patch.object( + module, + "secret_keys_lookup_failure", + side_effect=lambda name, namespace, required, target=target_secret_name: ( + ( + f"Required Secret {namespace}/{name} is missing keys: ca.crt", + True, + False, + ) + if name == target + else (None, False, False) + ), + ): + incomplete_role_secret_issues = module.publication_workload_secret_issues( + publication_expected, publication_documents + ) + if ( + len(incomplete_role_secret_issues) != 1 + or target_secret_name not in incomplete_role_secret_issues[0] + or "missing keys: ca.crt" not in incomplete_role_secret_issues[0] + ): + raise SystemExit( + f"incomplete {workload} leaf Secret did not fail closed: {incomplete_role_secret_issues}" + ) + namespace = "pr-42" release = "pr-42" node_port = 32007 diff --git a/dev-tools/tests/standalone-grpc-certificates-contract.sh b/dev-tools/tests/standalone-grpc-certificates-contract.sh index 86867d8882..233bf697fc 100644 --- a/dev-tools/tests/standalone-grpc-certificates-contract.sh +++ b/dev-tools/tests/standalone-grpc-certificates-contract.sh @@ -71,9 +71,12 @@ workloads = ( "entity-management-service", "game-logic-service", "automation-scripting-service", + "account-service", + "game-session-service", + "social-groups-service", ) if len(documents) != len(workloads): - raise SystemExit(f"expected five Certificate documents, got {len(documents)}") + raise SystemExit(f"expected eight 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": @@ -121,8 +124,8 @@ for workload, document in zip(workloads, documents, strict=True): PY actual_wait_count="$(grep -c ' wait ' "$STATE_DIR/calls")" - [[ "$actual_wait_count" -eq 5 ]] || { - echo "expected five Certificate readiness waits for $namespace, got $actual_wait_count" >&2 + [[ "$actual_wait_count" -eq 8 ]] || { + echo "expected eight 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 @@ -162,6 +165,9 @@ for workload in ( "entity-management-service", "game-logic-service", "automation-scripting-service", + "account-service", + "game-session-service", + "social-groups-service", ): 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 d9c4d56e14..b1c4ae7e2c 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -177,7 +177,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))$')", + "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))$')", ): require(certificate, needle, "Certificate boundary") status_rules = certificate_status["matchConstraints"]["resourceRules"] @@ -205,9 +205,44 @@ 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))$", + "^(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))$", "standalone Certificate validation", ) + for needle in ( + "object.metadata.name.endsWith('-grpc-account-service')", + "object.spec.secretName == 'firemud-grpc-account-service'", + "object.spec.issuerRef.name == 'firemud-ca-issuer'", + "object.spec.dnsNames == ['account-service', 'account-service.' + request.namespace, 'account-service.' + request.namespace + '.svc', 'account-service.' + request.namespace + '.svc.cluster.local']", + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/account-service']", + "object.metadata.name.endsWith('-grpc-game-session-service')", + "object.spec.secretName == 'firemud-grpc-game-session-service'", + "object.spec.issuerRef.name == 'firemud-ca-issuer'", + "object.spec.dnsNames == ['game-session-service', 'game-session-service.' + request.namespace, 'game-session-service.' + request.namespace + '.svc', 'game-session-service.' + request.namespace + '.svc.cluster.local']", + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-session-service']", + "object.metadata.name.endsWith('-grpc-social-groups-service')", + "object.spec.secretName == 'firemud-grpc-social-groups-service'", + "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']", + ): + require(certificate_validation, needle, "standalone workload identity") + normalized_certificate_validation = " ".join(certificate_validation.split()) + for workload in ("account-service", "game-session-service", "social-groups-service"): + expected_branch = ( + f"(object.metadata.name.endsWith('-grpc-{workload}') && " + f"object.spec.secretName == 'firemud-grpc-{workload}' && " + "object.spec.issuerRef.name == 'firemud-ca-issuer' && " + f"object.spec.dnsNames == ['{workload}', '{workload}.' + request.namespace, " + f"'{workload}.' + request.namespace + '.svc', " + f"'{workload}.' + request.namespace + '.svc.cluster.local'] && " + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{workload}'] && " + "object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])" + ) + require( + normalized_certificate_validation, + expected_branch, + f"standalone {workload} Certificate 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 ff11f7c488..98f8eb8404 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -198,7 +198,7 @@ def test_publication_grpc_consumers_reject_shared_client_identity_fallbacks(self lambda document: document["spec"]["template"]["spec"]["volumes"][ 0 ]["secret"].update({"secretName": "firemud-grpc-tls"}), - "unexpected grpc-tls source", + "distinct workload falls back to shared firemud-grpc-tls", ), ( "client certificate path", @@ -894,35 +894,64 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): { "name": "account-service", "env": [ + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": { + "fieldRef": {"fieldPath": "metadata.namespace"} + }, + }, { "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", - "value": "/tls/client.crt", + "value": "/tls/tls.crt", }, { "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", - "value": "/tls/client.key", + "value": "/tls/tls.key", }, { "name": "FIREMUD_GRPC_CA_CERT_PATH", - "value": "/tls/ca.crt", + "value": "/grpc-trust/ca.crt", }, ], "volumeMounts": [ {"name": "grpc-tls", "mountPath": "/tls", "readOnly": True}, + {"name": "grpc-trust", "mountPath": "/grpc-trust", "readOnly": True}, { "name": "jwt-signing-keys", "mountPath": "/var/run/secrets/firemud/jwt", "readOnly": True, }, + { + "name": "jwt-jwks", + "mountPath": "/var/run/secrets/firemud/jwks", + "readOnly": True, + }, ], } ], "volumes": [ - {"name": "grpc-tls", "secret": {"secretName": "firemud-grpc-tls"}}, + { + "name": "grpc-tls", + "secret": { + "secretName": "firemud-grpc-account-service", + "items": [ + {"key": "tls.crt", "path": "tls.crt"}, + {"key": "tls.key", "path": "tls.key"}, + ], + }, + }, + { + "name": "grpc-trust", + "secret": { + "secretName": "firemud-grpc-tls", + "items": [{"key": "ca.crt", "path": "ca.crt"}], + }, + }, { "name": "jwt-signing-keys", "secret": {"secretName": "jwt-signing-keys"}, }, + {"name": "jwt-jwks", "configMap": {"name": "jwt-jwks"}}, ], } document = { @@ -930,6 +959,21 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): "metadata": {"name": "account-service"}, "spec": {"template": {"spec": pod}}, } + with patch.object(self.validator, "SERVICE_IMAGES", {"account-service"}): + self.validator.validate_service_consumers( + [document], "pr-42", "standalone", "public" + ) + fallback = copy.deepcopy(document) + fallback["spec"]["template"]["spec"]["volumes"][0]["secret"][ + "secretName" + ] = "firemud-grpc-tls" + with self.assertRaisesRegex( + ValueError, + "Deployment/account-service distinct workload falls back to shared firemud-grpc-tls", + ): + self.validator.validate_service_consumers( + [fallback], "pr-42", "standalone", "public" + ) for field, malformed in ( ("volumeMounts", ["not-a-mapping"]), ("volumes", ["not-a-mapping"]), @@ -1839,21 +1883,26 @@ def _policy_documents(self, mode): for name, spec in self.validator.EXPECTED_INTERNAL_NETWORK_POLICY_SPECS.items() ] if mode == "hosted-controller": - documents.append( - self._policy_document( - "account-service-controller-ingress", - { - "podSelector": {"matchLabels": {"app": "account-service"}}, - "policyTypes": ["Ingress"], - "ingress": [ - { - "from": [controller_from], - "ports": [{"protocol": "TCP", "port": 6565}], - } - ], - }, + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + documents.append( + self._policy_document( + f"{workload}-controller-ingress", + { + "podSelector": {"matchLabels": {"app": workload}}, + "policyTypes": ["Ingress"], + "ingress": [ + { + "from": [controller_from], + "ports": [{"protocol": "TCP", "port": 6565}], + } + ], + }, + ) ) - ) documents.extend( [ self._policy_document( @@ -2022,6 +2071,40 @@ def test_mode_specific_policy_sets_and_rules_are_closed(self): with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): self.validator.validate_network_policies(missing_account, "hosted-controller") + missing_game_session = [ + document + for document in hosted + if document["metadata"]["name"] + != "game-session-service-controller-ingress" + ] + with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): + self.validator.validate_network_policies( + missing_game_session, "hosted-controller" + ) + + for field, value, message in ( + ( + "podSelector", + {"matchLabels": {"app": "account-service"}}, + "selects an unsafe workload", + ), + ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), + ("ingress", [], "has an unsafe exception"), + ): + with self.subTest(mode="hosted-controller", game_session_field=field): + malformed = copy.deepcopy(hosted) + policy = next( + document + for document in malformed + if document["metadata"]["name"] + == "game-session-service-controller-ingress" + ) + policy["spec"][field] = value + with self.assertRaisesRegex(ValueError, message): + self.validator.validate_network_policies( + malformed, "hosted-controller" + ) + for mode in ("standalone", "hosted-controller"): with self.subTest(mode=mode, case="missing gateway egress"): missing_gateway_egress = [ diff --git a/k8s/base/account-service.yaml b/k8s/base/account-service.yaml index 0acde4ba02..715a49e7cc 100644 --- a/k8s/base/account-service.yaml +++ b/k8s/base/account-service.yaml @@ -27,12 +27,16 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -42,6 +46,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -111,8 +118,19 @@ spec: readOnlyRootFilesystem: true volumes: - name: grpc-tls + secret: + secretName: firemud-grpc-account-service + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust secret: secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt - name: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/base/game-session-service.yaml b/k8s/base/game-session-service.yaml index b58a48d61a..22cc946d32 100644 --- a/k8s/base/game-session-service.yaml +++ b/k8s/base/game-session-service.yaml @@ -28,12 +28,16 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -43,6 +47,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -109,8 +116,19 @@ spec: readOnlyRootFilesystem: true volumes: - name: grpc-tls + secret: + secretName: firemud-grpc-game-session-service + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust secret: secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt - name: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/base/grpc-bootstrap.example.yaml b/k8s/base/grpc-bootstrap.example.yaml index 00a9aaa6ae..7bce1e8168 100644 --- a/k8s/base/grpc-bootstrap.example.yaml +++ b/k8s/base/grpc-bootstrap.example.yaml @@ -1,3 +1,8 @@ +# This example only provisions the shared transport/trust Secret. Account Service, Game Session, +# Social Groups, and the five publication workloads also require their separate cert-manager-issued +# leaf Secrets: firemud-grpc-account-service, firemud-grpc-game-session-service, +# firemud-grpc-social-groups-service, and one firemud-grpc- Secret for each publication +# workload. The shared Secret alone is not sufficient to start them. apiVersion: cert-manager.io/v1 kind: Certificate metadata: diff --git a/k8s/base/social-groups-service.yaml b/k8s/base/social-groups-service.yaml index b2a1763a3a..a22114d4b3 100644 --- a/k8s/base/social-groups-service.yaml +++ b/k8s/base/social-groups-service.yaml @@ -24,12 +24,16 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -39,6 +43,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -105,8 +112,19 @@ spec: readOnlyRootFilesystem: true volumes: - name: grpc-tls + secret: + secretName: firemud-grpc-social-groups-service + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust secret: secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt - name: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/helm/README.md b/k8s/helm/README.md index 2225957dc9..ffd8aeb535 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 with publication workloads enabled, the trusted environment setup must provision these namespace-scoped leaf Secrets: `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`. It must also provision the shared `firemud-grpc-tls` trust bundle. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for the five leaves; hosted-controller setup must wait for all five projections. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.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 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. 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 9d387b1bae..db8901e051 100644 --- a/k8s/helm/firemud/templates/_helpers.tpl +++ b/k8s/helm/firemud/templates/_helpers.tpl @@ -32,7 +32,7 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} {{- end -}} {{- define "firemud.grpcWorkloadNames" -}} -{{- list "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} +{{- list "account-service" "game-session-service" "social-groups-service" "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} {{- end -}} {{- define "firemud.grpcSecretName" -}} diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index f40e18b14e..f5de2c3d8d 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -121,17 +121,18 @@ spec: - protocol: TCP port: 9000 {{- if eq $certificateIdentityMode "hosted-controller" }} +{{- range $workload := list "account-service" "game-session-service" "social-groups-service" }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: - name: account-service-controller-ingress + name: {{ $workload }}-controller-ingress labels: -{{ include "firemud.commonLabels" . | indent 4 }} +{{ include "firemud.commonLabels" $ | indent 4 }} spec: podSelector: matchLabels: - app: account-service + app: {{ $workload }} policyTypes: - Ingress ingress: @@ -147,6 +148,7 @@ spec: - protocol: TCP port: 6565 {{- end }} +{{- end }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index a494f3da15..8df1914c3a 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 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 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 `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 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 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). ## Resource and status contract @@ -34,11 +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 ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and gRPC revision, source-generation, 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, every consumer has 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 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. 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, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, 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 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 also performs a mutual-TLS handshake to the fixed Account gRPC Service with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and current leaf fingerprint; rollout counters alone cannot make the identity Ready. 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. +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. @@ -52,7 +52,7 @@ Kubernetes RBAC cannot constrain `create`, `escalate`, or `bind` with `resourceN The NetworkPolicy is fail-closed for controller egress. Its raw manifest contains required address markers, and the trusted bootstrap replaces them with validated `/32` IPv4 CIDRs in a private render. `--api-service-ipv4`, `--api-endpoint-ipv4`, and `--public-probe-ipv4` are required together for `observe` or `active` mode; a paused bootstrap without them substitutes `127.0.0.1/32` for all three destinations so the break-glass pause cannot reopen broad egress. The bootstrap reads back the `kubernetes.default` Service ClusterIP and the single observed API endpoint on TCP/6443 before any cluster write, and fails closed unless the fixed `dev.preview.firedevops.net` lookup returns exactly one matching IPv4 A record. -The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account TCP/6565 rule remain unchanged. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. +The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account, Game Session, and Social Groups TCP/6565 selectors remain exact. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. The checked-in Deployment contains fail-closed image and activation markers. `bootstrap-hosted-identity-controller.sh` accepts only the approved image repository with a full SHA-256 digest and an explicit `paused`, `observe`, or `active` mode. Before invoking `kubectl`, it uses GitHub CLI attestation verification to require default SLSA provenance from this repository's `runtime-images.yml` workflow on exactly `develop` or `main` and rejects self-hosted-runner provenance. The trusted operator context therefore requires Python 3 with PyYAML, `gh` authenticated for GitHub API and private-repository attestation reads, read authentication for the private GHCR image, and network access to GitHub API, GHCR, and the Sigstore trust services used by GitHub attestations. After verification, bootstrap substitutes the image, gRPC trust-anchor fingerprint, and mode in a private render. For every mode, it validates the fixed `firemud-system/firemud-grpc-ca` certificate, key, and configured fingerprint before its first cluster write. It then applies and reads back the fail-closed namespace guard and its `Deny` binding before applying the namespace-lifecycle ClusterRoleBinding, followed by server-side apply without force-conflict takeover for the complete install. Its default is `paused`; Active bootstrap retains the later gate that verifies every required validating admission policy and binding before the controller is permitted to reconcile. diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index b10d5e6d09..8f4b0d28b5 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -135,8 +135,8 @@ spec: variables: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - - name: publicationServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)'" + - 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)'" 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' && - (request.name == 'firemud-grpc-tls' || - request.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))$') || - request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)$') || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-social-groups-service' || + request.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))$') || + request.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)$') || request.name == 'firemud-grpc-tls-previous' || - request.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))-previous$'))) || + request.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$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || - object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-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))$') || + (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-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))-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$'))))) validations: # Namespace deletion also deletes the exact retained material. Allow # only the built-in kube-system namespace controller, DELETE, managed @@ -184,9 +184,9 @@ spec: (request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$')) && - request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-' + variables.publicationServiceRegexGroup + '|firemud-grpc-' + variables.publicationServiceRegexGroup + '-previous|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')(-previous)?)$') && + request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '|firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '-previous|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')(-previous)?)$') && (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-tls-previous' || - request.name.matches('^firemud-grpc-' + variables.publicationServiceRegexGroup + '(-previous)?$') || + request.name.matches('^firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '(-previous)?$') || request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') ? @@ -195,7 +195,7 @@ spec: (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && ((request.operation == 'DELETE' && - request.name.matches('^firemud-grpc-' + variables.publicationServiceRegexGroup + '$')) || + request.name.matches('^firemud-grpc-' + variables.grpcWorkloadServiceRegexGroup + '$')) || (request.operation in ['CREATE', 'UPDATE'] && has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && @@ -204,11 +204,14 @@ spec: (object.metadata.name == 'firemud-grpc-world-management-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-world-management-service') || (object.metadata.name == 'firemud-grpc-entity-management-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-entity-management-service') || (object.metadata.name == 'firemud-grpc-game-logic-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-game-logic-service') || - (object.metadata.name == 'firemud-grpc-automation-scripting-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-automation-scripting-service'))))) || + (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'))))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && ((request.operation == 'DELETE' && (request.name == 'firemud-grpc-tls' || - (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')$') && + (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') ? @@ -216,7 +219,7 @@ spec: request.namespace) + '-')) || ((request.namespace == 'dev-identity' || request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$')) && (request.name == 'firemud-grpc-tls-previous' || - (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')-previous$') && + (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')-previous$') && request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') ? @@ -225,10 +228,10 @@ 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'] || 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'] || 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.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')$') && + (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('^(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' : request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') ? @@ -236,7 +239,7 @@ spec: request.namespace) + '-')) || ((request.namespace == 'dev-identity' || request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$')) && (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-' + variables.publicationServiceRegexGroup + ')-previous$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')-previous$') && object.metadata.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') ? @@ -255,7 +258,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'] || 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'] || 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' && @@ -270,8 +273,11 @@ spec: (object.metadata.name == 'dev-telnet-tls' && object.metadata.labels['firemud.dev/role'] == 'telnet') || (object.metadata.name == 'dev-gateway-internal-ws' && object.metadata.labels['firemud.dev/role'] == 'gateway-internal-ws') || (object.metadata.name == 'dev-tcp-proxy-bridge' && object.metadata.labels['firemud.dev/role'] == 'tcp-proxy-bridge') || - (object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && - object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)))) || + ((object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && + 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'))) || (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' && @@ -282,8 +288,11 @@ spec: object.metadata.labels['firemud.dev/role'] == 'gateway-internal-ws') || (object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-tcp-proxy-bridge' && object.metadata.labels['firemud.dev/role'] == 'tcp-proxy-bridge') || - (object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && - 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'].startsWith('grpc-publication-') && + 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'))))))) message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret reason: Forbidden - expression: >- @@ -312,8 +321,8 @@ spec: variables: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - - name: publicationServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)'" + - 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)'" matchConstraints: matchPolicy: Equivalent resourceRules: @@ -339,12 +348,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' && - request.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))$') && + request.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))$') && request.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))$') && + 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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) @@ -361,7 +370,7 @@ spec: request.operation == 'DELETE' && (request.namespace == 'dev-identity' || request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$')) && (request.name == 'firemud-grpc-tls' || - (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')$') && + (request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && request.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) || @@ -369,7 +378,7 @@ spec: request.subResource == '' && (request.namespace == 'dev-identity' || request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$')) && ((request.operation == 'DELETE' && - (request.name.matches('^((dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + '))$') && + (request.name.matches('^((dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + '))$') && request.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-'))) || @@ -377,8 +386,8 @@ 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'] || 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.publicationServiceRegexGroup + ')$') && + (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.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' : request.namespace.substring(0, request.namespace.size() - 9)) + '-') && @@ -392,7 +401,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'] || 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'] || 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' && @@ -418,15 +427,29 @@ spec: object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/tcp-proxy-service'] && object.spec.usages == ['digital signature', 'key encipherment', 'client auth'])) && (!object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') || - (object.metadata.name == (((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) && - object.spec.secretName == object.metadata.name && + (object.spec.secretName == object.metadata.name && object.spec.dnsNames == [object.metadata.labels['firemud.dev/role'].substring(17), object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((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/' + object.metadata.labels['firemud.dev/role'].substring(17)] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-account-service' || + (object.spec.secretName == object.metadata.name && + object.spec.dnsNames == ['account-service', 'account-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'account-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'account-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/account-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-game-session-service' || + (object.spec.secretName == object.metadata.name && + object.spec.dnsNames == ['game-session-service', 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'game-session-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/game-session-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-social-groups-service' || + (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']))))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.subResource == 'status' && request.operation == 'UPDATE' && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.publicationServiceRegexGroup + ')$') && + 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' : request.namespace.substring(0, request.namespace.size() - 9)) + '-') && @@ -538,7 +561,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')] && + 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.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && @@ -548,12 +571,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')] && + 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.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')] && + 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.verbs == ['update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && @@ -566,7 +589,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'] && + 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.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 cabecb34d2..f1a0a7e594 100644 --- a/k8s/hosted-identity-controller/crd.yaml +++ b/k8s/hosted-identity-controller/crd.yaml @@ -203,6 +203,9 @@ spec: gatewayInternalWs: *consumer_status_schema tcpProxyBridge: *consumer_status_schema grpc: *consumer_status_schema + grpcAccountService: *consumer_status_schema + grpcGameSessionService: *consumer_status_schema + grpcSocialGroupsService: *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/hosted-identity-controller/networkpolicy.yaml b/k8s/hosted-identity-controller/networkpolicy.yaml index 1b2d40475a..747873978b 100644 --- a/k8s/hosted-identity-controller/networkpolicy.yaml +++ b/k8s/hosted-identity-controller/networkpolicy.yaml @@ -148,9 +148,10 @@ spec: ports: - protocol: TCP port: 2323 - # Ready additionally requires an mTLS handshake to the fixed Account gRPC - # Service using the current projected leaf. Runtime Namespace labels are - # externally owned and validated before the controller reaches this probe. + # Ready additionally requires mTLS handshakes to the fixed Account, Game + # Session, and Social Groups gRPC Services using their current projected + # leaves. Runtime Namespace labels are externally owned and validated + # before this probe. - to: - namespaceSelector: matchLabels: @@ -164,6 +165,30 @@ spec: podSelector: matchLabels: app: account-service + - namespaceSelector: + matchLabels: + firemud.dev/preview: "true" + podSelector: + matchLabels: + app: game-session-service + - namespaceSelector: + matchLabels: + firemud.dev/dev-demo: "true" + podSelector: + matchLabels: + app: game-session-service + - namespaceSelector: + matchLabels: + firemud.dev/preview: "true" + podSelector: + matchLabels: + app: social-groups-service + - namespaceSelector: + matchLabels: + firemud.dev/dev-demo: "true" + podSelector: + matchLabels: + app: social-groups-service ports: - protocol: TCP port: 6565 diff --git a/k8s/trust-bootstrap/README.md b/k8s/trust-bootstrap/README.md index 887dc54f53..f55bf45103 100644 --- a/k8s/trust-bootstrap/README.md +++ b/k8s/trust-bootstrap/README.md @@ -10,7 +10,7 @@ This is a prerequisite for the private Gateway–TCP Proxy bridge in #2713. It m 4. Prepare the separate recovery-only GitHub Environment `trusted-preview-ca-recovery`. It is restricted to `develop` and is never selected by a PR-controlled or routine deployment job. Provision its dedicated recovery kubeconfig, `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret, and non-secret fingerprint/context variables. Test the recovery script's bundle validation, exact two-Secret reconstruction, refusal on a missing admission binding or surviving legacy credential, and the trusted `verify` workflow. Before the canonical CA exists, use disposable test material for this procedure; no test key may be installed as `firemud-grpc-ca` in the shared cluster. 5. Only after steps 1–4 have live evidence, generate a new preview-only RSA-4096 CA in a private, ephemeral operator directory. Use an unencrypted PKCS8 private key, critical `BasicConstraints CA:TRUE,pathlen:0`, critical `KeyUsage keyCertSign`, SHA-256, and 730-day validity. Do not use a cert-manager self-signed issuer to create the root. Compute the lowercase SHA-256 fingerprint of the DER certificate. Pipe `recover-firemud-ca.py pack` directly to `gh secret set FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE -e trusted-preview-ca-recovery` without printing or retaining the bundle; set the fingerprint as a protected Environment variable. The GitHub Environment secret is the encrypted out-of-cluster recovery copy. Verify that copy through the trusted workflow before removing the ephemeral operator files. Do not put the key, bundle, or kubeconfig in a PR, Actions artifact, log, issue, chat, user PC, or password manager. 6. Run the reviewed recovery workflow's `restore` operation on `develop`. It accepts only the dedicated recovery ServiceAccount, the explicitly selected Kubernetes context, all eight live fail-closed admission bindings, and a revoked legacy ServiceAccount/ClusterRoleBinding. It writes only `firemud-system/firemud-grpc-ca` (`Opaque`, `ca.crt`/`ca.key`) and `cert-manager/firemud-grpc-ca` (`kubernetes.io/tls`, `tls.crt`/`tls.key`), then compares exact bytes through private readback. The copy is never printed. Install the fixed `firemud-ca-issuer` only after this recovery and readback pass. -7. With the controller still inactive, request the fixed standalone internal Gateway and TCP Proxy Certificates through the scoped writer, then request the five standalone per-workload gRPC Certificates for `dev` and a disposable `pr-N` namespace through that same writer. Observe `Ready`, key-complete output Secrets, and served transport identities/chains. The runtime workflow consumes only the projected leaf keys and public `ca.crt`; after validating every gRPC leaf it deletes the legacy runtime `firemud-grpc-ca` signing-key Secret and old static leaf-source Secrets. Repeat unauthorized direct CertificateRequest and Certificate tests after the issuer becomes Ready; an admission-only dry-run before issuance is not proof that unauthorized signing cannot occur. Retain only non-secret evidence. Controller bootstrap and the #2713 private-bridge rollout are later gates. The standalone preview/dev-demo gRPC paths fail closed until this issuer bootstrap and live denial proof are complete. +7. With the controller still inactive, request the fixed standalone internal Gateway and TCP Proxy Certificates through the scoped writer, then request the eight standalone per-workload gRPC Certificates (five publication workloads, Account, Game Session, and Social Groups) for `dev` and a disposable `pr-N` namespace through that same writer. Observe `Ready`, key-complete output Secrets, and served transport identities/chains. The runtime workflow consumes only the projected leaf keys and public `ca.crt`; after validating every gRPC leaf it deletes the legacy runtime `firemud-grpc-ca` signing-key Secret and old static leaf-source Secrets. Repeat unauthorized direct CertificateRequest and Certificate tests after the issuer becomes Ready; an admission-only dry-run before issuance is not proof that unauthorized signing cannot occur. Retain only non-secret evidence. Controller bootstrap and the #2713 private-bridge rollout are later gates. The standalone preview/dev-demo gRPC paths fail closed until this issuer bootstrap and live denial proof are complete. ## Recovery copy and rotation diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index 3488c2e0d5..c0f954dabf 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))$'))) + 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))$'))) 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))$'))) + 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))$'))) 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)$') && + (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)$') && 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)$') && + (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)$') && 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)$') && + (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)$') && 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)$') && + (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)$') && 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$')) && - request.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))$')) || + request.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))$')) || (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$')) && - request.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))$')) || + request.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))$')) || (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))$') && + 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.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)$')) || + 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.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -252,10 +252,28 @@ spec: object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.dnsNames == ['automation-scripting-service', 'automation-scripting-service.' + request.namespace, 'automation-scripting-service.' + request.namespace + '.svc', 'automation-scripting-service.' + request.namespace + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/automation-scripting-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-account-service') && + object.spec.secretName == 'firemud-grpc-account-service' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + object.spec.dnsNames == ['account-service', 'account-service.' + request.namespace, 'account-service.' + request.namespace + '.svc', 'account-service.' + request.namespace + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/account-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-game-session-service') && + object.spec.secretName == 'firemud-grpc-game-session-service' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + object.spec.dnsNames == ['game-session-service', 'game-session-service.' + request.namespace, 'game-session-service.' + request.namespace + '.svc', 'game-session-service.' + request.namespace + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-session-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-social-groups-service') && + object.spec.secretName == 'firemud-grpc-social-groups-service' && + 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']))) || (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))$') && + 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))$') && has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.issuerRef.kind == 'ClusterIssuer' && 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 a8f242b2eb..c2775dd835 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 @@ -63,6 +63,12 @@ public final class HostedIdentityContract { public static final String TCP_PROXY_BRIDGE_ROLE = "tcp-proxy-bridge"; public static final String GRPC_ROLE = "grpc"; public static final String GRPC_PUBLICATION_ROLE_PREFIX = "grpc-publication-"; + public static final String GRPC_ACCOUNT_WORKLOAD = "account-service"; + public static final String GRPC_ACCOUNT_ROLE = "grpc-account-service"; + public static final String GRPC_GAME_SESSION_WORKLOAD = "game-session-service"; + 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 List GRPC_PUBLICATION_WORKLOADS = List.of( "game-design-service", @@ -97,6 +103,13 @@ public static String grpcPublicationRole(String workload) { return GRPC_PUBLICATION_ROLE_PREFIX + workload; } + public static boolean isGrpcWorkloadIdentityRole(String role) { + return GRPC_ACCOUNT_ROLE.equals(role) + || GRPC_GAME_SESSION_ROLE.equals(role) + || GRPC_SOCIAL_GROUPS_ROLE.equals(role) + || isGrpcPublicationRole(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 486402e12b..7ca52f52a8 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 @@ -189,11 +189,60 @@ private RoleMaterial grpcPublication( EnvironmentIdentityPlan plan, String workload, MaterializationBatch batch) { - String role = HostedIdentityContract.grpcPublicationRole(workload); + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.grpcPublicationRole(workload), + workload, + plan.grpcPublicationCertificateName(workload), + batch); + } + + private RoleMaterial grpcAccount( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + plan.grpcAccountCertificateName(), + batch); + } + + private RoleMaterial grpcGameSession( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + plan.grpcGameSessionCertificateName(), + batch); + } + + private RoleMaterial grpcSocialGroups( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + plan.grpcSocialGroupsCertificateName(), + batch); + } + + private RoleMaterial grpcWorkloadIdentity( + KubernetesClient client, + EnvironmentIdentityPlan plan, + String role, + String workload, + String certificateName, + MaterializationBatch batch) { + String sourceSecretName = plan.sourceSecretName(role); RoleExpectation expectation = new RoleExpectation( - plan.grpcPublicationDnsNames(workload), - List.of(plan.grpcPublicationUriSan(workload)), + plan.grpcWorkloadIdentityDnsNames(workload), + List.of(plan.grpcWorkloadIdentityUriSan(workload)), true, true, "kubernetes.io/tls", @@ -202,8 +251,14 @@ private RoleMaterial grpcPublication( client, plan, role, - certificateFactory.grpcPublication(plan, workload, properties.getGrpcRenewBefore()), - plan.sourceSecretName(role), + certificateFactory.grpcWorkloadIdentity( + plan, + role, + workload, + certificateName, + sourceSecretName, + properties.getGrpcRenewBefore()), + sourceSecretName, expectation, batch); } @@ -342,6 +397,15 @@ private RotationSnapshot rotationSnapshot(KubernetesClient client, EnvironmentId String role = HostedIdentityContract.grpcPublicationRole(workload); observations.put(role, rotationObservation(client, plan, role)); } + observations.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + observations.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + observations.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); String selectedRole = selectSerializedRole( observations.values().stream().map(RotationObservation::state).toList()); @@ -534,7 +598,7 @@ private SecretMaterialValidator.MaterialSummary validateAcceptedMaterial( HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE.equals(role) || HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE.equals(role) || HostedIdentityContract.GRPC_ROLE.equals(role) - || HostedIdentityContract.isGrpcPublicationRole(role); + || HostedIdentityContract.isGrpcWorkloadIdentityRole(role); Secret validationSecret = accepted; String expectedType = current.expectedType(); String expectedTrustAnchor = current.trustAnchor(); @@ -709,8 +773,8 @@ private static String certificateName(EnvironmentIdentityPlan plan, String role) plan.gatewayInternalWsCertificateName(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.tcpProxyBridgeCertificateName(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - yield plan.grpcPublicationCertificateNames().get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + yield plan.grpcWorkloadIdentityCertificateNames().get(role); } throw new IllegalArgumentException("unsupported cert-manager identity role: " + role); } @@ -725,7 +789,7 @@ private static String issuerName(EnvironmentIdentityPlan plan, String role) { HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.grpcIssuer(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { yield plan.grpcIssuer(); } throw new IllegalArgumentException("unsupported cert-manager identity role: " + role); @@ -1217,6 +1281,18 @@ public RoleMaterial grpcPublication(String workload) { return CertificateMaterialService.this.grpcPublication(client, plan, workload, this); } + public RoleMaterial grpcAccount() { + return CertificateMaterialService.this.grpcAccount(client, plan, this); + } + + public RoleMaterial grpcGameSession() { + return CertificateMaterialService.this.grpcGameSession(client, plan, this); + } + + public RoleMaterial grpcSocialGroups() { + return CertificateMaterialService.this.grpcSocialGroups(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 54763c059d..2bd9d9f1c7 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 @@ -79,14 +79,67 @@ public GenericKubernetesResource tcpProxyBridge( /** Builds one retained client/server identity for a protected publication workload. */ public GenericKubernetesResource grpcPublication( EnvironmentIdentityPlan plan, String workload, Duration renewBefore) { - return certificate( + return grpcWorkloadIdentity( plan, HostedIdentityContract.grpcPublicationRole(workload), + workload, plan.grpcPublicationCertificateName(workload), plan.grpcPublicationSourceSecretName(workload), + renewBefore); + } + + /** Builds the retained Account workload identity used by protected audit ingress. */ + public GenericKubernetesResource grpcAccount(EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + plan.grpcAccountCertificateName(), + plan.grpcAccountSourceSecretName(), + renewBefore); + } + + /** Builds the retained Game Session workload identity used for Account JOIN calls. */ + public GenericKubernetesResource grpcGameSession( + EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + plan.grpcGameSessionCertificateName(), + plan.grpcGameSessionSourceSecretName(), + renewBefore); + } + + /** + * Builds the retained Social Groups workload identity used by protected profile/presence calls. + */ + public GenericKubernetesResource grpcSocialGroups( + EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + plan.grpcSocialGroupsCertificateName(), + plan.grpcSocialGroupsSourceSecretName(), + renewBefore); + } + + GenericKubernetesResource grpcWorkloadIdentity( + EnvironmentIdentityPlan plan, + String role, + String workload, + String certificateName, + String secretName, + Duration renewBefore) { + return certificate( + plan, + role, + certificateName, + secretName, plan.grpcIssuer(), - plan.grpcPublicationDnsNames(workload), - List.of(plan.grpcPublicationUriSan(workload)), + plan.grpcWorkloadIdentityDnsNames(workload), + List.of(plan.grpcWorkloadIdentityUriSan(workload)), List.of("digital signature", "key encipherment", "server auth", "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 94f14640d9..decd481f6b 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 @@ -7,6 +7,7 @@ import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.function.UnaryOperator; @@ -44,7 +45,7 @@ public RolloutResult sync( String telnetRevision, String gatewayInternalWsRevision, String grpcRevision, - Map grpcPublicationRevisions, + Map grpcWorkloadIdentityRevisions, Runnable runtimeProfileFence) { if (runtimeProfileFence == null) { throw new IllegalArgumentException("runtime profile guard is required"); @@ -58,10 +59,10 @@ public RolloutResult sync( if (grpcRevision == null) { throw new IllegalArgumentException("gRPC revision is required"); } - if (grpcPublicationRevisions == null) { - throw new IllegalArgumentException("gRPC publication revisions are required"); + if (grpcWorkloadIdentityRevisions == null) { + throw new IllegalArgumentException("gRPC workload identity revisions are required"); } - if (!grpcPublicationRevisions.isEmpty()) { + if (!grpcWorkloadIdentityRevisions.isEmpty()) { for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { if (plan.grpcConsumers().contains(workload)) { throw new IllegalArgumentException( @@ -85,10 +86,11 @@ public RolloutResult sync( .computeIfAbsent(consumer, ignored -> new LinkedHashMap<>()) .put(HostedIdentityContract.GRPC_REVISION_ANNOTATION, grpcRevision); } - if (!grpcPublicationRevisions.isEmpty()) { + if (!grpcWorkloadIdentityRevisions.isEmpty()) { + // This combined leaf and shared-trust revision supersedes the plain trust revision above. for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); - String revision = grpcPublicationRevisions.get(role); + String revision = grpcWorkloadIdentityRevisions.get(role); if (revision == null) { throw new IllegalArgumentException("gRPC publication revision is required: " + workload); } @@ -96,7 +98,34 @@ public RolloutResult sync( .computeIfAbsent(workload, ignored -> new LinkedHashMap<>()) .put( HostedIdentityContract.GRPC_REVISION_ANNOTATION, - combinedGrpcPublicationRevision(grpcRevision, revision)); + combinedGrpcWorkloadRevision(grpcRevision, revision, "publication-leaf")); + } + for (RequiredGrpcWorkloadRevision workloadRevision : + List.of( + new RequiredGrpcWorkloadRevision( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + "account-leaf", + "Account gRPC workload identity revision is required"), + new RequiredGrpcWorkloadRevision( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + "game-session-leaf", + "Game Session gRPC workload identity revision is required"), + new RequiredGrpcWorkloadRevision( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + "social-groups-leaf", + "Social Groups gRPC workload identity revision is required"))) { + String revision = grpcWorkloadIdentityRevisions.get(workloadRevision.role()); + if (revision == null) { + throw new IllegalArgumentException(workloadRevision.missingRevisionMessage()); + } + revisionsByDeployment + .computeIfAbsent(workloadRevision.workload(), ignored -> new LinkedHashMap<>()) + .put( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + combinedGrpcWorkloadRevision(grpcRevision, revision, workloadRevision.leafKind())); } } Map readinessByDeployment = new LinkedHashMap<>(); @@ -111,30 +140,37 @@ public RolloutResult sync( readinessByDeployment.put(entry.getKey(), ready); } boolean telnetReady = readinessByDeployment.getOrDefault(TCP_PROXY_DEPLOYMENT, false); - var grpcConsumers = plan.grpcConsumers().stream(); - if (!grpcPublicationRevisions.isEmpty()) { - grpcConsumers = - java.util.stream.Stream.concat( - grpcConsumers, HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream()); + var requiredGrpcConsumers = new LinkedHashSet<>(plan.grpcConsumers()); + if (!grpcWorkloadIdentityRevisions.isEmpty()) { + requiredGrpcConsumers.addAll(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); + requiredGrpcConsumers.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + requiredGrpcConsumers.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + requiredGrpcConsumers.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); } boolean grpcReady = - grpcConsumers.allMatch(consumer -> readinessByDeployment.getOrDefault(consumer, false)); + requiredGrpcConsumers.stream() + .allMatch(consumer -> readinessByDeployment.getOrDefault(consumer, false)); return new RolloutResult(telnetReady && grpcReady, telnetReady, grpcReady); } - /** Encodes both inputs without delimiter ambiguity in the existing publication rollout value. */ - private static String combinedGrpcPublicationRevision( - String grpcRevision, String publicationRevision) { + /** Encodes shared trust and one workload leaf without delimiter ambiguity. */ + private static String combinedGrpcWorkloadRevision( + String grpcRevision, String leafRevision, String leafKind) { return "v1|shared-grpc|" + grpcRevision.length() + "|" + grpcRevision - + "|publication-leaf|" - + publicationRevision.length() + "|" - + publicationRevision; + + leafKind + + "|" + + leafRevision.length() + + "|" + + leafRevision; } + private record RequiredGrpcWorkloadRevision( + String role, String workload, String leafKind, String missingRevisionMessage) {} + /** * Terminates both bridge endpoints for the monotonic Retired identity-removal intent while * fencing every read/replace boundary with the current runtime identity. 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 6295cda4b8..f6da572281 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 @@ -178,6 +178,12 @@ public static List identitySecretNames(EnvironmentIdentityPlan plan) { names.add(plan.grpcPublicationSourceSecretName(workload)); names.add(plan.grpcPublicationSourceSecretName(workload) + "-previous"); } + names.add(plan.grpcAccountSourceSecretName()); + names.add(plan.grpcAccountSourceSecretName() + "-previous"); + names.add(plan.grpcGameSessionSourceSecretName()); + names.add(plan.grpcGameSessionSourceSecretName() + "-previous"); + names.add(plan.grpcSocialGroupsSourceSecretName()); + names.add(plan.grpcSocialGroupsSourceSecretName() + "-previous"); return List.copyOf(names); } @@ -216,6 +222,9 @@ static Role runtimeRole(EnvironmentIdentityPlan plan) { static List requiredDeploymentNames(EnvironmentIdentityPlan plan) { LinkedHashSet names = new LinkedHashSet<>(plan.grpcConsumers()); names.addAll(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); + names.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + names.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + names.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); names.addAll(DeploymentRolloutService.BRIDGE_DEPLOYMENTS); return List.copyOf(names); } @@ -232,6 +241,9 @@ public static List requiredCertificateNames(EnvironmentIdentityPlan plan HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() .map(plan::grpcPublicationCertificateName) .toList()); + names.add(plan.grpcAccountCertificateName()); + names.add(plan.grpcGameSessionCertificateName()); + names.add(plan.grpcSocialGroupsCertificateName()); return List.copyOf(names); } @@ -248,6 +260,9 @@ static List runtimeSecretNames(EnvironmentIdentityPlan plan) { HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() .map(plan::grpcPublicationSecretName) .toList()); + names.add(plan.grpcAccountSecretName()); + names.add(plan.grpcGameSessionSecretName()); + names.add(plan.grpcSocialGroupsSecretName()); 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 53aa4a0a31..3c2f761f80 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 @@ -4,6 +4,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import net.firedevops.firemud.hostedidentity.contract.HostedIdentityContract; public record EnvironmentIdentityPlan( @@ -29,24 +30,31 @@ public record EnvironmentIdentityPlan( String grpcIssuer, String caSecretName, List grpcConsumers, - Map grpcPublicationCertificateNames, - Map grpcPublicationSecretNames, - Map grpcPublicationSourceSecretNames) { + Map grpcWorkloadIdentityCertificateNames, + Map grpcWorkloadIdentitySecretNames, + Map grpcWorkloadIdentitySourceSecretNames) { public EnvironmentIdentityPlan { grpcConsumers = List.copyOf(grpcConsumers); - grpcPublicationCertificateNames = Map.copyOf(grpcPublicationCertificateNames); - grpcPublicationSecretNames = Map.copyOf(grpcPublicationSecretNames); - grpcPublicationSourceSecretNames = Map.copyOf(grpcPublicationSourceSecretNames); + grpcWorkloadIdentityCertificateNames = Map.copyOf(grpcWorkloadIdentityCertificateNames); + grpcWorkloadIdentitySecretNames = Map.copyOf(grpcWorkloadIdentitySecretNames); + grpcWorkloadIdentitySourceSecretNames = Map.copyOf(grpcWorkloadIdentitySourceSecretNames); - Set expectedGrpcPublicationRoles = - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .map(HostedIdentityContract::grpcPublicationRole) + Set expectedGrpcWorkloadIdentityRoles = + Stream.concat( + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() + .map(HostedIdentityContract::grpcPublicationRole), + Stream.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) .collect(Collectors.toUnmodifiableSet()); - if (!grpcPublicationCertificateNames.keySet().equals(expectedGrpcPublicationRoles) - || !grpcPublicationSecretNames.keySet().equals(expectedGrpcPublicationRoles) - || !grpcPublicationSourceSecretNames.keySet().equals(expectedGrpcPublicationRoles)) { + if (!grpcWorkloadIdentityCertificateNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) + || !grpcWorkloadIdentitySecretNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) + || !grpcWorkloadIdentitySourceSecretNames + .keySet() + .equals(expectedGrpcWorkloadIdentityRoles)) { throw new IllegalArgumentException( - "gRPC publication certificate, runtime Secret, and source Secret maps must contain exactly the supported roles"); + "gRPC workload-identity certificate, runtime Secret, and source Secret maps must contain exactly the supported roles"); } } @@ -58,8 +66,8 @@ public String secretName(String role) { case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> tcpProxyBridgeSecretName; case HostedIdentityContract.GRPC_ROLE -> grpcSecretName; default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - String secretName = grpcPublicationSecretNames.get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + String secretName = grpcWorkloadIdentitySecretNames.get(role); if (secretName != null) { yield secretName; } @@ -70,11 +78,11 @@ public String secretName(String role) { } public String sourceSecretName(String role) { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - String sourceSecretName = grpcPublicationSourceSecretNames.get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + String sourceSecretName = grpcWorkloadIdentitySourceSecretNames.get(role); if (sourceSecretName == null) { throw new IllegalArgumentException( - "missing source Secret for gRPC publication role: " + role); + "missing source Secret for gRPC workload identity role: " + role); } return sourceSecretName; } @@ -82,24 +90,70 @@ public String sourceSecretName(String role) { } public String grpcPublicationCertificateName(String workload) { - return grpcPublicationCertificateNames.get( + return grpcWorkloadIdentityCertificateNames.get( HostedIdentityContract.grpcPublicationRole(workload)); } public String grpcPublicationSecretName(String workload) { - return grpcPublicationSecretNames.get(HostedIdentityContract.grpcPublicationRole(workload)); + return grpcWorkloadIdentitySecretNames.get( + HostedIdentityContract.grpcPublicationRole(workload)); } public String grpcPublicationSourceSecretName(String workload) { - return grpcPublicationSourceSecretNames.get( + return grpcWorkloadIdentitySourceSecretNames.get( HostedIdentityContract.grpcPublicationRole(workload)); } + public String grpcAccountCertificateName() { + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcAccountSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcAccountSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcGameSessionCertificateName() { + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + public String grpcGameSessionSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + public String grpcGameSessionSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + public String grpcSocialGroupsCertificateName() { + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + + public String grpcSocialGroupsSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + + public String grpcSocialGroupsSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + public String grpcPublicationUriSan(String workload) { - return "spiffe://firemud/ns/" + runtimeNamespace + "/sa/" + workload; + return grpcWorkloadIdentityUriSan(workload); } public List grpcPublicationDnsNames(String workload) { + return grpcWorkloadIdentityDnsNames(workload); + } + + public String grpcWorkloadIdentityUriSan(String workload) { + return "spiffe://firemud/ns/" + runtimeNamespace + "/sa/" + workload; + } + + public List grpcWorkloadIdentityDnsNames(String workload) { return List.of( workload, workload + "." + runtimeNamespace, @@ -131,8 +185,8 @@ public EnvironmentIdentityPlan withGrpcConsumers(List consumers) { grpcIssuer, caSecretName, consumers, - grpcPublicationCertificateNames, - grpcPublicationSecretNames, - grpcPublicationSourceSecretNames); + grpcWorkloadIdentityCertificateNames, + grpcWorkloadIdentitySecretNames, + grpcWorkloadIdentitySourceSecretNames); } } 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 c87acdce4e..745e77d546 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 @@ -14,6 +14,9 @@ public class HostedEnvironmentIdentityStatus { private RoleStatus gatewayInternalWs; private RoleStatus tcpProxyBridge; private RoleStatus grpc; + private RoleStatus grpcAccountService; + private RoleStatus grpcGameSessionService; + private RoleStatus grpcSocialGroupsService; private Map grpcPublication; private RuntimeProfile profile; @@ -86,6 +89,30 @@ public void setGrpc(RoleStatus grpc) { this.grpc = copyRole(grpc); } + public RoleStatus getGrpcAccountService() { + return copyRole(grpcAccountService); + } + + public void setGrpcAccountService(RoleStatus grpcAccountService) { + this.grpcAccountService = copyRole(grpcAccountService); + } + + public RoleStatus getGrpcGameSessionService() { + return copyRole(grpcGameSessionService); + } + + public void setGrpcGameSessionService(RoleStatus grpcGameSessionService) { + this.grpcGameSessionService = copyRole(grpcGameSessionService); + } + + public RoleStatus getGrpcSocialGroupsService() { + return copyRole(grpcSocialGroupsService); + } + + public void setGrpcSocialGroupsService(RoleStatus grpcSocialGroupsService) { + this.grpcSocialGroupsService = copyRole(grpcSocialGroupsService); + } + 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 9e36158c92..a9fb3eb6e4 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 @@ -28,6 +28,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -79,6 +80,8 @@ static final class HandshakePolicyRejectedException extends IllegalStateExceptio private static final String BRIDGE_PROBE_CLIENT_IP = "127.0.0.1"; private static final SecureRandom WEBSOCKET_NONCE_SOURCE = new SecureRandom(); private static final String GRPC_PROBE_SERVICE = "account-service"; + private static final String GRPC_GAME_SESSION_PROBE_SERVICE = "game-session-service"; + private static final String GRPC_SOCIAL_GROUPS_PROBE_SERVICE = "social-groups-service"; private static final Logger LOGGER = LoggerFactory.getLogger(ServedEnvironmentProbe.class); private static final ThreadLocal CURRENT_ATTEMPT = new ThreadLocal<>(); private final HostedIdentityProperties properties; @@ -98,7 +101,9 @@ public ProbeResult probe( Secret tcpProxyBridgeMaterial, String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, - String expectedGrpcLeafSha256) { + String expectedGrpcLeafSha256, + String expectedGrpcGameSessionLeafSha256, + String expectedGrpcSocialGroupsLeafSha256) { return probe( plan, HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, @@ -108,7 +113,9 @@ public ProbeResult probe( tcpProxyBridgeMaterial, expectedGatewayInternalWsLeafSha256, grpcMaterial, - expectedGrpcLeafSha256); + expectedGrpcLeafSha256, + expectedGrpcGameSessionLeafSha256, + expectedGrpcSocialGroupsLeafSha256); } public ProbeResult probe( @@ -120,7 +127,9 @@ public ProbeResult probe( Secret tcpProxyBridgeMaterial, String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, - String expectedGrpcLeafSha256) { + String expectedGrpcLeafSha256, + String expectedGrpcGameSessionLeafSha256, + String expectedGrpcSocialGroupsLeafSha256) { return probe( plan, exposureMode, @@ -130,6 +139,8 @@ public ProbeResult probe( (hostname, port) -> bridge(hostname, port, tcpProxyBridgeMaterial, expectedGatewayInternalWsLeafSha256), (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcLeafSha256), + (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcGameSessionLeafSha256), + (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcSocialGroupsLeafSha256), TOTAL_PROBE_TIMEOUT); } @@ -148,6 +159,8 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, + grpcProbe, TOTAL_PROBE_TIMEOUT); } @@ -167,6 +180,8 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, + grpcProbe, timeout); } @@ -186,6 +201,98 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, + grpcProbe, + TOTAL_PROBE_TIMEOUT); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + Duration timeout) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcProbe, + grpcProbe, + timeout); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, + grpcProbe, + TOTAL_PROBE_TIMEOUT); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, + Duration timeout) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, + grpcProbe, + timeout); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, + EndpointProbe grpcSocialGroupsProbe) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, + grpcSocialGroupsProbe, TOTAL_PROBE_TIMEOUT); } @@ -197,6 +304,8 @@ ProbeResult probe( EndpointProbe telnetProbe, EndpointProbe bridgeProbe, EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, + EndpointProbe grpcSocialGroupsProbe, Duration timeout) { if (!HostedIdentityContract.PRIVATE_PREVIEW_EXPOSURE_MODE.equals(exposureMode) && !HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE.equals(exposureMode)) { @@ -221,7 +330,7 @@ ProbeResult probe( ProbeName.GRPC, () -> { try { - return grpcProbe.check(grpcHostname(plan), GRPC_PORT); + return grpcProbe.check(grpcHostname(plan, GRPC_PROBE_SERVICE), GRPC_PORT); } catch (IllegalArgumentException exception) { LOGGER.debug( "gRPC probe rejected material or configuration for runtime Namespace {}", @@ -230,6 +339,36 @@ ProbeResult probe( return new ProbeResult(false, "grpc-material-or-configuration-invalid"); } })); + probes.add( + startProbe( + ProbeName.GRPC_GAME_SESSION, + () -> { + try { + return grpcGameSessionProbe.check( + grpcHostname(plan, GRPC_GAME_SESSION_PROBE_SERVICE), GRPC_PORT); + } catch (IllegalArgumentException exception) { + LOGGER.debug( + "Game Session gRPC probe rejected material or configuration for runtime Namespace {}", + plan.runtimeNamespace(), + exception); + return new ProbeResult(false, "grpc-material-or-configuration-invalid"); + } + })); + probes.add( + startProbe( + ProbeName.GRPC_SOCIAL_GROUPS, + () -> { + try { + return grpcSocialGroupsProbe.check( + grpcHostname(plan, GRPC_SOCIAL_GROUPS_PROBE_SERVICE), GRPC_PORT); + } catch (IllegalArgumentException exception) { + LOGGER.debug( + "Social Groups gRPC probe rejected material or configuration for runtime Namespace {}", + plan.runtimeNamespace(), + exception); + return new ProbeResult(false, "grpc-material-or-configuration-invalid"); + } + })); long deadline = System.nanoTime() + timeout.toNanos(); try { List results = new ArrayList<>(probes.size()); @@ -297,7 +436,9 @@ private static void cancelOutstanding(List probes) { } static ProbeResult prefixedResult(ProbeName probeName, ProbeResult result) { - if (probeName == ProbeName.GRPC + if ((probeName == ProbeName.GRPC + || probeName == ProbeName.GRPC_GAME_SESSION + || probeName == ProbeName.GRPC_SOCIAL_GROUPS) && "grpc-material-or-configuration-invalid".equals(result.reason())) { return result; } @@ -400,11 +541,16 @@ interface InternalTlsSocketOpener { SSLSocket open() throws Exception; } - private static String grpcHostname(EnvironmentIdentityPlan plan) { - if (!plan.grpcConsumers().contains(GRPC_PROBE_SERVICE)) { + private static String grpcHostname(EnvironmentIdentityPlan plan, String service) { + if (!Set.of( + GRPC_PROBE_SERVICE, + GRPC_GAME_SESSION_PROBE_SERVICE, + GRPC_SOCIAL_GROUPS_PROBE_SERVICE) + .contains(service) + || !plan.grpcConsumers().contains(service)) { throw new IllegalArgumentException("fixed gRPC probe service is not a rollout consumer"); } - return GRPC_PROBE_SERVICE + "." + plan.runtimeNamespace() + ".svc.cluster.local"; + return service + "." + plan.runtimeNamespace() + ".svc.cluster.local"; } static SSLSocket openGrpcTlsSocket( @@ -890,7 +1036,9 @@ enum ProbeName { HTTPS("https"), TELNET("telnet"), BRIDGE("bridge"), - GRPC("grpc"); + GRPC("grpc"), + GRPC_GAME_SESSION("grpc-game-session"), + GRPC_SOCIAL_GROUPS("grpc-social-groups"); private final String label; 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 06538edad9..2eb238c017 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 @@ -166,6 +166,15 @@ public UpdateControl reconcile( materialRequests.add( new RoleMaterialRequest(role, () -> materialization.grpcPublication(workload))); } + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, materialization::grpcAccount)); + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, materialization::grpcGameSession)); + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, materialization::grpcSocialGroups)); List rolePipeline = new ArrayList<>(); for (RoleMaterialRequest request : materialRequests) { CertificateMaterialService.RoleMaterial material = request.material().get(); @@ -193,6 +202,12 @@ public UpdateControl reconcile( roleMaterials.material(HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE); CertificateMaterialService.RoleMaterial grpc = roleMaterials.material(HostedIdentityContract.GRPC_ROLE); + CertificateMaterialService.RoleMaterial grpcAccount = + roleMaterials.material(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + CertificateMaterialService.RoleMaterial grpcGameSession = + roleMaterials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + CertificateMaterialService.RoleMaterial grpcSocialGroups = + roleMaterials.material(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); validateDistinctIdentities( rolePipeline.stream() .map(RoleMaterialBinding::material) @@ -226,11 +241,20 @@ public UpdateControl reconcile( beforeRollout.profile(), roleMaterials); } - Map publicationRevisions = new LinkedHashMap<>(); + Map workloadIdentityRevisions = new LinkedHashMap<>(); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); - publicationRevisions.put(role, projections.get(role).revision()); + workloadIdentityRevisions.put(role, projections.get(role).revision()); } + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + projections.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE).revision()); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + projections.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE).revision()); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + projections.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE).revision()); DeploymentRolloutService.RolloutResult rollout = deploymentRolloutService.sync( client, @@ -238,7 +262,7 @@ public UpdateControl reconcile( projections.get(HostedIdentityContract.TELNET_ROLE).revision(), projections.get(HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE).revision(), projections.get(HostedIdentityContract.GRPC_ROLE).revision(), - publicationRevisions, + workloadIdentityRevisions, () -> assertRuntimeProfileCurrent(plan, runtimeProfile, "rollout mutation")); ServedEnvironmentProbe.ProbeResult probes; if (rollout.ready()) { @@ -258,7 +282,9 @@ public UpdateControl reconcile( bridgeMaterial, gatewayInternalWs.summary().certificateFingerprint(), grpc.source(), - grpc.summary().certificateFingerprint()); + grpcAccount.summary().certificateFingerprint(), + grpcGameSession.summary().certificateFingerprint(), + grpcSocialGroups.summary().certificateFingerprint()); } else { probes = new ServedEnvironmentProbe.ProbeResult(false, "rollout-pending"); } @@ -494,7 +520,7 @@ private static RoleMaterials of(CertificateMaterialService.RoleMaterial... mater } } default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { if (materialsByRole.putIfAbsent(role, material) != null) { throw new IllegalArgumentException("duplicate identity material role: " + role); } @@ -518,14 +544,18 @@ private CertificateMaterialService.RoleMaterial material(String role) { return materialsByRole.get(role); } - private boolean publicationEvidenceComplete() { + private boolean workloadIdentityEvidenceComplete() { return HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .map(HostedIdentityContract::grpcPublicationRole) - .allMatch( - role -> { - CertificateMaterialService.RoleMaterial material = materialsByRole.get(role); - return material != null && material.ready(); - }); + .map(HostedIdentityContract::grpcPublicationRole) + .allMatch(this::roleReady) + && roleReady(HostedIdentityContract.GRPC_ACCOUNT_ROLE) + && roleReady(HostedIdentityContract.GRPC_GAME_SESSION_ROLE) + && roleReady(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + + private boolean roleReady(String role) { + CertificateMaterialService.RoleMaterial material = materialsByRole.get(role); + return material != null && material.ready(); } } @@ -1022,12 +1052,12 @@ private UpdateControl status( boolean ready, RuntimeProfileService.RuntimeProfile profile, RoleMaterials materials) { - if (ready && !materials.publicationEvidenceComplete()) { + if (ready && !materials.workloadIdentityEvidenceComplete()) { ready = false; phase = HostedEnvironmentIdentityStatus.Phase.Verifying; - reason = "PublicationIdentityEvidenceIncomplete"; + reason = "WorkloadIdentityEvidenceIncomplete"; message = - "all five publication identity projections are required for readiness; this status does not authorize publication methods"; + "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"; } HostedEnvironmentIdentityStatus updatedStatus = statusService.status( @@ -1052,6 +1082,18 @@ private UpdateControl status( roleStatus( materials.material(HostedIdentityContract.GRPC_ROLE), previousRole(resource, HostedIdentityContract.GRPC_ROLE))); + updatedStatus.setGrpcAccountService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_ACCOUNT_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE))); + updatedStatus.setGrpcGameSessionService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE))); + updatedStatus.setGrpcSocialGroupsService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE))); updatedStatus.setGrpcPublication(publicationRoleStatus(resource, materials)); resource.setStatus(updatedStatus); return UpdateControl.patchStatus(resource).rescheduleAfter(properties.getReconcileInterval()); @@ -1113,6 +1155,11 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( resource.getStatus().getGatewayInternalWs(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> resource.getStatus().getTcpProxyBridge(); case HostedIdentityContract.GRPC_ROLE -> resource.getStatus().getGrpc(); + case HostedIdentityContract.GRPC_ACCOUNT_ROLE -> resource.getStatus().getGrpcAccountService(); + case HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> + resource.getStatus().getGrpcGameSessionService(); + case HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE -> + resource.getStatus().getGrpcSocialGroupsService(); 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 c026a27fe8..03ed3cd322 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 @@ -66,6 +66,24 @@ public EnvironmentIdentityPlan plan(String name) { publicationSourceSecrets.put(role, sourceName); publicationSecrets.put(role, "firemud-grpc-" + workload); } + for (Map.Entry workloadIdentity : + List.of( + Map.entry( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD), + Map.entry( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD), + Map.entry( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD))) { + String role = workloadIdentity.getKey(); + String workload = workloadIdentity.getValue(); + String certificateAndSourceName = materialPrefix + "-grpc-" + workload; + publicationCertificates.put(role, certificateAndSourceName); + publicationSourceSecrets.put(role, certificateAndSourceName); + publicationSecrets.put(role, "firemud-grpc-" + workload); + } return new EnvironmentIdentityPlan( name, properties.getControlNamespace(), 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 f10ba02980..39ae3f8dd2 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 @@ -454,7 +454,10 @@ void materializationBatchReusesOneRotationSelectionSnapshot() { plan.grpcPublicationSecretName("world-management-service"), plan.grpcPublicationSecretName("entity-management-service"), plan.grpcPublicationSecretName("game-logic-service"), - plan.grpcPublicationSecretName("automation-scripting-service")), + plan.grpcPublicationSecretName("automation-scripting-service"), + plan.grpcAccountSecretName(), + plan.grpcGameSessionSecretName(), + plan.grpcSocialGroupsSecretName()), java.util.Set.copyOf(read.getAllValues())); clearInvocations(runtimeSecrets); @@ -1949,6 +1952,65 @@ void grpcUsesTheAcceptedProjectionWithoutRereadingTheDeferredSource() { when(secretClient.identitySecrets().withName(sourceName)).thenReturn(sourceResource); when(sourceResource.get()).thenReturn(certManagerSource(plan, role, sourceName, data)); } + String accountRole = HostedIdentityContract.GRPC_ACCOUNT_ROLE; + String accountName = plan.grpcAccountSecretName(); + String accountSourceName = plan.grpcAccountSourceSecretName(); + String accountRevision = SecretProjectionService.revisionForRole(accountRole, data); + Resource accountProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(accountName)).thenReturn(accountProjectionResource); + when(accountProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + accountRole, + accountName, + data, + acceptedAnnotations(accountRevision, "1".repeat(64)))); + Resource accountSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(accountSourceName)) + .thenReturn(accountSourceResource); + when(accountSourceResource.get()) + .thenReturn(certManagerSource(plan, accountRole, accountSourceName, data)); + String gameSessionRole = HostedIdentityContract.GRPC_GAME_SESSION_ROLE; + String gameSessionName = plan.grpcGameSessionSecretName(); + String gameSessionSourceName = plan.grpcGameSessionSourceSecretName(); + String gameSessionRevision = SecretProjectionService.revisionForRole(gameSessionRole, data); + Resource gameSessionProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(gameSessionName)) + .thenReturn(gameSessionProjectionResource); + when(gameSessionProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + gameSessionRole, + gameSessionName, + data, + acceptedAnnotations(gameSessionRevision, "1".repeat(64)))); + Resource gameSessionSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(gameSessionSourceName)) + .thenReturn(gameSessionSourceResource); + when(gameSessionSourceResource.get()) + .thenReturn(certManagerSource(plan, gameSessionRole, gameSessionSourceName, data)); + String socialGroupsRole = HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE; + String socialGroupsName = plan.grpcSocialGroupsSecretName(); + String socialGroupsSourceName = plan.grpcSocialGroupsSourceSecretName(); + String socialGroupsRevision = SecretProjectionService.revisionForRole(socialGroupsRole, data); + Resource socialGroupsProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(socialGroupsName)) + .thenReturn(socialGroupsProjectionResource); + when(socialGroupsProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + socialGroupsRole, + socialGroupsName, + data, + acceptedAnnotations(socialGroupsRevision, "1".repeat(64)))); + Resource socialGroupsSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(socialGroupsSourceName)) + .thenReturn(socialGroupsSourceResource); + when(socialGroupsSourceResource.get()) + .thenReturn(certManagerSource(plan, socialGroupsRole, socialGroupsSourceName, 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 5c276f9442..9a3fed3895 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 @@ -135,6 +135,87 @@ void publicationCertificateUsesStableSourceNameAndBidirectionalWorkloadIdentity( certificateSpec, plan, HostedIdentityContract.grpcPublicationRole("game-design-service")); } + @Test + void accountCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcAccount(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-account-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-account-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/account-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "account-service", + "account-service.pr-42", + "account-service.pr-42.svc", + "account-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + @Test + void gameSessionCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcGameSession(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-game-session-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-game-session-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/game-session-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "game-session-service", + "game-session-service.pr-42", + "game-session-service.pr-42.svc", + "game-session-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + @Test + void socialGroupsCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcSocialGroups(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-social-groups-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-social-groups-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/social-groups-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "social-groups-service", + "social-groups-service.pr-42", + "social-groups-service.pr-42.svc", + "social-groups-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + @Test void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { var declaredMethods = @@ -146,10 +227,17 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { .filter(method -> java.lang.reflect.Modifier.isPublic(method.getModifiers())) .toList(); - assertEquals(5, publicMethods.size()); + assertEquals(8, publicMethods.size()); assertEquals( java.util.Set.of( - "ingress", "telnet", "gatewayInternalWs", "tcpProxyBridge", "grpcPublication"), + "ingress", + "telnet", + "gatewayInternalWs", + "tcpProxyBridge", + "grpcPublication", + "grpcAccount", + "grpcGameSession", + "grpcSocialGroups"), publicMethods.stream() .map(java.lang.reflect.Method::getName) .collect(java.util.stream.Collectors.toUnmodifiableSet())); 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 55c514f4c0..6a571ae977 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 @@ -56,8 +56,8 @@ void mixedRevisionEditPreservesCurrentRoleAndUpdatesOnlyStaleRole() { } @Test - void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllReady() { - EnvironmentIdentityPlan plan = planWithConsumers("account-service"); + void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady() { + EnvironmentIdentityPlan plan = planWithConsumers("account-service", "game-session-service"); Map publicationRevisions = new LinkedHashMap<>(); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); @@ -69,6 +69,8 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe plan, "tcp-proxy-service", "account-service", + "game-session-service", + "social-groups-service", "game-design-service", "world-management-service", "entity-management-service", @@ -80,12 +82,47 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe "tcp-proxy-service", Map.of(HostedIdentityContract.TELNET_REVISION_ANNOTATION, "telnet-current"), 3L)); + ArgumentCaptor accountReplacement = ArgumentCaptor.forClass(Deployment.class); + ArgumentCaptor gameSessionReplacement = ArgumentCaptor.forClass(Deployment.class); + ArgumentCaptor socialGroupsReplacement = ArgumentCaptor.forClass(Deployment.class); when(graph.resources().get("account-service").get()) .thenReturn( readyDeployment( "account-service", - Map.of(HostedIdentityContract.GRPC_REVISION_ANNOTATION, "grpc-current"), - 3L)); + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision("grpc-current", "account-old", "account-leaf")), + 3L)) + .thenAnswer(invocation -> accountReplacement.getValue()); + when(graph.resources().get("game-session-service").get()) + .thenReturn( + readyDeployment( + "game-session-service", + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision( + "grpc-current", "game-session-old", "game-session-leaf")), + 3L)) + .thenAnswer(invocation -> gameSessionReplacement.getValue()); + when(graph.resources().get("social-groups-service").get()) + .thenReturn( + readyDeployment( + "social-groups-service", + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision( + "grpc-current", "social-groups-old", "social-groups-leaf")), + 3L)) + .thenAnswer(invocation -> socialGroupsReplacement.getValue()); + ReplaceDeletable lockedAccount = mock(ReplaceDeletable.class); + when(graph.resources().get("account-service").lockResourceVersion("rv-3")) + .thenReturn(lockedAccount); + ReplaceDeletable lockedGameSession = mock(ReplaceDeletable.class); + when(graph.resources().get("game-session-service").lockResourceVersion("rv-3")) + .thenReturn(lockedGameSession); + ReplaceDeletable lockedSocialGroups = mock(ReplaceDeletable.class); + when(graph.resources().get("social-groups-service").lockResourceVersion("rv-3")) + .thenReturn(lockedSocialGroups); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); String publicationRevision = @@ -117,6 +154,12 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe when(graph.resources().get("game-logic-service").lockResourceVersion("rv-3")) .thenReturn(lockedGameLogic); + Map workloadIdentityRevisions = new LinkedHashMap<>(publicationRevisions); + workloadIdentityRevisions.put(HostedIdentityContract.GRPC_ACCOUNT_ROLE, "account-current"); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "game-session-current"); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "social-groups-current"); DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -125,7 +168,7 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe "telnet-current", "gateway-current", "grpc-current", - publicationRevisions, + workloadIdentityRevisions, () -> {}); assertEquals(false, result.ready()); @@ -141,10 +184,49 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe .getMetadata() .getAnnotations() .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + verify(lockedAccount).replace(accountReplacement.capture()); + assertEquals( + expectedWorkloadRevision("grpc-current", "account-current", "account-leaf"), + accountReplacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + verify(lockedGameSession).replace(gameSessionReplacement.capture()); + assertEquals( + expectedWorkloadRevision("grpc-current", "game-session-current", "game-session-leaf"), + gameSessionReplacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + verify(lockedSocialGroups).replace(socialGroupsReplacement.capture()); + assertEquals( + expectedWorkloadRevision("grpc-current", "social-groups-current", "social-groups-leaf"), + socialGroupsReplacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); Deployment converged = replacement.getValue(); converged.getMetadata().setGeneration(4L); converged.getStatus().setObservedGeneration(4L); + Deployment convergedAccount = accountReplacement.getValue(); + convergedAccount.getMetadata().setGeneration(4L); + convergedAccount.getStatus().setObservedGeneration(4L); + Deployment convergedGameSession = gameSessionReplacement.getValue(); + convergedGameSession.getMetadata().setGeneration(4L); + convergedGameSession.getStatus().setObservedGeneration(4L); + Deployment convergedSocialGroups = socialGroupsReplacement.getValue(); + convergedSocialGroups.getMetadata().setGeneration(4L); + convergedSocialGroups.getStatus().setObservedGeneration(4L); DeploymentRolloutService.RolloutResult secondResult = new DeploymentRolloutService() .sync( @@ -153,7 +235,7 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe "telnet-current", "gateway-current", "grpc-current", - publicationRevisions, + workloadIdentityRevisions, () -> {}); assertEquals(true, secondResult.ready()); @@ -169,16 +251,27 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe verify(graph.resources().get(workload), never()).lockResourceVersion(anyString()); } } - verify(graph.resources().get("account-service"), never()).lockResourceVersion(anyString()); + verify(graph.resources().get("account-service")).lockResourceVersion("rv-3"); + verify(lockedAccount, times(1)).replace(org.mockito.ArgumentMatchers.any(Deployment.class)); + verify(graph.resources().get("game-session-service")).lockResourceVersion("rv-3"); + verify(lockedGameSession, times(1)).replace(org.mockito.ArgumentMatchers.any(Deployment.class)); + verify(graph.resources().get("social-groups-service")).lockResourceVersion("rv-3"); + verify(lockedSocialGroups, times(1)) + .replace(org.mockito.ArgumentMatchers.any(Deployment.class)); } @Test - void sharedGrpcRevisionRollsEveryPublicationWorkloadAndLeavesUnrelatedWorkloadUntouched() { + void sharedGrpcRevisionRollsAllEightDistinctConsumersAndLeavesUnrelatedWorkloadUntouched() { 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); String[] deploymentNames = java.util.stream.Stream.concat( java.util.stream.Stream.of("tcp-proxy-service", "logging-admin-service"), - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream()) + grpcWorkloads.stream()) .toArray(String[]::new); DeploymentClientGraph graph = deploymentClient(plan, deploymentNames); when(graph.resources().get("tcp-proxy-service").get()) @@ -188,13 +281,13 @@ void sharedGrpcRevisionRollsEveryPublicationWorkloadAndLeavesUnrelatedWorkloadUn Map.of(HostedIdentityContract.TELNET_REVISION_ANNOTATION, "telnet-current"), 3L)); - Map publicationRevisions = new LinkedHashMap<>(); + Map workloadIdentityRevisions = new LinkedHashMap<>(); Map> lockedResources = new LinkedHashMap<>(); - for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { - String role = HostedIdentityContract.grpcPublicationRole(workload); - String publicationRevision = "publication-current-" + role; + for (String workload : grpcWorkloads) { + String role = grpcRoleForWorkload(workload); + String leafRevision = "leaf-current-" + role; assertEquals(false, plan.grpcConsumers().contains(workload)); - publicationRevisions.put(role, publicationRevision); + workloadIdentityRevisions.put(role, leafRevision); RollableScalableResource resource = graph.resources().get(workload); when(resource.get()) .thenReturn( @@ -202,13 +295,12 @@ void sharedGrpcRevisionRollsEveryPublicationWorkloadAndLeavesUnrelatedWorkloadUn workload, Map.of( HostedIdentityContract.GRPC_REVISION_ANNOTATION, - expectedPublicationRevision("grpc-old", publicationRevision)), + expectedWorkloadRevision("grpc-old", leafRevision, leafKindForRole(role))), 3L)); ReplaceDeletable locked = mock(ReplaceDeletable.class); when(resource.lockResourceVersion("rv-3")).thenReturn(locked); lockedResources.put(workload, locked); } - DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -217,18 +309,19 @@ void sharedGrpcRevisionRollsEveryPublicationWorkloadAndLeavesUnrelatedWorkloadUn "telnet-current", "gateway-current", "grpc-new", - publicationRevisions, + workloadIdentityRevisions, () -> {}); assertEquals(false, result.ready()); assertEquals(true, result.telnetReady()); assertEquals(false, result.grpcReady()); - for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { - String role = HostedIdentityContract.grpcPublicationRole(workload); + for (String workload : grpcWorkloads) { + String role = grpcRoleForWorkload(workload); + String leafRevision = workloadIdentityRevisions.get(role); ArgumentCaptor replacement = ArgumentCaptor.forClass(Deployment.class); verify(lockedResources.get(workload)).replace(replacement.capture()); assertEquals( - expectedPublicationRevision("grpc-new", publicationRevisions.get(role)), + expectedWorkloadRevision("grpc-new", leafRevision, leafKindForRole(role)), replacement .getValue() .getSpec() @@ -244,6 +337,164 @@ void sharedGrpcRevisionRollsEveryPublicationWorkloadAndLeavesUnrelatedWorkloadUn .lockResourceVersion(anyString()); } + @Test + void declaredWorkloadIdentityConsumersReceiveCombinedTrustAndLeafRevision() { + EnvironmentIdentityPlan plan = + planWithConsumers( + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + 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); + String[] deploymentNames = + java.util.stream.Stream.concat( + java.util.stream.Stream.of("tcp-proxy-service"), grpcWorkloads.stream()) + .toArray(String[]::new); + DeploymentClientGraph graph = deploymentClient(plan, deploymentNames); + when(graph.resources().get("tcp-proxy-service").get()) + .thenReturn( + readyDeployment( + "tcp-proxy-service", + Map.of(HostedIdentityContract.TELNET_REVISION_ANNOTATION, "telnet-current"), + 3L)); + + Map workloadIdentityRevisions = new LinkedHashMap<>(); + Map> lockedResources = new LinkedHashMap<>(); + for (String workload : grpcWorkloads) { + String role = grpcRoleForWorkload(workload); + String leafRevision = "leaf-current-" + role; + workloadIdentityRevisions.put(role, leafRevision); + String observedRevision = + plan.grpcConsumers().contains(workload) + ? "grpc-current" + : expectedWorkloadRevision("grpc-current", leafRevision, leafKindForRole(role)); + RollableScalableResource resource = graph.resources().get(workload); + when(resource.get()) + .thenReturn( + readyDeployment( + workload, + Map.of(HostedIdentityContract.GRPC_REVISION_ANNOTATION, observedRevision), + 3L)); + ReplaceDeletable locked = mock(ReplaceDeletable.class); + when(resource.lockResourceVersion("rv-3")).thenReturn(locked); + lockedResources.put(workload, locked); + } + + assertEquals(8, workloadIdentityRevisions.size()); + DeploymentRolloutService.RolloutResult result = + new DeploymentRolloutService() + .sync( + graph.client(), + plan, + "telnet-current", + "gateway-current", + "grpc-current", + workloadIdentityRevisions, + () -> {}); + + assertEquals(false, result.grpcReady()); + for (String workload : plan.grpcConsumers()) { + String role = grpcRoleForWorkload(workload); + ArgumentCaptor replacement = ArgumentCaptor.forClass(Deployment.class); + verify(lockedResources.get(workload)).replace(replacement.capture()); + assertEquals( + expectedWorkloadRevision( + "grpc-current", workloadIdentityRevisions.get(role), leafKindForRole(role)), + replacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + } + for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { + verify(lockedResources.get(workload), never()) + .replace(org.mockito.ArgumentMatchers.any(Deployment.class)); + } + } + + @Test + void dedicatedLeafRolloutsGateReadinessOutsideThePlanConsumerList() { + 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); + Map> pendingReplacements = new LinkedHashMap<>(); + Map> workloadLocks = new LinkedHashMap<>(); + + for (String pendingWorkload : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)) { + EnvironmentIdentityPlan plan = planWithConsumers(); + String[] deploymentNames = + java.util.stream.Stream.concat( + java.util.stream.Stream.of("tcp-proxy-service"), grpcWorkloads.stream()) + .toArray(String[]::new); + DeploymentClientGraph graph = deploymentClient(plan, deploymentNames); + when(graph.resources().get("tcp-proxy-service").get()) + .thenReturn( + readyDeployment( + "tcp-proxy-service", + Map.of(HostedIdentityContract.TELNET_REVISION_ANNOTATION, "telnet-current"), + 3L)); + + Map workloadIdentityRevisions = new LinkedHashMap<>(); + for (String workload : grpcWorkloads) { + String role = grpcRoleForWorkload(workload); + String desiredLeafRevision = "leaf-current-" + role; + workloadIdentityRevisions.put(role, desiredLeafRevision); + String observedLeafRevision = + pendingWorkload.equals(workload) ? "leaf-old-" + role : desiredLeafRevision; + RollableScalableResource resource = graph.resources().get(workload); + ArgumentCaptor replacement = ArgumentCaptor.forClass(Deployment.class); + when(resource.get()) + .thenReturn( + readyDeployment( + workload, + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision( + "grpc-current", observedLeafRevision, leafKindForRole(role))), + 3L)) + .thenAnswer(invocation -> replacement.getValue()); + ReplaceDeletable locked = mock(ReplaceDeletable.class); + when(resource.lockResourceVersion("rv-3")).thenReturn(locked); + workloadLocks.put(workload, locked); + if (pendingWorkload.equals(workload)) { + pendingReplacements.put(pendingWorkload, replacement); + } + } + + DeploymentRolloutService.RolloutResult result = + new DeploymentRolloutService() + .sync( + graph.client(), + plan, + "telnet-current", + "gateway-current", + "grpc-current", + workloadIdentityRevisions, + () -> {}); + + assertEquals(false, result.grpcReady(), pendingWorkload + " leaf rollout remains pending"); + verify(workloadLocks.get(pendingWorkload)) + .replace(pendingReplacements.get(pendingWorkload).capture()); + for (String workload : grpcWorkloads) { + if (!pendingWorkload.equals(workload)) { + verify(workloadLocks.get(workload), never()) + .replace(org.mockito.ArgumentMatchers.any(Deployment.class)); + } + } + } + } + @Test void rejectsPublicationWorkloadOverlappingGrpcConsumerBeforeAnyRolloutMutation() { String overlappingWorkload = HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.getFirst(); @@ -987,13 +1238,46 @@ private static EnvironmentIdentityPlan planWithConsumers(String... consumers) { private static String expectedPublicationRevision( String grpcRevision, String publicationRevision) { + return expectedWorkloadRevision(grpcRevision, publicationRevision, "publication-leaf"); + } + + private static String expectedWorkloadRevision( + String grpcRevision, String workloadRevision, String workloadKind) { return "v1|shared-grpc|" + grpcRevision.length() + "|" + grpcRevision - + "|publication-leaf|" - + publicationRevision.length() + "|" - + publicationRevision; + + workloadKind + + "|" + + workloadRevision.length() + + "|" + + workloadRevision; + } + + private static String grpcRoleForWorkload(String workload) { + if (HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD.equals(workload)) { + return HostedIdentityContract.GRPC_ACCOUNT_ROLE; + } + if (HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD.equals(workload)) { + return HostedIdentityContract.GRPC_GAME_SESSION_ROLE; + } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD.equals(workload)) { + return HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE; + } + return HostedIdentityContract.grpcPublicationRole(workload); + } + + private static String leafKindForRole(String role) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + return "account-leaf"; + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + return "game-session-leaf"; + } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return "social-groups-leaf"; + } + return "publication-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 6f4044bb8b..ff8128ad4e 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 @@ -234,7 +234,10 @@ void identityRoleNamesOnlyCoverCertManagerCertificates() { "pr-42-grpc-world-management-service", "pr-42-grpc-entity-management-service", "pr-42-grpc-game-logic-service", - "pr-42-grpc-automation-scripting-service"), + "pr-42-grpc-automation-scripting-service", + "pr-42-grpc-account-service", + "pr-42-grpc-game-session-service", + "pr-42-grpc-social-groups-service"), HostedIdentityScopeService.requiredCertificateNames(plan)); } @@ -250,6 +253,9 @@ void runtimeRoleCoversBothBridgeDeploymentsAndEveryGrpcConsumer() { "entity-management-service", "game-logic-service", "automation-scripting-service", + "account-service", + "game-session-service", + "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service"), HostedIdentityScopeService.requiredDeploymentNames(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 1ba8ae704b..47b6195d43 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 @@ -62,7 +62,7 @@ static Secret certManagerSource( HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.grpcIssuer(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { yield plan.grpcIssuer(); } throw new IllegalArgumentException("unsupported cert-manager role: " + role); @@ -371,6 +371,48 @@ static StableBatchFixture stableBatchFixture() { .getAnnotations() .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); } + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); SecretMaterialValidator validator = mock(SecretMaterialValidator.class); SecretMaterialValidator.MaterialSummary summary = new SecretMaterialValidator.MaterialSummary( @@ -480,11 +522,35 @@ static String secretName(EnvironmentIdentityPlan plan, String role) { case HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE -> plan.gatewayInternalWsSecretName(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.tcpProxyBridgeSecretName(); case HostedIdentityContract.GRPC_ROLE -> plan.grpcSecretName(); - default -> plan.grpcPublicationSecretName(grpcPublicationWorkload(role)); + default -> { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + yield plan.grpcAccountSecretName(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + yield plan.grpcGameSessionSecretName(); + } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + yield plan.grpcSocialGroupsSecretName(); + } + if (HostedIdentityContract.isGrpcPublicationRole(role)) { + yield plan.grpcPublicationSecretName( + role.substring(HostedIdentityContract.GRPC_PUBLICATION_ROLE_PREFIX.length())); + } + throw new IllegalArgumentException("unsupported role"); + } }; } static String sourceSecretName(EnvironmentIdentityPlan plan, String role) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + return plan.grpcAccountSourceSecretName(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + return plan.grpcGameSessionSourceSecretName(); + } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return plan.grpcSocialGroupsSourceSecretName(); + } 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 b7632c9067..928da2e43a 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 @@ -1403,6 +1403,13 @@ void caRotationValidatesOnlyTheSelectedNewSourceAndPinsOtherSharedRoles() { acceptedData, acceptedData); } + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); + } stubCertificate( secretClient.client(), plan, @@ -1578,6 +1585,13 @@ private static DriftSelectionFixture driftSelectionFixture(boolean sourceAdvance acceptedData, acceptedData); } + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); + } stubCertificate( secretClient.client(), plan, 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 733995d04d..832187b658 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 @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; @@ -105,11 +106,79 @@ void readinessProbeRequiresBridgeAndInternalGrpcAcceptanceAfterPublicEndpoints() assertEquals( "bridge-rejected", probe.probe(plan, 32001, ready, ready, rejected, ready).reason()); assertEquals("grpc-rejected", probe.probe(plan, 32001, ready, ready, ready, rejected).reason()); + assertEquals( + "grpc-game-session-rejected", + probe + .probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + (hostname, port) -> { + assertEquals("game-session-service.pr-42.svc.cluster.local", hostname); + assertEquals(6565, port); + return new ServedEnvironmentProbe.ProbeResult(false, "rejected"); + }) + .reason()); assertEquals( "served-bridge-and-grpc-accepted", probe.probe(plan, 32001, ready, ready, ready, ready).reason()); } + @Test + void readinessProbeRequiresSocialGroupsToServeItsCurrentLeafAtItsFixedEndpoint() { + HostedIdentityProperties properties = new HostedIdentityProperties(); + EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + List endpoints = Collections.synchronizedList(new ArrayList<>()); + ServedEnvironmentProbe.EndpointProbe ready = + (hostname, port) -> { + endpoints.add(hostname + ":" + port); + return new ServedEnvironmentProbe.ProbeResult(true, "ready"); + }; + ServedEnvironmentProbe.EndpointProbe staleSocialGroupsLeaf = + (hostname, port) -> { + assertEquals("social-groups-service.pr-42.svc.cluster.local", hostname); + assertEquals(6565, port); + return new ServedEnvironmentProbe.ProbeResult(false, "leaf-fingerprint-mismatch"); + }; + + ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); + assertEquals( + "grpc-social-groups-leaf-fingerprint-mismatch", + probe + .probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + ready, + staleSocialGroupsLeaf) + .reason()); + assertTrue(endpoints.contains("account-service.pr-42.svc.cluster.local:6565")); + assertTrue(endpoints.contains("game-session-service.pr-42.svc.cluster.local:6565")); + + ServedEnvironmentProbe.ProbeResult converged = + probe.probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + ready, + ready); + + assertTrue(converged.ready()); + assertTrue(endpoints.contains("social-groups-service.pr-42.svc.cluster.local:6565")); + } + @Test void privateReadinessSkipsOnlyThePublicTelnetProbe() { HostedIdentityProperties properties = new HostedIdentityProperties(); @@ -139,9 +208,11 @@ void privateReadinessSkipsOnlyThePublicTelnetProbe() { Set.of( "pr-42.preview.firedevops.net:443", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", - "account-service.pr-42.svc.cluster.local:6565"), + "account-service.pr-42.svc.cluster.local:6565", + "game-session-service.pr-42.svc.cluster.local:6565", + "social-groups-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(3, endpoints.size()); + assertEquals(5, endpoints.size()); } @Test @@ -173,9 +244,15 @@ void failureClassificationUsesStableProbeNamesRatherThanListPositions() { new ServedEnvironmentProbe.ProbeResult(false, "rejected"); assertEquals( - List.of("grpc-rejected", "https-rejected", "bridge-rejected", "telnet-rejected"), + List.of( + "grpc-rejected", + "grpc-social-groups-rejected", + "https-rejected", + "bridge-rejected", + "telnet-rejected"), List.of( ServedEnvironmentProbe.ProbeName.GRPC, + ServedEnvironmentProbe.ProbeName.GRPC_SOCIAL_GROUPS, ServedEnvironmentProbe.ProbeName.HTTPS, ServedEnvironmentProbe.ProbeName.BRIDGE, ServedEnvironmentProbe.ProbeName.TELNET) @@ -210,9 +287,11 @@ void readinessProbeSuppliesEachDerivedEndpointToItsProbeSeam() { "pr-42.preview.firedevops.net:443", "pr-42.preview.firedevops.net:32001", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", - "account-service.pr-42.svc.cluster.local:6565"), + "account-service.pr-42.svc.cluster.local:6565", + "game-session-service.pr-42.svc.cluster.local:6565", + "social-groups-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(4, endpoints.size()); + assertEquals(6, endpoints.size()); } @Test @@ -220,7 +299,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(4); + CountDownLatch started = new CountDownLatch(6); EndpointProbeState state = new EndpointProbeState(started); ServedEnvironmentProbe.EndpointProbe endpoint = state::check; @@ -228,7 +307,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { probe.probe(plan, 32001, endpoint, endpoint, endpoint, endpoint, Duration.ofSeconds(10)); assertEquals("served-bridge-and-grpc-accepted", result.reason()); - assertEquals(4, state.calls.get()); + assertEquals(6, state.calls.get()); assertEquals(0, started.getCount()); } @@ -237,8 +316,8 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(4); - CountDownLatch interrupted = new CountDownLatch(4); + CountDownLatch started = new CountDownLatch(6); + CountDownLatch interrupted = new CountDownLatch(6); List openSockets = Collections.synchronizedList(new ArrayList<>()); ServedEnvironmentProbe.EndpointProbe endpoint = (hostname, port) -> { @@ -262,7 +341,7 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t assertEquals("probe-deadline-exceeded", result.reason()); assertTrue(started.await(1, TimeUnit.SECONDS)); assertTrue(interrupted.await(1, TimeUnit.SECONDS)); - assertEquals(4, openSockets.size()); + assertEquals(6, openSockets.size()); for (SSLSocket openSocket : openSockets) { verify(openSocket).close(); } @@ -393,25 +472,47 @@ void servedProbeClosesSocketWhenSetupFailsBeforeOwnershipTransfer() throws Excep void internalGrpcProbeCompletesMutualTlsWithFixedCaHostnameAndLeafPin() throws Exception { HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); - Secret material = generatedMaterial(plan); - String trustAnchor = fingerprint(material.getData().get("ca.crt")); - String leaf = fingerprint(material.getData().get("tls.crt")); + List materials = GrpcMaterialFixture.generateDistinctLeavesWithSharedCa(plan); + Secret accountServerMaterial = materials.get(0); + Secret genericClientMaterial = materials.get(1); + String trustAnchor = fingerprint(accountServerMaterial.getData().get("ca.crt")); + String accountLeaf = fingerprint(accountServerMaterial.getData().get("tls.crt")); + String genericLeaf = fingerprint(genericClientMaterial.getData().get("tls.crt")); String identityHostname = "account-service.pr-42.svc.cluster.local"; + assertEquals( + accountServerMaterial.getData().get("ca.crt"), + genericClientMaterial.getData().get("ca.crt")); + assertNotEquals(accountLeaf, genericLeaf); - try (SSLServerSocket server = mutualTlsServer(material, trustAnchor, "h2")) { + try (SSLServerSocket server = mutualTlsServer(accountServerMaterial, trustAnchor, "h2")) { CompletableFuture accepted = acceptOne(server); try (SSLSocket client = ServedEnvironmentProbe.openGrpcTlsSocket( InetAddress.getLoopbackAddress().getHostAddress(), identityHostname, server.getLocalPort(), - leaf, - material, + accountLeaf, + genericClientMaterial, trustAnchor)) { assertNotNull(client); } accepted.get(10, TimeUnit.SECONDS); } + + try (SSLServerSocket server = mutualTlsServer(accountServerMaterial, trustAnchor, "h2")) { + CompletableFuture accepted = acceptOne(server); + try (SSLSocket client = + ServedEnvironmentProbe.openGrpcTlsSocket( + InetAddress.getLoopbackAddress().getHostAddress(), + identityHostname, + server.getLocalPort(), + genericLeaf, + genericClientMaterial, + trustAnchor)) { + assertNull(client); + } + accepted.get(10, TimeUnit.SECONDS); + } } @Test 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 8a161f3489..16e18a534b 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 @@ -182,7 +182,7 @@ void projectionAcceptanceStatusUsesTheFirstUnsyncedProjection() { } @Test - void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { + void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture( new RuntimeProfileService.RuntimeProfile( @@ -210,6 +210,8 @@ void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { any(Secret.class), anyString(), any(Secret.class), + anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); Map acknowledgedProjections = @@ -242,7 +244,7 @@ void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { status.getGrpcPublication().keySet()); assertTrue(status.getGrpcPublication().values().stream().allMatch(java.util.Objects::nonNull)); assertEquals( - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 5, + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 8, acknowledgedProjections.size()); assertEquals( "awaiting-acceptance", @@ -276,7 +278,9 @@ void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { any(Secret.class), anyString(), any(Secret.class), - anyString()); + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64))); } @Test @@ -320,6 +324,74 @@ void probeStatusOwnsReasonAndMessageAfterEarlierGatesPass() { false); } + @Test + void staleGameSessionOrSocialGroupsServedLeafBlocksControllerReadiness() { + for (String[] staleLeaf : + new String[][] {{"game-session-service", "c"}, {"social-groups-service", "d"}}) { + var expected = + new RuntimeProfileService.RuntimeProfile( + "uid", + "a".repeat(40), + "a".repeat(40), + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32016, + true); + DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture(expected); + String failureReason = "grpc-" + staleLeaf[0] + "-leaf-fingerprint-mismatch"; + when(fixture.batch.tcpProxyBridge()) + .thenReturn( + DeploymentHeadGateFixture.material( + fixture.plan, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, "4")); + MixedOperation> secrets = mock(MixedOperation.class); + NonNamespaceOperation> runtimeSecrets = + mock(NonNamespaceOperation.class); + Resource absent = mock(Resource.class); + when(fixture.client.secrets()).thenReturn(secrets); + when(secrets.inNamespace(fixture.plan.runtimeNamespace())).thenReturn(runtimeSecrets); + when(runtimeSecrets.withName(fixture.plan.tcpProxyBridgeSecretName())).thenReturn(absent); + when(absent.get()).thenReturn(null); + when(fixture.rollout.sync( + any(), any(), anyString(), anyString(), anyString(), anyMap(), any())) + .thenReturn(new DeploymentRolloutService.RolloutResult(true, true, true)); + when(fixture.probes.probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64)))) + .thenReturn(new ServedEnvironmentProbe.ProbeResult(false, failureReason)); + + UpdateControl result = fixture.reconcile(); + + HostedEnvironmentIdentityStatus status = result.getResource().orElseThrow().getStatus(); + assertEquals(HostedEnvironmentIdentityStatus.Phase.Verifying, status.getPhase()); + assertEquals("ServedProbePending", status.getConditions().get(0).getReason()); + assertEquals(failureReason, status.getConditions().get(0).getMessage()); + verify(fixture.probes) + .probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64))); + verify(fixture.projections, never()) + .acknowledge( + any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any()); + } + } + @Test void readyStatusPreservesTheSuccessfulProbeMessage() { var status = @@ -523,6 +595,8 @@ void readinessBoundaryRejectsAChangedRuntimeTupleBeforeAcknowledgement() { any(Secret.class), anyString(), any(Secret.class), + anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -580,6 +654,8 @@ void malformedRuntimeProfileAtReadinessBoundaryFailsClosedWithoutAcknowledgement any(Secret.class), anyString(), any(Secret.class), + anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -800,6 +876,8 @@ void projectionAcknowledgementFenceNamesTheProtectedAction() { any(Secret.class), anyString(), any(Secret.class), + anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); when(fixture.projections.acknowledge( @@ -1559,6 +1637,142 @@ void grpcPublicationRollbackIsRejectedBeforeRecreatingMissingRuntimeProjection() verifyNoInteractions(fixture.projections); } + @Test + void grpcWorkloadIdentityRollbackIsRejectedAndHighWaterSurvivesRuntimeRecreation() { + record SourceProgressCase( + long sourceGeneration, long objectGeneration, String spki, String failure) {} + + List rollbackCases = + List.of( + new SourceProgressCase(3, 2, "c".repeat(64), "generation"), + new SourceProgressCase(4, 1, "c".repeat(64), "object-generation"), + new SourceProgressCase(4, 2, "c".repeat(64), "same-generation-substitution")); + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { + for (SourceProgressCase rollbackCase : rollbackCases) { + DeploymentHeadGateFixture fixture = + new DeploymentHeadGateFixture( + new RuntimeProfileService.RuntimeProfile( + "recreated-runtime-uid", + "a".repeat(40), + "a".repeat(40), + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32016, + true)); + String previousCertificate = "previous-" + role; + String previousSpki = "b".repeat(64); + HostedEnvironmentIdentityStatus.RoleStatus highWater = + new HostedEnvironmentIdentityStatus.RoleStatus(); + highWater.setRevision( + SecretProjectionService.revisionForRole( + role, Map.of("tls.crt", encoded(previousCertificate)))); + highWater.setSourceGeneration(4L); + highWater.setSourceObjectGeneration(2L); + highWater.setSpkiSha256(previousSpki); + highWater.setProvenance("cert-manager"); + highWater.setState("source-ready"); + HostedEnvironmentIdentityStatus priorStatus = new HostedEnvironmentIdentityStatus(); + setGrpcWorkloadRoleStatus(priorStatus, role, highWater); + fixture.resource.setStatus(priorStatus); + + CertificateMaterialService.RoleMaterial olderSource = + roleMaterial( + role, + rollbackCase.sourceGeneration(), + rollbackCase.objectGeneration(), + rollbackCase.spki(), + "replacement-" + role + "-" + rollbackCase.failure()); + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + when(fixture.batch.grpcAccount()).thenReturn(olderSource); + } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + when(fixture.batch.grpcGameSession()).thenReturn(olderSource); + } else { + when(fixture.batch.grpcSocialGroups()).thenReturn(olderSource); + } + + UpdateControl result = fixture.reconcile(); + + HostedEnvironmentIdentityStatus blocked = result.getResource().orElseThrow().getStatus(); + String expectedMessage = + switch (rollbackCase.failure()) { + case "generation" -> + "certificate source generation rolled back for role " + + role + + " (source generation 3 < prior generation 4)"; + case "object-generation" -> "certificate source object generation rolled back"; + case "same-generation-substitution" -> + "certificate source changed without generation advancement"; + default -> throw new AssertionError("unknown rollback case"); + }; + assertEquals(HostedEnvironmentIdentityStatus.Phase.Blocked, blocked.getPhase()); + assertEquals("ReconciliationBlocked", blocked.getConditions().get(0).getReason()); + assertEquals(expectedMessage, blocked.getConditions().get(0).getMessage()); + HostedEnvironmentIdentityStatus.RoleStatus retained = grpcWorkloadRoleStatus(blocked, role); + assertNotNull(retained); + assertEquals(4L, retained.getSourceGeneration()); + assertEquals(2L, retained.getSourceObjectGeneration()); + assertEquals(highWater.getRevision(), retained.getRevision()); + assertEquals(previousSpki, retained.getSpkiSha256()); + verifyNoInteractions(fixture.projections); + } + } + } + + @Test + void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { + HostedEnvironmentIdentity resource = resource(); + HostedEnvironmentIdentityStatus status = new HostedEnvironmentIdentityStatus(); + resource.setStatus(status); + assertNull( + HostedIdentityReconciler.previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + assertNull( + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + assertNull( + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); + + HostedEnvironmentIdentityStatus.RoleStatus account = + roleStatus("account-revision", 4L, 2L, "a".repeat(64)); + HostedEnvironmentIdentityStatus.RoleStatus gameSession = + roleStatus("game-session-revision", 5L, 3L, "b".repeat(64)); + HostedEnvironmentIdentityStatus.RoleStatus socialGroups = + roleStatus("social-groups-revision", 6L, 4L, "c".repeat(64)); + status.setGrpcAccountService(account); + status.setGrpcGameSessionService(gameSession); + status.setGrpcSocialGroupsService(socialGroups); + resource.setStatus(status); + + HostedEnvironmentIdentityStatus.RoleStatus accountReadback = + HostedIdentityReconciler.previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE); + HostedEnvironmentIdentityStatus.RoleStatus gameSessionReadback = + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + HostedEnvironmentIdentityStatus.RoleStatus socialGroupsReadback = + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + assertNotSame(account, accountReadback); + assertNotSame(gameSession, gameSessionReadback); + assertEquals(account.getRevision(), accountReadback.getRevision()); + assertEquals(account.getSourceGeneration(), accountReadback.getSourceGeneration()); + assertEquals(account.getSourceObjectGeneration(), accountReadback.getSourceObjectGeneration()); + assertEquals(account.getSpkiSha256(), accountReadback.getSpkiSha256()); + assertEquals(gameSession.getRevision(), gameSessionReadback.getRevision()); + assertEquals(gameSession.getSourceGeneration(), gameSessionReadback.getSourceGeneration()); + assertEquals( + gameSession.getSourceObjectGeneration(), gameSessionReadback.getSourceObjectGeneration()); + assertEquals(gameSession.getSpkiSha256(), gameSessionReadback.getSpkiSha256()); + assertNotSame(socialGroups, socialGroupsReadback); + assertEquals(socialGroups.getRevision(), socialGroupsReadback.getRevision()); + assertEquals(socialGroups.getSourceGeneration(), socialGroupsReadback.getSourceGeneration()); + assertEquals( + socialGroups.getSourceObjectGeneration(), socialGroupsReadback.getSourceObjectGeneration()); + assertEquals(socialGroups.getSpkiSha256(), socialGroupsReadback.getSpkiSha256()); + } + @Test void grpcPublicationHistoryAllowsLegacyAbsenceAndRejectsMalformedPartialMap() { String role = HostedIdentityContract.grpcPublicationRole("game-design-service"); @@ -1759,6 +1973,9 @@ private static boolean crdSchemaAccepts(Map propertySchema, Object value) schemaMap(schemaMap(openApiSchema.get("properties")).get("status")).get("properties")); Map consumerSchema = schemaMap(statusProperties.get("ingress")); Map publicationSchema = schemaMap(statusProperties.get("grpcPublication")); + assertEquals(consumerSchema, statusProperties.get("grpcAccountService")); + assertEquals(consumerSchema, statusProperties.get("grpcGameSessionService")); + assertEquals(consumerSchema, statusProperties.get("grpcSocialGroupsService")); assertEquals( consumerSchema, publicationSchema.get("additionalProperties"), @@ -2101,6 +2318,8 @@ void missingBridgeProjectionMapsReconciliationToVerifyingProbeStatus() { org.mockito.ArgumentMatchers.isNull(), anyString(), any(Secret.class), + anyString(), + anyString(), anyString())) .thenReturn( new ServedEnvironmentProbe.ProbeResult(false, "material-or-leaf-fingerprint-missing")); @@ -2138,8 +2357,15 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { assertEquals("3".repeat(64), status.getGatewayInternalWs().getSpkiSha256()); assertEquals("4".repeat(64), status.getTcpProxyBridge().getSpkiSha256()); assertEquals("5".repeat(64), status.getGrpc().getSpkiSha256()); + assertEquals("b".repeat(64), status.getGrpcAccountService().getSpkiSha256()); + assertEquals("c".repeat(64), status.getGrpcGameSessionService().getSpkiSha256()); + assertEquals("d".repeat(64), status.getGrpcSocialGroupsService().getSpkiSha256()); + assertEquals(1L, status.getGrpcAccountService().getSourceGeneration()); + assertEquals(1L, status.getGrpcGameSessionService().getSourceGeneration()); + assertEquals(1L, status.getGrpcSocialGroupsService().getSourceGeneration()); ArgumentCaptor gatewayRevision = ArgumentCaptor.forClass(String.class); - ArgumentCaptor> publicationRevisions = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor> workloadIdentityRevisions = + ArgumentCaptor.forClass(Map.class); verify(fixture.rollout) .sync( any(), @@ -2147,7 +2373,7 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { anyString(), gatewayRevision.capture(), anyString(), - publicationRevisions.capture(), + workloadIdentityRevisions.capture(), any()); assertEquals( "revision-" + HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE, gatewayRevision.getValue()); @@ -2162,8 +2388,14 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { "grpc-publication-game-logic-service", "revision-grpc-publication-game-logic-service", "grpc-publication-automation-scripting-service", - "revision-grpc-publication-automation-scripting-service"), - publicationRevisions.getValue()); + "revision-grpc-publication-automation-scripting-service", + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + "revision-" + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + "revision-" + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + "revision-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), + workloadIdentityRevisions.getValue()); verify(fixture.runtime, times(2)) .validateTcpProxyService(fixture.client, fixture.plan, expected); } @@ -2221,6 +2453,64 @@ private static CertificateMaterialService.RoleMaterial material( state); } + private static CertificateMaterialService.RoleMaterial roleMaterial( + String role, long generation, long objectGeneration, String spki, String certificate) { + return new CertificateMaterialService.RoleMaterial( + role, + new SecretBuilder() + .withType("kubernetes.io/tls") + .withData(Map.of("tls.crt", encoded(certificate))) + .build(), + new SecretMaterialValidator.MaterialSummary( + sha256(certificate), spki, Instant.EPOCH, Instant.MAX, "4".repeat(64)), + generation, + objectGeneration, + "cert-manager", + SOURCE_READY); + } + + private static HostedEnvironmentIdentityStatus.RoleStatus roleStatus( + String revision, long sourceGeneration, long sourceObjectGeneration, String spki) { + HostedEnvironmentIdentityStatus.RoleStatus status = + new HostedEnvironmentIdentityStatus.RoleStatus(); + status.setRevision(revision); + status.setSourceGeneration(sourceGeneration); + status.setSourceObjectGeneration(sourceObjectGeneration); + status.setSpkiSha256(spki); + status.setProvenance("cert-manager"); + status.setState("source-ready"); + return status; + } + + private static void setGrpcWorkloadRoleStatus( + HostedEnvironmentIdentityStatus status, + String role, + HostedEnvironmentIdentityStatus.RoleStatus roleStatus) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + status.setGrpcAccountService(roleStatus); + } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + status.setGrpcGameSessionService(roleStatus); + } else if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + status.setGrpcSocialGroupsService(roleStatus); + } else { + throw new IllegalArgumentException("unsupported workload identity role: " + role); + } + } + + private static HostedEnvironmentIdentityStatus.RoleStatus grpcWorkloadRoleStatus( + HostedEnvironmentIdentityStatus status, String role) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + return status.getGrpcAccountService(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + return status.getGrpcGameSessionService(); + } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return status.getGrpcSocialGroupsService(); + } + throw new IllegalArgumentException("unsupported workload identity role: " + role); + } + private static String sha256(String value) { try { return HexFormat.of() @@ -2301,6 +2591,12 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr "4", SERIALIZED_DEFERRED_DRIFT)); when(batch.grpc(any())).thenReturn(material(plan, HostedIdentityContract.GRPC_ROLE, "5")); + when(batch.grpcAccount()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE, "b")); + when(batch.grpcGameSession()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "c")); + when(batch.grpcSocialGroups()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "d")); 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 a00d7701fb..35ebee8251 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 @@ -51,6 +51,37 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { "spring-cloud-gateway", "tcp-proxy-service"), plan.grpcConsumers()); + assertEquals( + "pr-42-grpc-game-design-service", + plan.grpcPublicationSourceSecretName("game-design-service")); + assertEquals( + "firemud-grpc-game-design-service", plan.grpcPublicationSecretName("game-design-service")); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/game-design-service", + plan.grpcPublicationUriSan("game-design-service")); + assertEquals("pr-42-grpc-account-service", plan.grpcAccountCertificateName()); + assertEquals("pr-42-grpc-account-service", plan.grpcAccountSourceSecretName()); + assertEquals("firemud-grpc-account-service", plan.grpcAccountSecretName()); + assertEquals( + plan.grpcAccountSecretName(), plan.secretName(HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + assertEquals("pr-42-grpc-game-session-service", plan.grpcGameSessionCertificateName()); + assertEquals("pr-42-grpc-game-session-service", plan.grpcGameSessionSourceSecretName()); + assertEquals("firemud-grpc-game-session-service", plan.grpcGameSessionSecretName()); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/game-session-service", + plan.grpcWorkloadIdentityUriSan(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD)); + assertEquals( + plan.grpcGameSessionSecretName(), + plan.secretName(HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + assertEquals("pr-42-grpc-social-groups-service", plan.grpcSocialGroupsCertificateName()); + assertEquals("pr-42-grpc-social-groups-service", plan.grpcSocialGroupsSourceSecretName()); + assertEquals("firemud-grpc-social-groups-service", plan.grpcSocialGroupsSecretName()); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/social-groups-service", + plan.grpcWorkloadIdentityUriSan(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)); + assertEquals( + plan.grpcSocialGroupsSecretName(), + plan.secretName(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { assertEquals("pr-42-grpc-" + workload, plan.grpcPublicationSourceSecretName(workload)); assertEquals("firemud-grpc-" + workload, plan.grpcPublicationSecretName(workload)); @@ -189,20 +220,20 @@ void mapsEveryRoleFamilyToItsCanonicalSourceSecretName() { void rejectsPublicationSourceSecretRoleMapsWithMissingOrExtraRoles() { var plan = planner.plan("pr-42"); String role = HostedIdentityContract.grpcPublicationRole("game-design-service"); - var sourceSecretNames = new HashMap<>(plan.grpcPublicationSourceSecretNames()); + var sourceSecretNames = new HashMap<>(plan.grpcWorkloadIdentitySourceSecretNames()); sourceSecretNames.remove(role); assertInvalidPublicationRoleMaps( plan, - plan.grpcPublicationCertificateNames(), - plan.grpcPublicationSecretNames(), + plan.grpcWorkloadIdentityCertificateNames(), + plan.grpcWorkloadIdentitySecretNames(), sourceSecretNames); - var extraSourceSecretNames = new HashMap<>(plan.grpcPublicationSourceSecretNames()); + var extraSourceSecretNames = new HashMap<>(plan.grpcWorkloadIdentitySourceSecretNames()); extraSourceSecretNames.put("grpc-publication-unsupported-service", "unsupported-source-secret"); assertInvalidPublicationRoleMaps( plan, - plan.grpcPublicationCertificateNames(), - plan.grpcPublicationSecretNames(), + plan.grpcWorkloadIdentityCertificateNames(), + plan.grpcWorkloadIdentitySecretNames(), extraSourceSecretNames); } @@ -212,37 +243,37 @@ void rejectsPublicationCertificateAndSecretRoleMapsWithMissingOrExtraRoles() { String role = HostedIdentityContract.grpcPublicationRole("game-design-service"); String unsupportedRole = "grpc-publication-unsupported-service"; - var missingCertificateNames = new HashMap<>(plan.grpcPublicationCertificateNames()); + var missingCertificateNames = new HashMap<>(plan.grpcWorkloadIdentityCertificateNames()); missingCertificateNames.remove(role); assertInvalidPublicationRoleMaps( plan, missingCertificateNames, - plan.grpcPublicationSecretNames(), - plan.grpcPublicationSourceSecretNames()); + plan.grpcWorkloadIdentitySecretNames(), + plan.grpcWorkloadIdentitySourceSecretNames()); - var extraCertificateNames = new HashMap<>(plan.grpcPublicationCertificateNames()); + var extraCertificateNames = new HashMap<>(plan.grpcWorkloadIdentityCertificateNames()); extraCertificateNames.put(unsupportedRole, "unsupported-certificate"); assertInvalidPublicationRoleMaps( plan, extraCertificateNames, - plan.grpcPublicationSecretNames(), - plan.grpcPublicationSourceSecretNames()); + plan.grpcWorkloadIdentitySecretNames(), + plan.grpcWorkloadIdentitySourceSecretNames()); - var missingSecretNames = new HashMap<>(plan.grpcPublicationSecretNames()); + var missingSecretNames = new HashMap<>(plan.grpcWorkloadIdentitySecretNames()); missingSecretNames.remove(role); assertInvalidPublicationRoleMaps( plan, - plan.grpcPublicationCertificateNames(), + plan.grpcWorkloadIdentityCertificateNames(), missingSecretNames, - plan.grpcPublicationSourceSecretNames()); + plan.grpcWorkloadIdentitySourceSecretNames()); - var extraSecretNames = new HashMap<>(plan.grpcPublicationSecretNames()); + var extraSecretNames = new HashMap<>(plan.grpcWorkloadIdentitySecretNames()); extraSecretNames.put(unsupportedRole, "unsupported-secret"); assertInvalidPublicationRoleMaps( plan, - plan.grpcPublicationCertificateNames(), + plan.grpcWorkloadIdentityCertificateNames(), extraSecretNames, - plan.grpcPublicationSourceSecretNames()); + plan.grpcWorkloadIdentitySourceSecretNames()); } @Test @@ -267,7 +298,7 @@ private static void assertInvalidPublicationRoleMaps( IllegalArgumentException.class, () -> copyPlan(plan, certificateNames, secretNames, sourceSecretNames)); assertEquals( - "gRPC publication certificate, runtime Secret, and source Secret maps must contain exactly the supported roles", + "gRPC workload-identity certificate, runtime Secret, and source Secret maps must contain exactly the supported roles", failure.getMessage()); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/GrpcMaterialFixture.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/GrpcMaterialFixture.java index d9c458f5e2..ade11b868e 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/GrpcMaterialFixture.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/GrpcMaterialFixture.java @@ -12,6 +12,7 @@ import java.time.Instant; import java.util.Base64; import java.util.Date; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.hostedidentity.config.HostedIdentityProperties; @@ -50,6 +51,23 @@ public static Secret generate(EnvironmentIdentityPlan plan) { } } + public static List generateDistinctLeavesWithSharedCa(EnvironmentIdentityPlan plan) { + try { + Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); + Duration lifetime = Duration.ofDays(7); + Secret caSource = generatedCa(now, Duration.ofDays(60)); + String trustAnchor = SecretMaterialValidator.trustAnchorFingerprint(caSource); + GrpcTransportBundleGenerator.validateCa(caSource, trustAnchor); + GrpcTransportBundleGenerator generator = + new GrpcTransportBundleGenerator(new SecretMaterialValidator()); + return List.of( + generator.generate(plan, caSource, 1, lifetime, now), + generator.generate(plan, caSource, 2, lifetime, now)); + } catch (Exception exception) { + throw new AssertionError("unable to create shared-CA gRPC test leaves", exception); + } + } + private static Secret generatedCa(Instant now, Duration lifetime) throws Exception { KeyPair keyPair = generateRsaKeyPair(); X500Name name = new X500Name("CN=FireMUD test transport root, O=FireMUD");