diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 25f49b447..6b0f346c7 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1236,6 +1236,8 @@ jobs: - run: helm lint charts/gameplane - name: evaluate monitoring rules run: bash charts/gameplane/tests/monitoring-rules.sh + - name: check MCP server RBAC scope + run: bash charts/gameplane/tests/mcp-server-rbac.sh standalone-compose: name: standalone Compose smoke diff --git a/changelog/unreleased/1046-mcp-namespace-scope.md b/changelog/unreleased/1046-mcp-namespace-scope.md new file mode 100644 index 000000000..e5a8797b2 --- /dev/null +++ b/changelog/unreleased/1046-mcp-namespace-scope.md @@ -0,0 +1,10 @@ +# Breaking: MCP server no longer reads every namespace + +The break-glass MCP server (`mcpServer.enabled`) no longer has a cluster-wide +ClusterRole for Pods, Events and pod logs. The chart removes the old +`-mcp-server-read` ClusterRole and ClusterRoleBinding on upgrade. Break-glass +reads now cover only the release namespace and the managed game namespaces, through +namespaced Roles. A ClusterRole remains for GameTemplate, Module and ModuleSource only. +After upgrading, use a personal MCP token (`/users/me/mcp-tokens`) for per-user reads +across clusters. See [`docs/security.md`](docs/security.md#mcp-server-optional). +[PR #1046](https://github.com/GameplanePanel/Gameplane/pull/1046) diff --git a/charts/gameplane/templates/mcp-server.yaml b/charts/gameplane/templates/mcp-server.yaml index 40051e993..2e7cba769 100644 --- a/charts/gameplane/templates/mcp-server.yaml +++ b/charts/gameplane/templates/mcp-server.yaml @@ -1,12 +1,26 @@ {{- if not .Values.api.standalone }} {{- if .Values.mcpServer.enabled }} +{{- $gameNamespaces := include "gameplane.operatorGameNamespaces" . | fromJsonArray }} +{{- $scopeNamespaces := uniq (concat (list .Release.Namespace) $gameNamespaces) }} # Optional, strictly read-only MCP server. It speaks MCP (JSON-RPC 2.0) over # stdio only, never a network port, so there is no Service here — reach a # running instance with: # kubectl exec -i deploy/gameplane-mcp-server -n {{ .Release.Namespace }} -- /mcp-server serve # The container's own long-running process runs the `idle` subcommand (no # args); it does nothing besides keep a container alive for `kubectl exec` -# to attach to. Each `serve` session gets its own isolated read-only client. +# to attach to. +# +# This is break-glass access only: `kubectl exec` requires cluster exec rights, +# so no Gameplane user check happens on this path. Per-user MCP access runs on +# the user's own machine and reads through the API with a personal token, so +# it needs no RBAC here. +# +# Scope is namespaced and read-only (get/list/watch, no write verb anywhere in +# this file). The server reads only the release namespace and the managed game +# namespaces, through namespaced Roles. The single cluster-scoped grant is a +# read-only ClusterRole for GameTemplate, Module and ModuleSource, which are +# cluster-scoped kinds. See mcp-server/README.md for the read-only guarantee +# this mirrors in code. apiVersion: v1 kind: ServiceAccount metadata: @@ -14,41 +28,68 @@ metadata: namespace: {{ .Release.Namespace }} labels: {{- include "gameplane.labels" . | nindent 4 }} --- -# Cluster-wide, read-only: get/list/watch only, on exactly the resources the -# server's tools read. No write verb (create/update/patch/delete) appears -# anywhere in this file — see mcp-server/README.md for the read-only -# guarantee this mirrors in code (Client in mcp-server/internal/kube/client.go exposes no -# mutating method, and main_test.go asserts no tool is registered that could -# use one). apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: - name: {{ .Release.Name }}-mcp-server-read + name: {{ .Release.Name }}-mcp-server-catalog-read labels: {{- include "gameplane.labels" . | nindent 4 }} rules: - apiGroups: ["gameplane.local"] - resources: [gameservers, gametemplates, backups, backupschedules, restores, modules, modulesources] + resources: [gametemplates, modules, modulesources] verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ .Release.Name }}-mcp-server-catalog-read + labels: {{- include "gameplane.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ .Release.Name }}-mcp-server-catalog-read +subjects: + - kind: ServiceAccount + name: gameplane-mcp-server + namespace: {{ .Release.Namespace }} +{{- range $namespace := $scopeNamespaces }} +--- +# Namespaced read-only Role for one in-scope namespace. A game namespace also +# gets the GameServer, backup and restore reads; the release namespace gets +# them only when it is also a game namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $.Release.Name }}-mcp-server-read + namespace: {{ $namespace }} + labels: {{- include "gameplane.labels" $ | nindent 4 }} +rules: - apiGroups: [""] resources: [pods, events] verbs: [get, list, watch] - apiGroups: [""] resources: [pods/log] verbs: [get] +{{- if has $namespace $gameNamespaces }} + - apiGroups: ["gameplane.local"] + resources: [gameservers, backups, backupschedules, restores] + verbs: [get, list, watch] +{{- end }} --- apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding +kind: RoleBinding metadata: - name: {{ .Release.Name }}-mcp-server-read - labels: {{- include "gameplane.labels" . | nindent 4 }} + name: {{ $.Release.Name }}-mcp-server-read + namespace: {{ $namespace }} + labels: {{- include "gameplane.labels" $ | nindent 4 }} roleRef: apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: {{ .Release.Name }}-mcp-server-read + kind: Role + name: {{ $.Release.Name }}-mcp-server-read subjects: - kind: ServiceAccount name: gameplane-mcp-server - namespace: {{ .Release.Namespace }} + namespace: {{ $.Release.Namespace }} +{{- end }} --- apiVersion: apps/v1 kind: Deployment @@ -80,6 +121,9 @@ spec: # No ports, no probes: this container exposes no HTTP/TCP surface to # probe — its only interface is `kubectl exec -i ... -- /mcp-server # serve`, which Kubernetes doesn't have a probe verb for. + env: + - name: GAMEPLANE_MCP_NAMESPACES + value: {{ join "," $scopeNamespaces | quote }} resources: {{ toYaml .Values.mcpServer.resources | nindent 12 }} securityContext: allowPrivilegeEscalation: false diff --git a/charts/gameplane/tests/mcp-server-rbac.sh b/charts/gameplane/tests/mcp-server-rbac.sh new file mode 100755 index 000000000..bb2a89eae --- /dev/null +++ b/charts/gameplane/tests/mcp-server-rbac.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Render the MCP server RBAC and check that it stays namespaced, read-only and in scope. +set -euo pipefail +cd "$(dirname "$0")/../../.." +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT +helm template gameplane charts/gameplane --namespace gameplane-system \ + --set mcpServer.enabled=true --set 'operator.gameNamespaces={tenant-b}' > "$scratch/enabled.yaml" +helm template gameplane charts/gameplane --namespace gameplane-system \ + --set mcpServer.enabled=false > "$scratch/disabled.yaml" +python3 - "$scratch" <<'PY' +import pathlib,sys,yaml +root=pathlib.Path(sys.argv[1]) +SA='gameplane-mcp-server' +RELEASE_NS='gameplane-system' +EXPECTED_NS=['gameplane-system','gameplane-games','tenant-b'] +READ_VERBS={'get','list','watch'} + +def docs(path): + return [d for d in yaml.safe_load_all(path.read_text()) if d] + +def is_sa_subject(subject): + return subject.get('kind')=='ServiceAccount' and subject.get('name')==SA + +def sa_objects(all_docs): + return [d for d in all_docs if d.get('kind') in ('ClusterRoleBinding','RoleBinding') + and any(is_sa_subject(s) for s in d.get('subjects') or [])] + +enabled=docs(root/'enabled.yaml') +# Map each SA binding to the role it references. +bound=[] +for b in sa_objects(enabled): + ref=b['roleRef'] + bound.append((b['kind'], b['metadata'].get('namespace'), ref['kind'], ref['name'])) + +def rules_for(kind, name, namespace=None): + for d in enabled: + if d.get('kind')==kind and d['metadata']['name']==name: + if kind=='Role' and d['metadata'].get('namespace')!=namespace: + continue + return d.get('rules') or [] + raise AssertionError(f'missing {kind} {name} {namespace}') + +# 1. No ClusterRole bound to the SA grants pods, events or pods/log. +for bkind, bns, rkind, rname in bound: + if rkind!='ClusterRole': + continue + for rule in rules_for('ClusterRole', rname): + resources=set(rule.get('resources') or []) + assert not resources & {'pods','events','pods/log'}, (rname, rule) + +# 2. Catalog ClusterRole has exactly gametemplates, modules, modulesources. +catalog=[b for b in bound if b[0]=='ClusterRoleBinding' and b[2]=='ClusterRole'] +assert len(catalog)==1, catalog +catalog_rules=rules_for('ClusterRole', catalog[0][3]) +assert len(catalog_rules)==1, catalog_rules +assert set(catalog_rules[0]['resources'])=={'gametemplates','modules','modulesources'}, catalog_rules +assert catalog_rules[0]['apiGroups']==['gameplane.local'], catalog_rules + +# 3. Namespaced Roles with the expected name exist and are bound to the SA, once per namespace. +role_ns=sorted(ns for bkind, ns, rkind, rname in bound + if bkind=='RoleBinding' and rkind=='Role' and rname=='gameplane-mcp-server-read') +assert role_ns==sorted(EXPECTED_NS), role_ns +# Every RoleBinding for the SA, whatever role it names, stays inside the scope. +stray=[(ns, rname) for bkind, ns, rkind, rname in bound if bkind=='RoleBinding' and ns not in EXPECTED_NS] +assert not stray, stray +for ns in EXPECTED_NS: + rules_for('Role','gameplane-mcp-server-read',ns) + +# 4. No rule bound to the SA has a verb other than get/list/watch (pods/log allows get only). +for bkind, bns, rkind, rname in bound: + for rule in rules_for(rkind, rname, bns if rkind=='Role' else None): + verbs=set(rule.get('verbs') or []) + assert verbs<=READ_VERBS, (rname, rule) + if set(rule.get('resources') or [])=={'pods/log'}: + assert verbs=={'get'}, rule + +# 5. Deployment env lists exactly the in-scope namespaces. +deployments=[d for d in enabled if d.get('kind')=='Deployment' and d['metadata']['name']=='gameplane-mcp-server'] +assert len(deployments)==1 +env={e['name']:e.get('value') for e in deployments[0]['spec']['template']['spec']['containers'][0].get('env') or []} +assert sorted(env.get('GAMEPLANE_MCP_NAMESPACES','').split(','))==sorted(EXPECTED_NS), env + +# 6. Disabled: no object references the SA. +disabled=docs(root/'disabled.yaml') +leftovers=[(d['kind'], d['metadata']['name']) for d in disabled + if d.get('kind') in ('ServiceAccount','Deployment','Role','RoleBinding','ClusterRole','ClusterRoleBinding') + and ('mcp-server' in d['metadata']['name'] or d['metadata']['name']==SA)] +assert not leftovers, leftovers +assert not sa_objects(disabled), sa_objects(disabled) +print('mcp-server RBAC scope ok') +PY diff --git a/docs/agent-architecture.md b/docs/agent-architecture.md index 979435352..010d37a91 100644 --- a/docs/agent-architecture.md +++ b/docs/agent-architecture.md @@ -61,6 +61,8 @@ This document is the **first stop** for AI agents modifying or extending Gamepla | Change the website | `website/AGENTS.md` (submodule) | | Add a DB migration | `api/specs.md`, `api/internal/db/migrations/README.md` | | Change CI or a workflow | `docs/contributing.md` ("CI and workflows", "How CI picks tests") | +| Change personal MCP tokens or the MCP read routes (`api/internal/auth/mcptokens.go`, `api/internal/handlers/mcp_tokens.go`, `api/internal/handlers/pods.go`) | `api/specs.md`, `docs/security.md` ("mcp-server (optional)") | +| Change MCP server RBAC or namespace scope (`charts/gameplane/templates/mcp-server.yaml`, `charts/gameplane/tests/mcp-server-rbac.sh`) | `docs/security.md` ("mcp-server (optional)"), `mcp-server/specs.md` | | Decide where new code goes | `docs/layout.md` | ## How to use this index diff --git a/docs/multicluster-ui.md b/docs/multicluster-ui.md index 7b7402c90..7131c7561 100644 --- a/docs/multicluster-ui.md +++ b/docs/multicluster-ui.md @@ -85,3 +85,8 @@ Accounts, roles, audit and installation settings remain centrally managed. Their requests do not inherit the inventory selection. Combined panels manage the local module catalog; standalone panels require an explicit remote target for modules and sources. + +**MCP access.** Personal MCP tokens read through the API with the same per-cluster +grants as the dashboard. A session lists every cluster the user may read, and an +ungranted cluster answers like an unknown one. See +[`docs/security.md`](security.md#mcp-server-optional). diff --git a/docs/security.md b/docs/security.md index a6f5b47d2..8b9e21367 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1125,26 +1125,35 @@ Secret read. Without the grant, the API omits "used" and the dashboard shows ## mcp-server (optional) -The optional MCP server [optional] (`mcpServer.enabled`, see [`mcp-server/README.md`](https://github.com/GameplanePanel/mcp/blob/main/README.md)) -is strictly read-only — no tool it exposes can create, update, patch, -delete, or apply anything, enforced structurally (its tool handlers only -ever hold a client whose exported methods are List/Get-shaped) and by RBAC -(a ClusterRole granting only `get`/`list`/`watch`, plus `get` on -`pods/log`). - -That RBAC grant is **cluster-wide**, not scoped to `gameplane-games` or any -other single namespace: the server can list/read Pods, Events, and pod logs -in every namespace, including `kube-system` and any other workload's -namespace sharing the cluster. Pod logs in particular can surface secrets -an application logs at startup or during errors (API keys, connection -strings, stack traces) — Kubernetes has no mechanism to redact those. -Combined with write-freedom and opt-in, admin-only installation -(`mcpServer.enabled` plus whatever gates `kubectl exec` access to the -`gameplane-mcp-server` pod), this is an accepted tradeoff, not an oversight -— but install it knowing that anyone who can reach a `serve` session gets -read access to cluster-wide pod state and logs, not just Gameplane-managed -namespaces. If that blast radius is wider than acceptable for a given -cluster, don't enable `mcpServer` there. +The optional MCP server (`mcpServer.enabled`, see [`mcp-server/README.md`](https://github.com/GameplanePanel/mcp/blob/main/README.md)) +is strictly read-only: no tool it exposes can create, update, patch, delete, +or apply anything. It runs in one of two modes. + +- **Per-user mode.** A user creates a personal MCP token in the dashboard and + runs the MCP client on their own machine. The client reads only through the + API, with the user's roles, namespace grants and per-cluster grants. The API + accepts an MCP token only for `GET` on a fixed list of read routes. The + server itself holds no Kubernetes permissions in this mode, so the RBAC + described below does not apply to it. +- **Break-glass mode.** `kubectl exec -i deploy/gameplane-mcp-server -n -- /mcp-server serve`. + Access is admin-only by virtue of `kubectl exec` rights; no Gameplane user + check happens on this path. The pod's ServiceAccount has namespaced Roles + only, in the release namespace and in each managed game namespace, granting + `get`/`list`/`watch` on Pods, Events and `pods/log` (`get`), and + `get`/`list`/`watch` on GameServers, backups, backup schedules and restores + in the game namespaces. Its one ClusterRole covers GameTemplate, Module and + ModuleSource only, which are cluster-scoped kinds. No other cluster-wide + read is granted, and no write verb appears anywhere. + +Break-glass reads therefore cover the release namespace and the managed game +namespaces, not every namespace in the cluster. Pod logs can still surface +secrets an application logs at startup or during errors (API keys, connection +strings, stack traces), and Kubernetes has no mechanism to redact those. Within +the scoped namespaces this is an accepted tradeoff for an opt-in, admin-only +install (`mcpServer.enabled` plus whatever gates `kubectl exec` access to the +`gameplane-mcp-server` pod). Anyone who can reach a break-glass `serve` session +can read pods, events and logs in those namespaces. If that is wider than +acceptable for a cluster, don't enable `mcpServer` there. ## Secrets diff --git a/mcp-server b/mcp-server index 3e070f858..59524cef4 160000 --- a/mcp-server +++ b/mcp-server @@ -1 +1 @@ -Subproject commit 3e070f858569ef1ff006fefb23d8ebc9c6f8659c +Subproject commit 59524cef456ecbb2d212cbf79fd8473f8fc2c196 diff --git a/test/e2e/buckets.sh b/test/e2e/buckets.sh index 882fe329e..aae7a9502 100755 --- a/test/e2e/buckets.sh +++ b/test/e2e/buckets.sh @@ -433,10 +433,14 @@ EOF # optional-components owns its cluster: TestOptionalComponents_Lifecycle runs # `helm upgrade --reuse-values` to enable the MCP server and the audit-syslog -# bridge, so it is the bucket's only test. Login budget: 2 (one admin, one -# restricted user). +# bridge, so it owns the bucket's cluster. Login budget: 2 (one admin, one +# restricted user). TestOptionalComponents_MCPScope is the bucket's other test: +# it is non-parallel, so Go runs it before the parallel lifecycle test resumes, +# it re-enables the MCP server itself, scales the API to 0 and back, disables +# the MCP server again on cleanup, and makes no logins. bucket_optional_components() { cat <<'EOF' TestOptionalComponents_Lifecycle +TestOptionalComponents_MCPScope EOF } diff --git a/test/e2e/optional_components_scope_e2e_test.go b/test/e2e/optional_components_scope_e2e_test.go new file mode 100644 index 000000000..908c94b27 --- /dev/null +++ b/test/e2e/optional_components_scope_e2e_test.go @@ -0,0 +1,186 @@ +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ocMCPSA is the MCP server's service account as kubectl auth can-i expects it. +const ocMCPSA = "system:serviceaccount:gameplane-system:gameplane-mcp-server" + +// ocCanI asks the API server whether the MCP server's service account may +// perform the action. kubectl auth can-i exits 1 for "no", so the verdict is +// read from the last output line; anything other than yes or no fails the test. +func ocCanI(ctx context.Context, t *testing.T, args ...string) bool { + t.Helper() + full := append([]string{"auth", "can-i"}, args...) + full = append(full, "--as="+ocMCPSA) + out, err := envInstance.Kubectl(ctx, full...) + lines := strings.Split(strings.TrimSpace(out), "\n") + verdict := strings.TrimSpace(lines[len(lines)-1]) + switch verdict { + case "yes": + return true + case "no": + return false + default: + t.Fatalf("kubectl auth can-i %v: unexpected output %q (err=%v)", args, out, err) + return false + } +} + +// ocDeployReady reports whether the named Deployment has at least want ready replicas. +func ocDeployReady(ctx context.Context, ns, name string, want int32) func() (bool, string) { + return func() (bool, string) { + d, err := envInstance.K8s.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return false, err.Error() + } + return d.Status.ReadyReplicas >= want, fmt.Sprintf("%s readyReplicas=%d want>=%d", name, d.Status.ReadyReplicas, want) + } +} + +// TestOptionalComponents_MCPScope checks the break-glass MCP server's +// namespaced RBAC and its scope guard, then proves it still answers in the +// release namespace when the API is down. It runs sequentially on the +// optional-components bucket cluster after the lifecycle test: it enables the +// MCP server itself, scales the API to 0 and back, and makes no logins. +func TestOptionalComponents_MCPScope(t *testing.T) { + ctx := context.Background() + + // Go runs this non-parallel test before the parallel lifecycle test resumes, + // and the lifecycle test expects the MCP server disabled on entry, so turn it + // back off once this test is done. + t.Cleanup(func() { + cctx := context.Background() + helmUpgradeReuse(cctx, t, "mcpServer.enabled=false") + envInstance.Eventually(t, 3*time.Minute, func() (bool, string) { + _, err := envInstance.K8s.AppsV1().Deployments(ocNS).Get(cctx, "gameplane-mcp-server", metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return true, "gameplane-mcp-server removed" + } + return false, fmt.Sprintf("gameplane-mcp-server still present (err=%v)", err) + }) + }) + + helmUpgradeReuse(ctx, t, "mcpServer.enabled=true") + envInstance.Eventually(t, 3*time.Minute, ocDeployReady(ctx, ocNS, "gameplane-mcp-server", 1)) + + // Namespaced reads only: pods and logs outside the managed namespaces are denied. + if ocCanI(ctx, t, "list", "pods", "-n", "kube-system") { + t.Fatalf("mcp service account: list pods in kube-system must be denied") + } + if ocCanI(ctx, t, "get", "pods/log", "-n", "kube-system") { + t.Fatalf("mcp service account: get pods/log in kube-system must be denied") + } + if !ocCanI(ctx, t, "list", "pods", "-n", ocGamesNS) { + t.Fatalf("mcp service account: list pods in %s must be allowed", ocGamesNS) + } + if !ocCanI(ctx, t, "list", "pods", "-n", ocNS) { + t.Fatalf("mcp service account: list pods in %s must be allowed", ocNS) + } + if !ocCanI(ctx, t, "list", "gametemplates.gameplane.local") { + t.Fatalf("mcp service account: list gametemplates must be allowed (catalog ClusterRole)") + } + if ocCanI(ctx, t, "create", "gameservers.gameplane.local", "-n", ocGamesNS) { + t.Fatalf("mcp service account: create gameservers must be denied (read-only)") + } + + // The old cluster-wide ClusterRole must be gone. + _, err := envInstance.K8s.RbacV1().ClusterRoles().Get(ctx, "gameplane-mcp-server-read", metav1.GetOptions{}) + if !apierrors.IsNotFound(err) { + t.Fatalf("clusterrole gameplane-mcp-server-read: want NotFound, got err=%v", err) + } + + // Scope guard inside the MCP server: default namespace listing skips + // kube-system, and an explicit out-of-scope namespace is refused. + m := ocStartMCP(ctx, t) + defer m.close() + m.call(t, 1, "initialize", map[string]any{ + "protocolVersion": "2025-06-18", + "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "gameplane-e2e", "version": "1"}, + }) + m.notify(t, "notifications/initialized") + + defaultRes := m.call(t, 2, "tools/call", map[string]any{ + "name": "list_pods", + "arguments": map[string]any{}, + }) + if isErr, _ := defaultRes["isError"].(bool); isErr { + t.Fatalf("list_pods without arguments returned isError: %s", ocTextOf(defaultRes)) + } + if text := ocTextOf(defaultRes); strings.Contains(text, `"namespace": "kube-system"`) || strings.Contains(text, `"namespace":"kube-system"`) { + t.Fatalf("list_pods without arguments leaked kube-system pods") + } + + outRes := m.call(t, 3, "tools/call", map[string]any{ + "name": "list_pods", + "arguments": map[string]any{"namespace": "kube-system"}, + }) + if isErr, _ := outRes["isError"].(bool); !isErr { + t.Fatalf("list_pods kube-system: want isError=true, got %v", outRes) + } + if text := ocTextOf(outRes); !strings.Contains(text, "not in scope") { + t.Fatalf("list_pods kube-system: want %q in error text, got %q", "not in scope", text) + } + + // Break-glass without the API: the MCP server reads the release namespace + // directly, so it must answer while gameplane-api has no replicas. + apiScale, err := envInstance.K8s.AppsV1().Deployments(ocNS).GetScale(ctx, "gameplane-api", metav1.GetOptions{}) + if err != nil { + t.Fatalf("get scale gameplane-api: %v", err) + } + apiReplicas := apiScale.Spec.Replicas + t.Cleanup(func() { + cctx := context.Background() + s, err := envInstance.K8s.AppsV1().Deployments(ocNS).GetScale(cctx, "gameplane-api", metav1.GetOptions{}) + if err != nil { + t.Errorf("get scale gameplane-api for restore: %v", err) + return + } + s.Spec.Replicas = apiReplicas + if _, err := envInstance.K8s.AppsV1().Deployments(ocNS).UpdateScale(cctx, "gameplane-api", s, metav1.UpdateOptions{}); err != nil { + t.Errorf("restore gameplane-api replicas to %d: %v", apiReplicas, err) + return + } + envInstance.Eventually(t, 3*time.Minute, ocDeployReady(cctx, ocNS, "gameplane-api", apiReplicas)) + }) + + apiScale.Spec.Replicas = 0 + if _, err := envInstance.K8s.AppsV1().Deployments(ocNS).UpdateScale(ctx, "gameplane-api", apiScale, metav1.UpdateOptions{}); err != nil { + t.Fatalf("scale gameplane-api to 0: %v", err) + } + envInstance.Eventually(t, 3*time.Minute, func() (bool, string) { + d, err := envInstance.K8s.AppsV1().Deployments(ocNS).Get(ctx, "gameplane-api", metav1.GetOptions{}) + if err != nil { + return false, err.Error() + } + return d.Status.Replicas == 0, fmt.Sprintf("gameplane-api replicas=%d", d.Status.Replicas) + }) + + bg := ocStartMCP(ctx, t) + defer bg.close() + bg.call(t, 1, "initialize", map[string]any{ + "protocolVersion": "2025-06-18", + "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "gameplane-e2e", "version": "1"}, + }) + bg.notify(t, "notifications/initialized") + + sysRes := bg.call(t, 2, "tools/call", map[string]any{ + "name": "list_pods", + "arguments": map[string]any{"namespace": ocNS}, + }) + if isErr, _ := sysRes["isError"].(bool); isErr { + t.Fatalf("break-glass list_pods %s with API scaled to 0: isError: %s", ocNS, ocTextOf(sysRes)) + } +}