From 037af23072d7fd41cea92e66599cb8a8ac5d4d23 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:55:05 +0000 Subject: [PATCH 1/3] feat: per-user mode through the Gameplane API and namespace-scoped break-glass serve gains a per-user mode: with GAMEPLANE_PANEL_URL and a personal GAMEPLANE_MCP_TOKEN it reads through the Gameplane API as the token's user, GET only, across every cluster the user may read. Without a panel URL it keeps reading Kubernetes directly, limited to the namespaces in GAMEPLANE_MCP_NAMESPACES. Tool handlers now take a reader.Reader that both clients implement. Tools gain optional cluster and server inputs. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- README.md | 219 ++++++++--- fixadvice.go | 6 +- internal/kube/allowlist_test.go | 340 +++++++++++++++++ internal/kube/client.go | 278 ++++++++++++-- internal/panel/client.go | 630 ++++++++++++++++++++++++++++++++ internal/panel/client_test.go | 600 ++++++++++++++++++++++++++++++ internal/panel/fanout.go | 181 +++++++++ internal/panel/fanout_test.go | 187 ++++++++++ internal/panel/source_test.go | 64 ++++ internal/reader/reader.go | 45 +++ main.go | 133 +++++-- panel_invariants_test.go | 46 +++ specs.md | 221 ++++++----- tools.go | 42 ++- 14 files changed, 2766 insertions(+), 226 deletions(-) create mode 100644 internal/kube/allowlist_test.go create mode 100644 internal/panel/client.go create mode 100644 internal/panel/client_test.go create mode 100644 internal/panel/fanout.go create mode 100644 internal/panel/fanout_test.go create mode 100644 internal/panel/source_test.go create mode 100644 internal/reader/reader.go create mode 100644 panel_invariants_test.go diff --git a/README.md b/README.md index 66eb0e5..c315a35 100644 --- a/README.md +++ b/README.md @@ -3,41 +3,132 @@ > This repository is checked out as the `mcp-server/` submodule of [GameplanePanel/Gameplane](https://github.com/GameplanePanel/Gameplane). Paths such as `docs/`, `operator/`, `api/`, `charts/` and `web/` below refer to that repository. The **mcp-server** [optional] is a strictly **read-only** [Model Context Protocol](https://modelcontextprotocol.io/) -(MCP) server for Gameplane clusters. It lets an AI assistant read cluster -state — 7 of Gameplane's 9 CRDs (not Cluster or NetworkCapture), Pods, Events, and pod logs — and get a -suggested fix as plain text (YAML and/or `kubectl` commands) for a human -operator to review and run. +(MCP) server for Gameplane. It lets an AI assistant read state — 7 of +Gameplane's 9 CRDs (not Cluster or NetworkCapture), Pods, Events, and pod +logs — and get a suggested fix as plain text (YAML and/or `kubectl` commands) +for a human operator to review and run. This repository is checked out as the `mcp-server/` submodule of [GameplanePanel/Gameplane](https://github.com/GameplanePanel/Gameplane), which builds and ships the image and Helm chart (`mcpServer.enabled`). Lint, tests, coverage and govulncheck for this module run in this repository's own CI. +## Two modes + +The server runs in one of two modes, chosen by `serve` at start-up. Both use +the same tools and the same read-only interface. + +### Per-user mode (recommended) + +Set `GAMEPLANE_PANEL_URL` and the server reads through the Gameplane API as +the user who owns the token. Results follow that user's roles, namespace +grants and per-cluster grants, across every cluster the user may read. The +process needs no Kubernetes credentials. + +1. In the Gameplane dashboard, open **Settings → MCP tokens** and create a + token. Tokens start with `gpmcp_`. +2. Start the server: + + ```sh + GAMEPLANE_PANEL_URL=https:// GAMEPLANE_MCP_TOKEN=gpmcp_… mcp-server serve + ``` + + Or with the image: + + ```sh + docker run --rm -i -e GAMEPLANE_PANEL_URL -e GAMEPLANE_MCP_TOKEN \ + ghcr.io/gameplanepanel/gameplane/mcp-server:edge serve + ``` + +3. Point your MCP client at it. For example: + + ```json + { + "mcpServers": { + "gameplane": { + "command": "mcp-server", + "args": ["serve"], + "env": { + "GAMEPLANE_PANEL_URL": "https://panel.example.com", + "GAMEPLANE_MCP_TOKEN": "gpmcp_…" + } + } + } + } + ``` + + The Docker form runs the image instead: set `"command": "docker"` and + `"args": ["run", "--rm", "-i", "-e", "GAMEPLANE_PANEL_URL", "-e", "GAMEPLANE_MCP_TOKEN", "ghcr.io/gameplanepanel/gameplane/mcp-server:edge", "serve"]`, + keeping the same `env` block. + +Options for `serve` (each also has an environment variable): + +- `--panel-url` (`GAMEPLANE_PANEL_URL`) — the Gameplane API base URL. Setting + it selects per-user mode. The URL must use `https`; `http` is accepted only + for `localhost` or a loopback address. +- `--panel-ca` (`GAMEPLANE_PANEL_CA`) — a PEM CA bundle added to the system + roots, for a panel served with a private certificate authority. +- `GAMEPLANE_MCP_TOKEN` — the MCP token. Read from the environment only (there + is no flag). Required when `GAMEPLANE_PANEL_URL` is set; it must start with + `gpmcp_`. The token is never written to logs or error messages. + +Every request the server makes is a `GET`. A token with a revoked or expired +status gets a "not authenticated" error on the next call. + +### Break-glass mode (admin only) + +Leave `GAMEPLANE_PANEL_URL` unset and `serve` reads the cluster directly with +the Kubernetes credentials of the process (in-cluster ServiceAccount, or the +kubeconfig). It is for administrators debugging the cluster, and it works +while the Gameplane API is down. + +- There is no Gameplane user check. Anyone who can `kubectl exec` into the + `gameplane-mcp-server` pod can use it. +- It reads the **local cluster** only. Passing a `cluster` argument is an + error in this mode. +- Reads are limited to an allow-list of namespaces when `GAMEPLANE_MCP_NAMESPACES` + is set (a comma-separated list): in the chart, the release namespace plus the + managed game namespaces. Unset means unrestricted, and the process's own + Kubernetes permissions apply. + +```sh +kubectl exec -i deploy/gameplane-mcp-server -n gameplane-system -- /mcp-server serve +``` + +## Security model + It **never** creates, updates, patches, deletes, or applies anything. That is a hard invariant, held by two layers: 1. **The handler boundary**: every MCP tool handler (`tools.go`, - `fixadvice.go`) lives in `package main` and takes a `*kube.Client` - (`internal/kube/client.go`). That type's only exported methods are - List/Get-shaped (`ListCRD`, `GetCRD`, `ListPods`, `GetPod`, - `ListEvents`, `PodLogs`); the typed and dynamic Kubernetes clientsets - behind it are **unexported fields** on `Client`, defined in - `internal/kube`. A handler that holds only the `*kube.Client` therefore - cannot call `Create`/`Update`/`Delete`/`Patch`/`Apply` through it. The - boundary is on the `*kube.Client`, not on `package main`: `runServe` - loads the `*rest.Config` itself, so keeping handlers on the - `*kube.Client` (and having no mutating call site anywhere in the - module) is a code convention, not a compile-time guarantee. - `main_test.go`'s `TestClientHasNoMutatingMethods` is a tripwire on top - of that (it reflects over `kube.Client`'s method set so a future - mutating method added to `internal/kube` fails a test immediately). -2. **By RBAC**: the Kubernetes ClusterRole the chart's `mcpServer.enabled` - toggle installs grants only `get`/`list`/`watch` (plus `get` on - `pods/log`) — there is no `create`/`update`/`patch`/`delete` verb in it. - This is the **authoritative** layer and the only one that stops - mutation by any code in the process: the API server rejects a write - from the ServiceAccount this pod runs as, whatever client makes it. A - standalone run against a kubeconfig (see below) has that kubeconfig + `fixadvice.go`) lives in `package main` and takes a `reader.Reader` + (`internal/reader`). Both implementations expose only List/Get-shaped + methods (`ListCRD`, `GetCRD`, `ListPods`, `GetPod`, `ListEvents`, + `PodLogs`): + - the break-glass `*kube.Client` (`internal/kube`), whose typed and dynamic + clientsets are **unexported fields**; + - the per-user `*panel.Client` (`internal/panel`), which builds every + request in one helper that issues only `GET`. + + A handler that holds a `reader.Reader` therefore cannot call + `Create`/`Update`/`Delete`/`Patch`/`Apply` through it. The boundary is a + code convention enforced by the method sets, not a compile-time guarantee: + `runServe` loads the `*rest.Config` itself. Tripwires are + `main_test.go`'s `TestClientHasNoMutatingMethods`, `panel_invariants_test.go`'s + `TestPanelClientHasNoMutatingMethods`, and `internal/panel/source_test.go`, + which fails if the panel package contains any HTTP method other than GET. +2. **By RBAC or by the API**: + - **Break-glass**: the Helm chart's `mcpServer.enabled` ServiceAccount holds + only `get`/`list`/`watch` (plus `get` on `pods/log`). Those grants are + namespaced Roles in the release namespace and in each managed game + namespace, plus a ClusterRole for the cluster-scoped kinds. See + [RBAC scope](#rbac-scope). There is no `create`/`update`/`patch`/`delete` + verb anywhere in them. This is the **authoritative** layer for break-glass. + - **Per-user**: the process holds no Kubernetes permissions. The Gameplane + API applies the user's roles, and it accepts only `GET` from an MCP token. + + In both modes the API server or the Gameplane API rejects a write, whatever + client makes it. A standalone run against a kubeconfig has that kubeconfig user's permissions instead, so point it at a read-only identity. A third, cosmetic layer: every tool this server installs (`tools.go`) @@ -46,24 +137,6 @@ carries the MCP spec's `readOnlyHint: true` annotation, and `main_test.go`'s contains a mutating verb — this makes the guarantee visible to MCP clients, it doesn't enforce it. -### RBAC blast radius - -The `get`/`list`/`watch` ClusterRole above is **cluster-wide**: it is not -scoped to `gameplane-games` or any other single namespace, so it can read -Pods, Events, and pod logs in every namespace the cluster has, including -`kube-system` and any other workload's namespace. Pod logs in particular -can surface application secrets that a container logs at startup (API keys, -connection strings, etc.) — Kubernetes doesn't distinguish "log line" from -"log line containing a secret". This is an accepted tradeoff (the server is -opt-in, admin-installed via `mcpServer.enabled`, and write-free even so), -but install it with that blast radius in mind: anyone who can -`kubectl exec` into the `gameplane-mcp-server` pod (or otherwise reach an -MCP client already wired to it) can read logs and object state for -*any* pod in the cluster, not just Gameplane-managed ones. If that's wider -than you want, don't enable `mcpServer` on a cluster that also runs -unrelated, more sensitive workloads. See [`docs/security.md`](https://github.com/GameplanePanel/Gameplane/blob/master/docs/security.md) for the rest of -the threat model. - ## Tools | Tool | Reads | @@ -76,6 +149,28 @@ the threat model. | `get_pod_logs` | A bounded tail (default 200 lines, capped at 5000) of a container's logs; retains the newest 256 KiB from the complete response, with a notice when truncated | | `propose_fix` | Given a resource reference + a free-text symptom, returns suggested YAML/kubectl text, grounded in a best-effort read of the resource's current status. Never applies anything itself. | +Every tool except `propose_fix` also takes these optional arguments: + +- `cluster` — a registered cluster ID. **Per-user mode only**; break-glass + mode returns an error for any value. With it empty, list tools cover every + cluster the user may read, and each returned item is annotated + `gameplane.local/cluster`. Get tools and log reads use the local cluster + when `cluster` is empty. +- `server` — a GameServer name. **Per-user mode only**; it is ignored in + break-glass mode. It is accepted by `list_pods`, `list_events` and + `get_pod_logs`. In per-user mode it routes pod, event and log reads through + that server (`/servers/{name}/…`). `get_pod_logs` requires it for game + server pods. Without it, logs are readable only for the API and operator + system pods. + +`propose_fix` accepts `cluster` but not `server`. Its reads follow the same +rules as the get tools. + +In per-user mode, a cluster that fails for any reason other than 403 or 404 +during a list is reported in the response: its `metadata.resourceVersion` +(or the list's `resourceVersion`) reads `unavailable clusters: `. Clusters +that return 403 or 404 are skipped silently. + ## Transport: stdio only, no network port This server speaks MCP (JSON-RPC 2.0) over stdio — it never opens an HTTP @@ -84,26 +179,18 @@ or TCP port. It has two subcommands: - `idle` (default, no args) — block until terminated. This is what the bundled Helm Deployment runs as its long-lived container process, purely so there is always a live container to `kubectl exec` into. -- `serve` — run one MCP stdio session against the real cluster. Point an - MCP host's launcher (e.g. Claude Desktop / Claude Code's MCP config, or - any other MCP-compatible client) at: - - ```sh - kubectl exec -i deploy/gameplane-mcp-server -n gameplane-system -- /mcp-server serve - ``` - - Each `kubectl exec -i` spawns an independent, isolated `serve` process - sharing the pod's ServiceAccount credentials and network access — - concurrent sessions from different users/hosts don't interfere with each - other or with the idle placeholder process. +- `serve` — run one MCP stdio session. Flags and environment are listed under + [Two modes](#two-modes). Each session is independent, so concurrent sessions + from different users or hosts don't interfere with each other or with the + idle placeholder process. Diagnostics go to stderr; stdout is the MCP stream. ## Run via the Helm chart Set `mcpServer.enabled=true`. The chart deploys a Deployment (no Service — -there is no network port to expose), a dedicated ServiceAccount, and a -cluster-scoped, read-only ClusterRole/ClusterRoleBinding (`get`/`list`/ -`watch` only, on 7 of Gameplane's 9 CRDs (not Cluster or NetworkCapture) plus core Pods/Events, and `get` on -the `pods/log` subresource). +there is no network port to expose) and a dedicated ServiceAccount. It runs +break-glass mode: `serve` reads the local cluster with that ServiceAccount. +The chart does not grant cluster-wide reads of pods, events or pod logs. See +[RBAC scope](#rbac-scope). ```yaml mcpServer: @@ -114,6 +201,17 @@ mcpServer: limits: { cpu: 200m, memory: 128Mi } ``` +## RBAC scope + +- **Per-user mode** needs no Kubernetes permissions. The API applies the + token's user, namespace grants and per-cluster grants. +- **Break-glass mode** uses the chart's read-only grants. These are namespaced + Roles in the release namespace and in each managed game namespace. Those + Roles cover pods, events and `pods/log`, and in game namespaces also + GameServer, Backup, BackupSchedule and Restore. A ClusterRole is granted only + for the cluster-scoped kinds: GameTemplate, Module and ModuleSource. Every + grant is `get`/`list`/`watch`, except `get` on `pods/log`. + ## Run standalone (against a kubeconfig) ```sh @@ -123,6 +221,9 @@ KUBECONFIG=~/.kube/config docker run --rm -i \ ghcr.io/gameplanepanel/gameplane/mcp-server:edge serve ``` +This runs break-glass mode with `GAMEPLANE_MCP_NAMESPACES` unset, so reads are +unrestricted and the kubeconfig's own permissions apply. + `serve` builds its Kubernetes client via `ctrl.GetConfig()`, so it works in-cluster (via the pod's ServiceAccount) or locally against `KUBECONFIG`/ `~/.kube/config`, same as any other controller-runtime-based Gameplane diff --git a/fixadvice.go b/fixadvice.go index f809d66..e866191 100644 --- a/fixadvice.go +++ b/fixadvice.go @@ -12,7 +12,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "github.com/GameplanePanel/gameplane/mcp-server/internal/kube" + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" ) // fixRule matches a propose_fix symptom against a set of keywords and @@ -108,7 +108,7 @@ var fixRules = []fixRule{ // advice, and a generic diagnostics footer. It never mutates anything — // the resource read below is a plain Get, same as get_gameplane_resource/ // get_pod. -func buildFixSuggestion(ctx context.Context, c *kube.Client, in proposeFixInput) string { +func buildFixSuggestion(ctx context.Context, c reader.Reader, in proposeFixInput) string { var b strings.Builder fmt.Fprintf(&b, "Symptom: %s\n", in.Symptom) @@ -161,7 +161,7 @@ func matchFixRules(symptom string) []fixRule { // error (not found, unknown kind, no reference given) becomes a plain // sentence in the output rather than a tool error — propose_fix should // still return useful generic advice even without a valid resource ref. -func observeState(ctx context.Context, c *kube.Client, in proposeFixInput) string { +func observeState(ctx context.Context, c reader.Reader, in proposeFixInput) string { switch { case in.Kind == "" || in.Name == "": return " (no resource reference given — advice below is generic)\n" diff --git a/internal/kube/allowlist_test.go b/internal/kube/allowlist_test.go new file mode 100644 index 0000000..b17faae --- /dev/null +++ b/internal/kube/allowlist_test.go @@ -0,0 +1,340 @@ +package kube + +import ( + "context" + "errors" + "slices" + "testing" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" + k8sfake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +// seededAllowlistClient builds a Client over fake clientsets seeded with one +// pod, one event and one GameServer in each of "games", "games-2" and +// "secret", plus a cluster-scoped GameTemplate. It is restricted to allow. +func seededAllowlistClient(allow []string) *Client { + scheme := NewScheme() + typed := k8sfake.NewSimpleClientset( + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "mc-0", Namespace: "games"}}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "mc-1", Namespace: "games-2"}}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "secret-0", Namespace: "secret"}}, + &corev1.Event{ObjectMeta: metav1.ObjectMeta{Name: "ev-a", Namespace: "games"}, Reason: "Started"}, + &corev1.Event{ObjectMeta: metav1.ObjectMeta{Name: "ev-b", Namespace: "games-2"}, Reason: "Started"}, + &corev1.Event{ObjectMeta: metav1.ObjectMeta{Name: "ev-s", Namespace: "secret"}, Reason: "Started"}, + ) + dyn := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(scheme, gvrToListKindMap(), + newUnstructuredCRD("GameServer", "games", "mc", nil), + newUnstructuredCRD("GameServer", "games-2", "val", nil), + newUnstructuredCRD("GameServer", "secret", "hidden", nil), + newUnstructuredCRD("GameTemplate", "", "mc-java", nil), + ) + return NewFrom(typed, dyn, scheme).WithNamespaces(allow) +} + +// failListIn returns a reactor that fails list calls against namespace ns +// with err and lets every other call through to the fake's tracker. +func failListIn(ns string, err error) k8stesting.ReactionFunc { + return func(a k8stesting.Action) (bool, runtime.Object, error) { + if a.GetNamespace() == ns { + return true, nil, err + } + return false, nil, nil + } +} + +func podNames(list *corev1.PodList) []string { + out := make([]string, 0, len(list.Items)) + for _, p := range list.Items { + out = append(out, p.Name) + } + slices.Sort(out) + return out +} + +func eventNames(list *corev1.EventList) []string { + out := make([]string, 0, len(list.Items)) + for _, e := range list.Items { + out = append(out, e.Name) + } + slices.Sort(out) + return out +} + +func crdNames(list *unstructured.UnstructuredList) []string { + out := make([]string, 0, len(list.Items)) + for _, it := range list.Items { + out = append(out, it.GetName()) + } + slices.Sort(out) + return out +} + +func TestAllowlistRejectsOutOfScopeNamespace(t *testing.T) { + ctx := context.Background() + c := seededAllowlistClient([]string{"games", "games-2"}) + calls := []struct { + name string + call func() error + }{ + {"ListCRD", func() error { _, err := c.ListCRD(ctx, "GameServer", "secret", ""); return err }}, + {"GetCRD", func() error { _, err := c.GetCRD(ctx, "GameServer", "secret", "hidden"); return err }}, + {"ListPods", func() error { _, err := c.ListPods(ctx, "secret", ""); return err }}, + {"GetPod", func() error { _, err := c.GetPod(ctx, "secret", "secret-0"); return err }}, + {"ListEvents", func() error { _, err := c.ListEvents(ctx, "secret", ""); return err }}, + {"PodLogs", func() error { _, err := c.PodLogs(ctx, "secret", "secret-0", "", 0, false); return err }}, + } + for _, tt := range calls { + t.Run(tt.name, func(t *testing.T) { + if err := tt.call(); !errors.Is(err, ErrNamespaceNotInScope) { + t.Fatalf("want ErrNamespaceNotInScope, got %v", err) + } + }) + } +} + +func TestAllowlistRequiresNamespaceForSingleObjectReads(t *testing.T) { + ctx := context.Background() + c := seededAllowlistClient([]string{"games"}) + + if _, err := c.GetPod(ctx, "", "mc-0"); !errors.Is(err, errNamespaceRequired) { + t.Errorf("GetPod with empty namespace: want errNamespaceRequired, got %v", err) + } + if _, err := c.PodLogs(ctx, "", "mc-0", "", 0, false); !errors.Is(err, errNamespaceRequired) { + t.Errorf("PodLogs with empty namespace: want errNamespaceRequired, got %v", err) + } +} + +func TestAllowlistAllowsInScopeReads(t *testing.T) { + ctx := context.Background() + c := seededAllowlistClient([]string{"games", "games-2"}) + + pod, err := c.GetPod(ctx, "games", "mc-0") + if err != nil { + t.Fatalf("GetPod in scope: %v", err) + } + if pod.Name != "mc-0" { + t.Errorf("want pod mc-0, got %q", pod.Name) + } + + obj, err := c.GetCRD(ctx, "GameServer", "games-2", "val") + if err != nil { + t.Fatalf("GetCRD in scope: %v", err) + } + if obj.GetName() != "val" { + t.Errorf("want GameServer val, got %q", obj.GetName()) + } + + // Cluster-scoped kinds ignore the namespace argument, so the allow-list + // does not apply to them. + tmpl, err := c.ListCRD(ctx, "GameTemplate", "secret", "") + if err != nil { + t.Fatalf("ListCRD cluster-scoped kind: %v", err) + } + if got := crdNames(tmpl); !slices.Equal(got, []string{"mc-java"}) { + t.Errorf("want [mc-java], got %v", got) + } +} + +func TestAllowlistMergesOnlyAllowedNamespaces(t *testing.T) { + ctx := context.Background() + c := seededAllowlistClient([]string{"games", "games-2"}) + + pods, err := c.ListPods(ctx, "", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if got := podNames(pods); !slices.Equal(got, []string{"mc-0", "mc-1"}) { + t.Errorf("pods: want [mc-0 mc-1], got %v", got) + } + if pods.ResourceVersion != "" { + t.Errorf("pods: nothing was skipped, want empty resource version, got %q", pods.ResourceVersion) + } + + events, err := c.ListEvents(ctx, "", "") + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if got := eventNames(events); !slices.Equal(got, []string{"ev-a", "ev-b"}) { + t.Errorf("events: want [ev-a ev-b], got %v", got) + } + + servers, err := c.ListCRD(ctx, "GameServer", "", "") + if err != nil { + t.Fatalf("ListCRD GameServer: %v", err) + } + if got := crdNames(servers); !slices.Equal(got, []string{"mc", "val"}) { + t.Errorf("GameServers: want [mc val], got %v", got) + } +} + +func TestAllowlistSkipsMissingAndForbiddenNamespaces(t *testing.T) { + ctx := context.Background() + scheme := NewScheme() + typed := k8sfake.NewSimpleClientset( + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "mc-0", Namespace: "games"}}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "mc-1", Namespace: "games-2"}}, + &corev1.Event{ObjectMeta: metav1.ObjectMeta{Name: "ev-a", Namespace: "games"}, Reason: "Started"}, + &corev1.Event{ObjectMeta: metav1.ObjectMeta{Name: "ev-b", Namespace: "games-2"}, Reason: "Started"}, + ) + typed.PrependReactor("list", "pods", failListIn("locked", + apierrors.NewForbidden(schema.GroupResource{Resource: "pods"}, "", errors.New("denied")))) + typed.PrependReactor("list", "events", failListIn("locked", + apierrors.NewNotFound(schema.GroupResource{Resource: "events"}, ""))) + + dyn := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(scheme, gvrToListKindMap(), + newUnstructuredCRD("GameServer", "games", "mc", nil), + newUnstructuredCRD("GameServer", "games-2", "val", nil), + ) + dyn.PrependReactor("list", "gameservers", failListIn("locked", + apierrors.NewNotFound(schema.GroupResource{Resource: "gameservers"}, ""))) + + c := NewFrom(typed, dyn, scheme).WithNamespaces([]string{"games", "locked", "games-2"}) + + pods, err := c.ListPods(ctx, "", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if got := podNames(pods); !slices.Equal(got, []string{"mc-0", "mc-1"}) { + t.Errorf("pods: want [mc-0 mc-1], got %v", got) + } + if want := "skipped namespaces: locked"; pods.ResourceVersion != want { + t.Errorf("pods resource version: want %q, got %q", want, pods.ResourceVersion) + } + + events, err := c.ListEvents(ctx, "", "") + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if got := eventNames(events); !slices.Equal(got, []string{"ev-a", "ev-b"}) { + t.Errorf("events: want [ev-a ev-b], got %v", got) + } + if events.ResourceVersion != "skipped namespaces: locked" { + t.Errorf("events resource version: want skipped note, got %q", events.ResourceVersion) + } + + servers, err := c.ListCRD(ctx, "GameServer", "", "") + if err != nil { + t.Fatalf("ListCRD GameServer: %v", err) + } + if got := crdNames(servers); !slices.Equal(got, []string{"mc", "val"}) { + t.Errorf("GameServers: want [mc val], got %v", got) + } + if servers.GetResourceVersion() != "skipped namespaces: locked" { + t.Errorf("GameServer resource version: want skipped note, got %q", servers.GetResourceVersion()) + } +} + +func TestAllowlistReturnsUnexpectedListErrors(t *testing.T) { + scheme := NewScheme() + typed := k8sfake.NewSimpleClientset() + typed.PrependReactor("list", "pods", failListIn("boom", + apierrors.NewInternalError(errors.New("apiserver exploded")))) + c := NewFrom(typed, dynamicfake.NewSimpleDynamicClientWithCustomListKinds(scheme, gvrToListKindMap()), scheme). + WithNamespaces([]string{"games", "boom"}) + + _, err := c.ListPods(context.Background(), "", "") + if err == nil { + t.Fatal("want error from a non-skippable list failure") + } + if errors.Is(err, ErrNamespaceNotInScope) { + t.Errorf("unexpected scope error: %v", err) + } +} + +func TestClusterSelectionRejectedInBreakGlass(t *testing.T) { + ctx := reader.WithTarget(context.Background(), reader.Target{Cluster: "prod"}) + c := seededAllowlistClient([]string{"games"}) + + calls := []struct { + name string + call func() error + }{ + {"ListCRD", func() error { _, err := c.ListCRD(ctx, "GameServer", "", ""); return err }}, + {"GetCRD", func() error { _, err := c.GetCRD(ctx, "GameServer", "games", "mc"); return err }}, + {"ListPods", func() error { _, err := c.ListPods(ctx, "", ""); return err }}, + {"GetPod", func() error { _, err := c.GetPod(ctx, "games", "mc-0"); return err }}, + {"ListEvents", func() error { _, err := c.ListEvents(ctx, "", ""); return err }}, + {"PodLogs", func() error { _, err := c.PodLogs(ctx, "games", "mc-0", "", 0, false); return err }}, + } + for _, tt := range calls { + t.Run(tt.name, func(t *testing.T) { + if err := tt.call(); !errors.Is(err, errClusterNotAvailable) { + t.Fatalf("want errClusterNotAvailable, got %v", err) + } + }) + } +} + +func TestServerTargetIgnoredInBreakGlass(t *testing.T) { + ctx := reader.WithTarget(context.Background(), reader.Target{Server: "mc"}) + c := seededAllowlistClient([]string{"games"}) + + pods, err := c.ListPods(ctx, "games", "") + if err != nil { + t.Fatalf("ListPods with a server target: %v", err) + } + if got := podNames(pods); !slices.Equal(got, []string{"mc-0"}) { + t.Errorf("want [mc-0], got %v", got) + } +} + +func TestParseNamespaces(t *testing.T) { + cases := []struct { + in string + want []string + }{ + {" a, ,b,a ", []string{"a", "b"}}, + {"", nil}, + {" , ,", nil}, + {"x", []string{"x"}}, + {"games,games-2", []string{"games", "games-2"}}, + } + for _, tt := range cases { + got := ParseNamespaces(tt.in) + if !slices.Equal(got, tt.want) { + t.Errorf("ParseNamespaces(%q) = %v, want %v", tt.in, got, tt.want) + } + } +} + +func TestNoNamespacesListsAcrossAllNamespaces(t *testing.T) { + ctx := context.Background() + c := seededAllowlistClient(ParseNamespaces("")) + + pods, err := c.ListPods(ctx, "", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if got := podNames(pods); !slices.Equal(got, []string{"mc-0", "mc-1", "secret-0"}) { + t.Errorf("want every pod, got %v", got) + } + + events, err := c.ListEvents(ctx, "", "") + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if got := eventNames(events); !slices.Equal(got, []string{"ev-a", "ev-b", "ev-s"}) { + t.Errorf("want every event, got %v", got) + } + + servers, err := c.ListCRD(ctx, "GameServer", "", "") + if err != nil { + t.Fatalf("ListCRD GameServer: %v", err) + } + if got := crdNames(servers); !slices.Equal(got, []string{"hidden", "mc", "val"}) { + t.Errorf("want every GameServer, got %v", got) + } + if servers.GetResourceVersion() != "" { + t.Errorf("unrestricted list must not carry a skip note, got %q", servers.GetResourceVersion()) + } +} diff --git a/internal/kube/client.go b/internal/kube/client.go index 7d22686..926eb67 100644 --- a/internal/kube/client.go +++ b/internal/kube/client.go @@ -1,23 +1,32 @@ // Package kube is the strictly read-only Kubernetes access layer for the -// Gameplane MCP server. Client exposes only List/Get-shaped methods -// (ListCRD, GetCRD, ListPods, GetPod, ListEvents, PodLogs); the typed and -// dynamic clientsets backing those methods are unexported fields on Client. -// A caller that holds only a *Client therefore cannot reach a mutating -// verb (Create/Update/Delete/Patch/Apply) through it, and every MCP tool -// handler in package main (see ../../tools.go) receives only a *Client. -// This bounds what the handlers can do with their input; it does not bound -// package main as a whole, which loads the *rest.Config that New takes. +// Gameplane MCP server's break-glass mode. Client exposes only List/Get-shaped +// methods (ListCRD, GetCRD, ListPods, GetPod, ListEvents, PodLogs); the typed +// and dynamic clientsets backing those methods are unexported fields on Client. +// A caller that holds only a *Client therefore cannot reach a mutating verb +// (Create/Update/Delete/Patch/Apply) through it. Client satisfies +// reader.Reader, so every MCP tool handler in package main receives it as a +// reader.Reader; the per-user panel client is the other implementation. +// +// Break-glass Client reads the local cluster with the kubeconfig's own +// credentials. WithNamespaces optionally restricts it to an allow-list of +// namespaces (GAMEPLANE_MCP_NAMESPACES); cluster selection is rejected because +// only per-user mode can reach other clusters. +// // See main.go's package doc comment (in the parent module) for the other -// layer: the get/list/watch-only RBAC ClusterRole the Helm chart installs, -// which is the only layer that stops mutation by any code in the process. +// layer: the namespaced Roles and get/list/watch-only ClusterRole the Helm +// chart installs, which is the only layer that stops mutation by any code in +// the process. package kube import ( "context" "errors" "fmt" + "slices" + "strings" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -26,6 +35,8 @@ import ( "k8s.io/client-go/kubernetes" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" ) // gameplaneGroupVersion is the Gameplane CRD API group, mirroring @@ -39,6 +50,18 @@ var gameplaneGroupVersion = schema.GroupVersion{Group: "gameplane.local", Versio // outside the fixed set of Gameplane CRDs this server knows how to read. var errUnknownKind = errors.New("unknown Gameplane resource kind") +// errClusterNotAvailable is returned when a call names a cluster. Break-glass +// mode reads only the local cluster; cluster selection needs per-user mode. +var errClusterNotAvailable = errors.New("cluster selection needs per-user mode (GAMEPLANE_PANEL_URL); break-glass mode reads only the local cluster") + +// ErrNamespaceNotInScope is returned when a call names a namespace outside the +// allow-list set with WithNamespaces. +var ErrNamespaceNotInScope = errors.New("namespace not in scope") + +// errNamespaceRequired is returned when an allow-listed client is asked for a +// namespaced object without naming the namespace. +var errNamespaceRequired = errors.New("namespace is required when the namespace allow-list is set") + // CRDKind describes one of the 7 Gameplane CRDs (of 9 total; Cluster and // NetworkCapture are not exposed) this server can list/get. // Exported (along with CRDKinds below) so callers outside this package — @@ -117,13 +140,18 @@ func NewScheme() *runtime.Scheme { // them, so no code outside this package can call Create/Update/Delete/ // Patch/Apply through this type, structurally, regardless of what tools get // registered against it. See the package doc comment above for how this -// combines with the RBAC ClusterRole to form the full read-only guarantee. +// combines with the RBAC Roles and ClusterRole to form the full read-only +// guarantee. type Client struct { - typed kubernetes.Interface - dynamic dynamic.Interface - Scheme *runtime.Scheme + typed kubernetes.Interface + dynamic dynamic.Interface + Scheme *runtime.Scheme + namespaces []string // allow-list; empty = unrestricted } +// Client is the break-glass implementation of reader.Reader. +var _ reader.Reader = (*Client)(nil) + // New builds a Client from a rest.Config, e.g. the one returned by // ctrl.GetConfig() (in-cluster config, falling back to KUBECONFIG/ // ~/.kube/config for local runs against a dev cluster). @@ -151,18 +179,93 @@ func NewFrom(typed kubernetes.Interface, dyn dynamic.Interface, scheme *runtime. return &Client{typed: typed, dynamic: dyn, Scheme: scheme} } -// resourceInterface returns the dynamic client scoped to kind's GVR (and to -// namespace, when kind is namespaced and namespace is non-empty). -func (c *Client) resourceInterface(kind, namespace string) (dynamic.ResourceInterface, error) { +// WithNamespaces restricts the client to an allow-list of namespaces. Names +// are trimmed; empties and duplicates are dropped. An empty list leaves the +// client unrestricted. It returns c for chaining. +func (c *Client) WithNamespaces(ns []string) *Client { + c.namespaces = dedupeNamespaces(ns) + return c +} + +// ParseNamespaces splits a comma-separated namespace list (e.g. the value of +// GAMEPLANE_MCP_NAMESPACES) into trimmed, non-empty, de-duplicated names in +// their original order. +func ParseNamespaces(s string) []string { + return dedupeNamespaces(strings.Split(s, ",")) +} + +func dedupeNamespaces(in []string) []string { + var out []string + seen := make(map[string]struct{}, len(in)) + for _, raw := range in { + ns := strings.TrimSpace(raw) + if ns == "" { + continue + } + if _, dup := seen[ns]; dup { + continue + } + seen[ns] = struct{}{} + out = append(out, ns) + } + return out +} + +// checkTarget rejects a cluster selection, which break-glass mode cannot honour. +// Server is ignored here. +func checkTarget(ctx context.Context) error { + if reader.TargetFrom(ctx).Cluster != "" { + return errClusterNotAvailable + } + return nil +} + +// checkNamespace enforces the allow-list on an explicitly named namespace. +// An empty namespace is not checked here; callers handle it. +func (c *Client) checkNamespace(ns string) error { + if ns == "" || len(c.namespaces) == 0 || slices.Contains(c.namespaces, ns) { + return nil + } + return fmt.Errorf("namespace %q not in scope: %w", ns, ErrNamespaceNotInScope) +} + +// requireNamespace rejects an empty namespace for a single-object read when +// the allow-list is set, since there is no safe namespace to fall back to. +func (c *Client) requireNamespace(ns string) error { + if ns == "" && len(c.namespaces) > 0 { + return errNamespaceRequired + } + return nil +} + +// skippable reports whether a per-namespace list error means the namespace is +// absent or not visible to this client, so the merged list skips it. +func skippable(err error) bool { + return apierrors.IsNotFound(err) || apierrors.IsForbidden(err) +} + +// skippedNote is the resource-version annotation that records skipped +// namespaces on a merged list. +func skippedNote(skipped []string) string { + return "skipped namespaces: " + strings.Join(skipped, ", ") +} + +func kindOf(kind string) (CRDKind, error) { k, ok := CRDKinds[kind] if !ok { - return nil, fmt.Errorf("%w: %q (known: %s)", errUnknownKind, kind, knownKindsList()) + return CRDKind{}, fmt.Errorf("%w: %q (known: %s)", errUnknownKind, kind, knownKindsList()) } + return k, nil +} + +// resourceInterface returns the dynamic client scoped to k's GVR (and to +// namespace, when k is namespaced and namespace is non-empty). +func (c *Client) resourceInterface(k CRDKind, namespace string) dynamic.ResourceInterface { ri := c.dynamic.Resource(k.GVR) if k.Namespaced && namespace != "" { - return ri.Namespace(namespace), nil + return ri.Namespace(namespace) } - return ri, nil + return ri } func knownKindsList() string { @@ -178,34 +281,74 @@ func knownKindsList() string { // ListCRD lists objects of a Gameplane CRD kind. namespace is ignored for // cluster-scoped kinds; an empty namespace on a namespaced kind lists across -// all namespaces. labelSelector is passed through verbatim to the API server. +// all namespaces (or, with an allow-list set, across the allowed namespaces). +// labelSelector is passed through verbatim to the API server. func (c *Client) ListCRD(ctx context.Context, kind, namespace, labelSelector string) (*unstructured.UnstructuredList, error) { - ri, err := c.resourceInterface(kind, namespace) + if err := checkTarget(ctx); err != nil { + return nil, err + } + k, err := kindOf(kind) if err != nil { return nil, err } - list, err := ri.List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) + if k.Namespaced { + if err := c.checkNamespace(namespace); err != nil { + return nil, err + } + if namespace == "" && len(c.namespaces) > 0 { + return c.listCRDAcross(ctx, kind, k, labelSelector) + } + } + list, err := c.resourceInterface(k, namespace).List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) if err != nil { return nil, fmt.Errorf("list %s: %w", kind, err) } return list, nil } +// listCRDAcross lists kind in each allow-listed namespace, in order, and +// merges the items. Namespaces that are absent or forbidden are skipped and +// recorded on the merged list's resource version. +func (c *Client) listCRDAcross(ctx context.Context, kind string, k CRDKind, labelSelector string) (*unstructured.UnstructuredList, error) { + merged := &unstructured.UnstructuredList{} + merged.SetGroupVersionKind(gameplaneGroupVersion.WithKind(kind + "List")) + var skipped []string + for _, ns := range c.namespaces { + list, err := c.dynamic.Resource(k.GVR).Namespace(ns).List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) + if err != nil { + if skippable(err) { + skipped = append(skipped, ns) + continue + } + return nil, fmt.Errorf("list %s in %q: %w", kind, ns, err) + } + merged.Items = append(merged.Items, list.Items...) + } + if len(skipped) > 0 { + merged.SetResourceVersion(skippedNote(skipped)) + } + return merged, nil +} + // GetCRD fetches a single Gameplane CRD object by name. namespace is // required for namespaced kinds and ignored for cluster-scoped ones. func (c *Client) GetCRD(ctx context.Context, kind, namespace, name string) (*unstructured.Unstructured, error) { - k, ok := CRDKinds[kind] - if !ok { - return nil, fmt.Errorf("%w: %q (known: %s)", errUnknownKind, kind, knownKindsList()) + if err := checkTarget(ctx); err != nil { + return nil, err + } + k, err := kindOf(kind) + if err != nil { + return nil, err } if k.Namespaced && namespace == "" { return nil, fmt.Errorf("%s is namespace-scoped: namespace is required", kind) } - ri, err := c.resourceInterface(kind, namespace) - if err != nil { - return nil, err + if k.Namespaced { + if err := c.checkNamespace(namespace); err != nil { + return nil, err + } } - obj, err := ri.Get(ctx, name, metav1.GetOptions{}) + obj, err := c.resourceInterface(k, namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("get %s %s/%s: %w", kind, namespace, name, err) } @@ -213,8 +356,34 @@ func (c *Client) GetCRD(ctx context.Context, kind, namespace, name string) (*uns } // ListPods lists core Pods in namespace (empty namespace lists across all -// namespaces), optionally filtered by a label selector. +// namespaces, or across the allow-list when set), optionally filtered by a +// label selector. func (c *Client) ListPods(ctx context.Context, namespace, labelSelector string) (*corev1.PodList, error) { + if err := checkTarget(ctx); err != nil { + return nil, err + } + if err := c.checkNamespace(namespace); err != nil { + return nil, err + } + if namespace == "" && len(c.namespaces) > 0 { + merged := &corev1.PodList{} + var skipped []string + for _, ns := range c.namespaces { + list, err := c.typed.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) + if err != nil { + if skippable(err) { + skipped = append(skipped, ns) + continue + } + return nil, fmt.Errorf("list pods in %q: %w", ns, err) + } + merged.Items = append(merged.Items, list.Items...) + } + if len(skipped) > 0 { + merged.ResourceVersion = skippedNote(skipped) + } + return merged, nil + } list, err := c.typed.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) if err != nil { return nil, fmt.Errorf("list pods in %q: %w", namespace, err) @@ -224,6 +393,15 @@ func (c *Client) ListPods(ctx context.Context, namespace, labelSelector string) // GetPod fetches a single Pod by namespace and name. func (c *Client) GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error) { + if err := checkTarget(ctx); err != nil { + return nil, err + } + if err := c.checkNamespace(namespace); err != nil { + return nil, err + } + if err := c.requireNamespace(namespace); err != nil { + return nil, err + } pod, err := c.typed.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("get pod %s/%s: %w", namespace, name, err) @@ -232,9 +410,34 @@ func (c *Client) GetPod(ctx context.Context, namespace, name string) (*corev1.Po } // ListEvents lists core Events in namespace (empty namespace lists across -// all namespaces), optionally filtered by a field selector (e.g. -// "involvedObject.name=my-server,involvedObject.kind=GameServer"). +// all namespaces, or across the allow-list when set), optionally filtered by +// a field selector (e.g. "involvedObject.name=my-server,involvedObject.kind=GameServer"). func (c *Client) ListEvents(ctx context.Context, namespace, fieldSelector string) (*corev1.EventList, error) { + if err := checkTarget(ctx); err != nil { + return nil, err + } + if err := c.checkNamespace(namespace); err != nil { + return nil, err + } + if namespace == "" && len(c.namespaces) > 0 { + merged := &corev1.EventList{} + var skipped []string + for _, ns := range c.namespaces { + list, err := c.typed.CoreV1().Events(ns).List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}) + if err != nil { + if skippable(err) { + skipped = append(skipped, ns) + continue + } + return nil, fmt.Errorf("list events in %q: %w", ns, err) + } + merged.Items = append(merged.Items, list.Items...) + } + if len(skipped) > 0 { + merged.ResourceVersion = skippedNote(skipped) + } + return merged, nil + } list, err := c.typed.CoreV1().Events(namespace).List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}) if err != nil { return nil, fmt.Errorf("list events in %q: %w", namespace, err) @@ -246,6 +449,15 @@ func (c *Client) ListEvents(ctx context.Context, namespace, fieldSelector string // defaultTailLines; a request above maxTailLines is capped rather than // rejected, so an overly broad ask degrades gracefully instead of failing. func (c *Client) PodLogs(ctx context.Context, namespace, pod, container string, tailLines int64, previous bool) (string, error) { + if err := checkTarget(ctx); err != nil { + return "", err + } + if err := c.checkNamespace(namespace); err != nil { + return "", err + } + if err := c.requireNamespace(namespace); err != nil { + return "", err + } tail := tailLines switch { case tail <= 0: diff --git a/internal/panel/client.go b/internal/panel/client.go new file mode 100644 index 0000000..ea53f59 --- /dev/null +++ b/internal/panel/client.go @@ -0,0 +1,630 @@ +// Package panel is the per-user reader: it reads through the Gameplane API as +// the MCP token's user. Every request is built and sent by get, the only +// place in the package that talks to the network, and get issues GET requests +// only. The source tripwire in source_test.go enforces that. +package panel + +import ( + "context" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + "unicode/utf8" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +const ( + requestTimeout = 30 * time.Second + defaultFanout = 4 + defaultPerCluster = 10 * time.Second + maxResponseBytes = 32 << 20 + maxMessageBytes = 300 + defaultTailLines = 200 + maxTailLines = 5000 + tokenPrefix = "gpmcp_" + sessionHeader = "X-Gameplane-MCP-Session" + clusterAnnotation = "gameplane.local/cluster" +) + +// Client is the per-user reader. It holds the panel base URL, the MCP token +// and a per-process session ID. +type Client struct { + base *url.URL + token string + session string + hc *http.Client + fanout int + perCluster time.Duration +} + +// kindInfo maps a CRD kind onto its panel API path. +type kindInfo struct { + kind string + path string + namespaced bool + listOnly bool +} + +var kinds = []kindInfo{ + {kind: "GameServer", path: "servers", namespaced: true}, + {kind: "GameTemplate", path: "templates"}, + {kind: "Backup", path: "backups", namespaced: true}, + {kind: "BackupSchedule", path: "schedules", namespaced: true}, + {kind: "Restore", path: "restores", namespaced: true}, + {kind: "Module", path: "modules"}, + {kind: "ModuleSource", path: "modules/sources", listOnly: true}, +} + +// New builds a per-user Client. baseURL must be https, or http for a loopback +// host. token must be a Gameplane MCP token. caFile, when set, is a PEM bundle +// added to the system roots for a private certificate authority. +func New(baseURL, token, caFile string) (*Client, error) { + u, err := url.Parse(strings.TrimSpace(baseURL)) + if err != nil { + return nil, fmt.Errorf("parse panel URL: %w", err) + } + if u.Host == "" { + return nil, errors.New("panel URL must include a host") + } + if u.User != nil { + return nil, errors.New("panel URL must not contain credentials") + } + switch u.Scheme { + case "https": + case "http": + if !isLoopbackHost(u.Hostname()) { + return nil, errors.New("panel URL must use https (http is allowed only for localhost or a loopback address)") + } + default: + return nil, errors.New("panel URL must use https (http is allowed only for localhost or a loopback address)") + } + u.RawQuery = "" + u.RawFragment = "" + u.Fragment = "" + + if !strings.HasPrefix(token, tokenPrefix) { + return nil, errors.New("GAMEPLANE_MCP_TOKEN must be a Gameplane MCP token (gpmcp_…)") + } + + tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} + if caFile != "" { + pool, err := certPool(caFile) + if err != nil { + return nil, err + } + tlsCfg.RootCAs = pool + } + tr, ok := http.DefaultTransport.(*http.Transport) + if !ok { + tr = &http.Transport{Proxy: http.ProxyFromEnvironment} + } + tr = tr.Clone() + tr.TLSClientConfig = tlsCfg + + raw := make([]byte, 16) + if _, err := rand.Read(raw); err != nil { + return nil, fmt.Errorf("generate session ID: %w", err) + } + + return &Client{ + base: u, + token: token, + session: base64.RawURLEncoding.EncodeToString(raw), + hc: &http.Client{Timeout: requestTimeout, Transport: tr}, + fanout: defaultFanout, + perCluster: defaultPerCluster, + }, nil +} + +func isLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func certPool(caFile string) (*x509.CertPool, error) { + pool, err := x509.SystemCertPool() + if err != nil || pool == nil { + pool = x509.NewCertPool() + } + pemBytes, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("read panel CA file: %w", err) + } + if !pool.AppendCertsFromPEM(pemBytes) { + return nil, errors.New("panel CA file contains no PEM certificates") + } + return pool, nil +} + +// APIError is a non-2xx response from the Gameplane API. +type APIError struct { + Status int + Path string + Message string +} + +func (e *APIError) Error() string { + switch e.Status { + case http.StatusUnauthorized: + return "not authenticated: the MCP token is missing, expired or revoked" + case http.StatusForbidden: + return "permission denied: " + e.Message + case http.StatusNotFound: + return "not found: " + e.Message + } + return fmt.Sprintf("gameplane api %s: %s: %s", e.Path, http.StatusText(e.Status), e.Message) +} + +// statusOf returns the HTTP status carried by err, or 0 when err is not an APIError. +func statusOf(err error) int { + var apiErr *APIError + if errors.As(err, &apiErr) { + return apiErr.Status + } + return 0 +} + +// trimMessage bounds an error body to maxMessageBytes and removes the token +// if the server ever echoes it. +func (c *Client) trimMessage(body []byte) string { + s := strings.TrimSpace(string(body)) + s = strings.ReplaceAll(s, c.token, "[redacted]") + if len(s) > maxMessageBytes { + cut := maxMessageBytes + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + s = s[:cut] + } + return s +} + +// endpoint joins path and q onto the panel base URL. +func (c *Client) endpoint(path string, q url.Values) (string, error) { + full := strings.TrimSuffix(c.base.String(), "/") + path + u, err := url.Parse(full) + if err != nil { + return "", fmt.Errorf("gameplane api %s: build URL: %w", path, err) + } + u.RawQuery = q.Encode() + return u.String(), nil +} + +// get is the only request builder in the package. It sends a GET with the +// bearer token and session header, adds the cluster selection when the +// context names one, and decodes the body into out. A *string out receives +// the raw body. +func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error { + if q == nil { + q = url.Values{} + } + if cl := reader.TargetFrom(ctx).Cluster; cl != "" { + q.Set("cluster", cl) + } + target, err := c.endpoint(path, q) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return fmt.Errorf("gameplane api %s: build request: %w", path, err) + } + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set(sessionHeader, c.session) + req.Header.Set("Accept", "application/json") + + resp, err := c.hc.Do(req) + if err != nil { + return fmt.Errorf("gameplane api %s: %w", path, err) + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) + if err != nil { + return fmt.Errorf("gameplane api %s: read response: %w", path, err) + } + if len(body) > maxResponseBytes { + return fmt.Errorf("gameplane api %s: response exceeds %d bytes", path, maxResponseBytes) + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return &APIError{Status: resp.StatusCode, Path: path, Message: c.trimMessage(body)} + } + if s, ok := out.(*string); ok { + *s = string(body) + return nil + } + if err := json.Unmarshal(body, out); err != nil { + return fmt.Errorf("gameplane api %s: decode response: %w", path, err) + } + return nil +} + +// lookupKind resolves a CRD kind name to its panel path. +func lookupKind(kind string) (kindInfo, error) { + for _, k := range kinds { + if k.kind == kind { + return k, nil + } + } + names := make([]string, 0, len(kinds)) + for _, k := range kinds { + names = append(names, k.kind) + } + return kindInfo{}, fmt.Errorf("unknown kind %q; known kinds: %s", kind, strings.Join(names, ", ")) +} + +// unstructuredList wraps items as an UnstructuredList. The kind is set so the +// list marshals like the API's own list objects. +func unstructuredList(kind string, items []unstructured.Unstructured) *unstructured.UnstructuredList { + list := &unstructured.UnstructuredList{Object: map[string]any{}, Items: items} + if list.Items == nil { + list.Items = []unstructured.Unstructured{} + } + list.SetKind(kind + "List") + return list +} + +// getItems fetches a {items:[...]} response as unstructured objects. Objects +// are wrapped from the raw maps, so the API response does not need a kind. +func (c *Client) getItems(ctx context.Context, path string, q url.Values) ([]unstructured.Unstructured, error) { + var raw struct { + Items []map[string]any `json:"items"` + } + if err := c.get(ctx, path, q, &raw); err != nil { + return nil, err + } + items := make([]unstructured.Unstructured, 0, len(raw.Items)) + for _, m := range raw.Items { + if m != nil { + items = append(items, unstructured.Unstructured{Object: m}) + } + } + return items, nil +} + +// namespaces lists the namespaces visible in the selected cluster. +func (c *Client) namespaces(ctx context.Context) ([]string, error) { + var out struct { + Namespaces []string `json:"namespaces"` + } + if err := c.get(ctx, "/namespaces", nil, &out); err != nil { + return nil, err + } + return out.Namespaces, nil +} + +// ListCRD lists objects of kind. With no cluster in the context it fans out +// across every registered cluster. +func (c *Client) ListCRD(ctx context.Context, kind, namespace, labelSelector string) (*unstructured.UnstructuredList, error) { + k, err := lookupKind(kind) + if err != nil { + return nil, err + } + if reader.TargetFrom(ctx).Cluster != "" { + return c.listCRDLocal(ctx, k, namespace, labelSelector) + } + return c.listCRDAcross(ctx, k, namespace, labelSelector) +} + +// listCRDLocal lists kind in the selected cluster. A namespaced kind with no +// namespace loops over the cluster's namespaces. +func (c *Client) listCRDLocal(ctx context.Context, k kindInfo, ns, sel string) (*unstructured.UnstructuredList, error) { + if !k.namespaced || ns != "" { + return c.listCRDIn(ctx, k, ns, sel) + } + nss, err := c.namespaces(ctx) + if err != nil { + if k.kind == "GameServer" && statusOf(err) == http.StatusForbidden { + return c.ownServers(ctx, "", sel) + } + return nil, err + } + var items []unstructured.Unstructured + for _, n := range nss { + part, err := c.listCRDIn(ctx, k, n, sel) + if err != nil { + return nil, err + } + items = append(items, part.Items...) + } + return unstructuredList(k.kind, items), nil +} + +// listCRDIn lists kind in one namespace (or unscoped for cluster-scoped kinds). +// A GameServer list that the user may not make by namespace falls back to the +// user's own servers. +func (c *Client) listCRDIn(ctx context.Context, k kindInfo, ns, sel string) (*unstructured.UnstructuredList, error) { + q := url.Values{} + if k.namespaced && ns != "" { + q.Set("namespace", ns) + } + if sel != "" { + q.Set("labelSelector", sel) + } + items, err := c.getItems(ctx, "/"+k.path, q) + if err != nil { + if k.kind == "GameServer" && ns != "" && statusOf(err) == http.StatusForbidden { + return c.ownServers(ctx, ns, sel) + } + return nil, err + } + return unstructuredList(k.kind, items), nil +} + +// ownServers reads /users/me/servers and keeps only the items in ns when ns +// is set. +func (c *Client) ownServers(ctx context.Context, ns, sel string) (*unstructured.UnstructuredList, error) { + q := url.Values{} + if sel != "" { + q.Set("labelSelector", sel) + } + items, err := c.getItems(ctx, "/users/me/servers", q) + if err != nil { + return nil, err + } + if ns != "" { + kept := make([]unstructured.Unstructured, 0, len(items)) + for _, it := range items { + if it.GetNamespace() == ns { + kept = append(kept, it) + } + } + items = kept + } + return unstructuredList("GameServer", items), nil +} + +// GetCRD reads one object. ModuleSource has no single-object endpoint, so it +// is listed and matched by name. +func (c *Client) GetCRD(ctx context.Context, kind, namespace, name string) (*unstructured.Unstructured, error) { + k, err := lookupKind(kind) + if err != nil { + return nil, err + } + if k.listOnly { + list, err := c.listCRDLocal(ctx, k, "", "") + if err != nil { + return nil, err + } + for i := range list.Items { + if list.Items[i].GetName() == name { + return &list.Items[i], nil + } + } + return nil, &APIError{Status: http.StatusNotFound, Path: "/" + k.path, Message: fmt.Sprintf("%s %q not found", k.kind, name)} + } + q := url.Values{} + if k.namespaced && namespace != "" { + q.Set("namespace", namespace) + } + var raw map[string]any + if err := c.get(ctx, "/"+k.path+"/"+url.PathEscape(name), q, &raw); err != nil { + return nil, err + } + if raw == nil { + return nil, &APIError{Status: http.StatusNotFound, Path: "/" + k.path, Message: fmt.Sprintf("%s %q not found", k.kind, name)} + } + return &unstructured.Unstructured{Object: raw}, nil +} + +// ListPods lists pods. With no cluster in the context it fans out across every +// registered cluster. +func (c *Client) ListPods(ctx context.Context, namespace, labelSelector string) (*corev1.PodList, error) { + if reader.TargetFrom(ctx).Cluster != "" { + return c.listPodsLocal(ctx, namespace, labelSelector) + } + return c.listPodsAcross(ctx, namespace, labelSelector) +} + +// listPodsLocal lists pods in the selected cluster. A server target or a +// named namespace is one request; otherwise it loops over the namespaces. +func (c *Client) listPodsLocal(ctx context.Context, ns, sel string) (*corev1.PodList, error) { + if reader.TargetFrom(ctx).Server != "" || ns != "" { + return c.podsIn(ctx, ns, sel) + } + nss, err := c.namespaces(ctx) + if err != nil { + return nil, err + } + merged := &corev1.PodList{} + for _, n := range nss { + part, err := c.podsIn(ctx, n, sel) + if err != nil { + return nil, err + } + merged.Items = append(merged.Items, part.Items...) + } + return merged, nil +} + +func (c *Client) podsIn(ctx context.Context, ns, sel string) (*corev1.PodList, error) { + q := url.Values{} + if ns != "" { + q.Set("namespace", ns) + } + path := "/pods" + if srv := reader.TargetFrom(ctx).Server; srv != "" { + path = "/servers/" + url.PathEscape(srv) + "/pods" + } else if sel != "" { + q.Set("labelSelector", sel) + } + out := &corev1.PodList{} + if err := c.get(ctx, path, q, out); err != nil { + return nil, err + } + return out, nil +} + +// GetPod reads one pod from the selected cluster. +func (c *Client) GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error) { + q := url.Values{} + if namespace != "" { + q.Set("namespace", namespace) + } + pod := &corev1.Pod{} + if err := c.get(ctx, "/pods/"+url.PathEscape(name), q, pod); err != nil { + return nil, err + } + return pod, nil +} + +// serverEvent is one row of /servers/{name}/events. +type serverEvent struct { + ID string `json:"id"` + Time string `json:"time"` + Type string `json:"type"` + Reason string `json:"reason"` + Message string `json:"message"` + Source string `json:"source"` + Object string `json:"object"` + Count int32 `json:"count"` +} + +// toEvent converts a server event row to a corev1.Event. A malformed time +// leaves LastTimestamp zero rather than failing the whole list. +func (e serverEvent) toEvent(ns string) corev1.Event { + kind, name, ok := strings.Cut(e.Object, "/") + if !ok { + kind, name = "", e.Object + } + ev := corev1.Event{ + ObjectMeta: metav1.ObjectMeta{Name: e.ID, Namespace: ns}, + Type: e.Type, + Reason: e.Reason, + Message: e.Message, + Source: corev1.EventSource{Component: e.Source}, + Count: e.Count, + InvolvedObject: corev1.ObjectReference{Kind: kind, Name: name, Namespace: ns}, + } + if t, err := time.Parse(time.RFC3339, e.Time); err == nil { + ev.LastTimestamp = metav1.NewTime(t) + } + return ev +} + +// ListEvents lists events. With no cluster in the context it fans out across +// every registered cluster. +func (c *Client) ListEvents(ctx context.Context, namespace, fieldSelector string) (*corev1.EventList, error) { + if reader.TargetFrom(ctx).Cluster != "" { + return c.listEventsLocal(ctx, namespace, fieldSelector) + } + return c.listEventsAcross(ctx, namespace, fieldSelector) +} + +// listEventsLocal lists events in the selected cluster, with the same +// namespace rules as listPodsLocal. +func (c *Client) listEventsLocal(ctx context.Context, ns, fsel string) (*corev1.EventList, error) { + if reader.TargetFrom(ctx).Server != "" || ns != "" { + return c.eventsIn(ctx, ns, fsel) + } + nss, err := c.namespaces(ctx) + if err != nil { + return nil, err + } + merged := &corev1.EventList{} + for _, n := range nss { + part, err := c.eventsIn(ctx, n, fsel) + if err != nil { + return nil, err + } + merged.Items = append(merged.Items, part.Items...) + } + return merged, nil +} + +func (c *Client) eventsIn(ctx context.Context, ns, fsel string) (*corev1.EventList, error) { + q := url.Values{} + if ns != "" { + q.Set("namespace", ns) + } + if srv := reader.TargetFrom(ctx).Server; srv != "" { + var rows []serverEvent + if err := c.get(ctx, "/servers/"+url.PathEscape(srv)+"/events", q, &rows); err != nil { + return nil, err + } + out := &corev1.EventList{Items: make([]corev1.Event, 0, len(rows))} + for _, r := range rows { + out.Items = append(out.Items, r.toEvent(ns)) + } + return out, nil + } + if fsel != "" { + q.Set("fieldSelector", fsel) + } + out := &corev1.EventList{} + if err := c.get(ctx, "/kube-events", q, out); err != nil { + return nil, err + } + return out, nil +} + +// PodLogs reads pod logs. A server target reads that server's pod through the +// API. Without one, the operator and API system pods are readable by name; +// any other pod needs a server. +func (c *Client) PodLogs(ctx context.Context, namespace, pod, container string, tailLines int64, previous bool) (string, error) { + tail := tailLines + if tail <= 0 { + tail = defaultTailLines + } + if tail > maxTailLines { + tail = maxTailLines + } + tailStr := strconv.FormatInt(tail, 10) + + var logs string + if srv := reader.TargetFrom(ctx).Server; srv != "" { + q := url.Values{} + if namespace != "" { + q.Set("namespace", namespace) + } + q.Set("pod", pod) + if container != "" { + q.Set("container", container) + } + q.Set("tailLines", tailStr) + q.Set("previous", strconv.FormatBool(previous)) + if err := c.get(ctx, "/servers/"+url.PathEscape(srv)+"/logs/pod/tail", q, &logs); err != nil { + return "", err + } + return logs, nil + } + + var path string + switch { + case strings.HasPrefix(pod, "gameplane-api"): + path = "/admin/system-logs/api" + case strings.HasPrefix(pod, "gameplane-operator"): + path = "/admin/system-logs/operator" + default: + return "", errors.New("server is required to read game server logs in per-user mode") + } + q := url.Values{} + q.Set("pod", pod) + q.Set("tailLines", tailStr) + if err := c.get(ctx, path, q, &logs); err != nil { + return "", err + } + return logs, nil +} + +var _ reader.Reader = (*Client)(nil) diff --git a/internal/panel/client_test.go b/internal/panel/client_test.go new file mode 100644 index 0000000..3e9b0fe --- /dev/null +++ b/internal/panel/client_test.go @@ -0,0 +1,600 @@ +package panel + +import ( + "context" + "encoding/pem" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +const testToken = "gpmcp_test_token" + +// handlerFunc answers one request to the fake panel API. +type handlerFunc func(r *http.Request) (int, string) + +// recorded is the part of one request the tests assert on. +type recorded struct { + method string + path string + query url.Values + auth string + session string +} + +// fakeAPI is a recording stand-in for the Gameplane API. Routes are keyed by +// URL path; an unknown path answers 404. +type fakeAPI struct { + mu sync.Mutex + routes map[string]handlerFunc + reqs []recorded +} + +func (f *fakeAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.reqs = append(f.reqs, recorded{ + method: r.Method, + path: r.URL.Path, + query: r.URL.Query(), + auth: r.Header.Get("Authorization"), + session: r.Header.Get(sessionHeader), + }) + h := f.routes[r.URL.Path] + f.mu.Unlock() + + if h == nil { + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, "no route for "+r.URL.Path) + return + } + status, body := h(r) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, body) +} + +func (f *fakeAPI) requests() []recorded { + f.mu.Lock() + defer f.mu.Unlock() + return append([]recorded(nil), f.reqs...) +} + +// reply answers 200 with body. +func reply(body string) handlerFunc { + return func(*http.Request) (int, string) { return http.StatusOK, body } +} + +// fail answers status with body. +func fail(status int, body string) handlerFunc { + return func(*http.Request) (int, string) { return status, body } +} + +// byCluster dispatches on the cluster query parameter. +func byCluster(m map[string]handlerFunc) handlerFunc { + return func(r *http.Request) (int, string) { + h, ok := m[r.URL.Query().Get("cluster")] + if !ok { + return http.StatusBadRequest, "unexpected cluster " + r.URL.Query().Get("cluster") + } + return h(r) + } +} + +func newTestClient(t *testing.T, routes map[string]handlerFunc) (*Client, *fakeAPI) { + t.Helper() + api := &fakeAPI{routes: routes} + srv := httptest.NewServer(api) + t.Cleanup(srv.Close) + c, err := New(srv.URL, testToken, "") + if err != nil { + t.Fatalf("New: %v", err) + } + return c, api +} + +// clusterCtx selects a cluster, so calls do not fan out. +func clusterCtx(cluster string) context.Context { + return reader.WithTarget(context.Background(), reader.Target{Cluster: cluster}) +} + +// assertGETWithAuth checks that every recorded request was a GET carrying the +// bearer token and one stable session header. +func assertGETWithAuth(t *testing.T, reqs []recorded) { + t.Helper() + for _, r := range reqs { + if r.method != http.MethodGet { + t.Errorf("%s: method = %s, want GET", r.path, r.method) + } + if r.auth != "Bearer "+testToken { + t.Errorf("%s: Authorization = %q, want bearer token", r.path, r.auth) + } + if r.session == "" { + t.Errorf("%s: missing %s header", r.path, sessionHeader) + } + if len(reqs) > 0 && r.session != reqs[0].session { + t.Errorf("%s: session %q differs from %q", r.path, r.session, reqs[0].session) + } + } +} + +func TestReaderMethodsHitPanelPaths(t *testing.T) { + pods := `{"items":[{"metadata":{"name":"mc-0","namespace":"games"}}]}` + routes := map[string]handlerFunc{ + "/servers": reply(`{"items":[{"metadata":{"name":"mc","namespace":"games"}}]}`), + "/backups/nightly": reply(`{"metadata":{"name":"nightly","namespace":"games"}}`), + "/templates/mc-java": reply(`{"metadata":{"name":"mc-java"}}`), + "/modules/sources": reply(`{"items":[{"metadata":{"name":"official"}},{"metadata":{"name":"community"}}]}`), + "/pods": reply(pods), + "/servers/mc/pods": reply(pods), + "/pods/mc-0": reply(`{"metadata":{"name":"mc-0","namespace":"games"},"status":{"phase":"Running"}}`), + "/kube-events": reply(`{"items":[{"metadata":{"name":"ev1","namespace":"games"},"reason":"Started"}]}`), + "/servers/mc/events": reply(`[]`), + "/servers/mc/logs/pod/tail": reply("line one\nline two\n"), + "/admin/system-logs/api": reply("api log"), + "/admin/system-logs/operator": reply("operator log"), + } + + cases := []struct { + name string + target reader.Target + call func(ctx context.Context, c *Client) error + path string + query url.Values + }{ + { + name: "ListCRD GameServer", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.ListCRD(ctx, "GameServer", "games", "app=mc") + return err + }, + path: "/servers", + query: url.Values{"namespace": {"games"}, "labelSelector": {"app=mc"}, "cluster": {"prod"}}, + }, + { + name: "GetCRD Backup", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.GetCRD(ctx, "Backup", "games", "nightly") + return err + }, + path: "/backups/nightly", + query: url.Values{"namespace": {"games"}, "cluster": {"prod"}}, + }, + { + name: "GetCRD GameTemplate is cluster-scoped", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.GetCRD(ctx, "GameTemplate", "ignored", "mc-java") + return err + }, + path: "/templates/mc-java", + query: url.Values{"cluster": {"prod"}}, + }, + { + name: "GetCRD ModuleSource lists and matches by name", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + obj, err := c.GetCRD(ctx, "ModuleSource", "", "community") + if err != nil { + return err + } + if obj.GetName() != "community" { + return errors.New("GetCRD returned " + obj.GetName() + ", want community") + } + return nil + }, + path: "/modules/sources", + query: url.Values{"cluster": {"prod"}}, + }, + { + name: "ListPods by namespace", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.ListPods(ctx, "games", "app=mc") + return err + }, + path: "/pods", + query: url.Values{"namespace": {"games"}, "labelSelector": {"app=mc"}, "cluster": {"prod"}}, + }, + { + name: "ListPods for a server", + target: reader.Target{Cluster: "prod", Server: "mc"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.ListPods(ctx, "games", "") + return err + }, + path: "/servers/mc/pods", + query: url.Values{"namespace": {"games"}, "cluster": {"prod"}}, + }, + { + name: "GetPod", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.GetPod(ctx, "games", "mc-0") + return err + }, + path: "/pods/mc-0", + query: url.Values{"namespace": {"games"}, "cluster": {"prod"}}, + }, + { + name: "ListEvents by namespace", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.ListEvents(ctx, "games", "involvedObject.name=mc-0") + return err + }, + path: "/kube-events", + query: url.Values{"namespace": {"games"}, "fieldSelector": {"involvedObject.name=mc-0"}, "cluster": {"prod"}}, + }, + { + name: "ListEvents for a server", + target: reader.Target{Cluster: "prod", Server: "mc"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.ListEvents(ctx, "games", "") + return err + }, + path: "/servers/mc/events", + query: url.Values{"namespace": {"games"}, "cluster": {"prod"}}, + }, + { + name: "PodLogs for a server", + target: reader.Target{Cluster: "prod", Server: "mc"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.PodLogs(ctx, "games", "mc-0", "main", 50, true) + return err + }, + path: "/servers/mc/logs/pod/tail", + query: url.Values{ + "namespace": {"games"}, "pod": {"mc-0"}, "container": {"main"}, + "tailLines": {"50"}, "previous": {"true"}, "cluster": {"prod"}, + }, + }, + { + name: "PodLogs for the API system pod", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.PodLogs(ctx, "gameplane-system", "gameplane-api-7d9", "", 0, false) + return err + }, + path: "/admin/system-logs/api", + query: url.Values{"pod": {"gameplane-api-7d9"}, "tailLines": {"200"}, "cluster": {"prod"}}, + }, + { + name: "PodLogs for the operator system pod clamps the tail", + target: reader.Target{Cluster: "prod"}, + call: func(ctx context.Context, c *Client) error { + _, err := c.PodLogs(ctx, "gameplane-system", "gameplane-operator-1", "", 9999, false) + return err + }, + path: "/admin/system-logs/operator", + query: url.Values{"pod": {"gameplane-operator-1"}, "tailLines": {"5000"}, "cluster": {"prod"}}, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + c, api := newTestClient(t, routes) + ctx := reader.WithTarget(context.Background(), tt.target) + if err := tt.call(ctx, c); err != nil { + t.Fatalf("call: %v", err) + } + reqs := api.requests() + if len(reqs) != 1 { + t.Fatalf("want 1 request, got %d: %+v", len(reqs), reqs) + } + if reqs[0].path != tt.path { + t.Errorf("path = %q, want %q", reqs[0].path, tt.path) + } + if !reflect.DeepEqual(reqs[0].query, tt.query) { + t.Errorf("query = %v, want %v", reqs[0].query, tt.query) + } + assertGETWithAuth(t, reqs) + }) + } +} + +func TestPodLogsReturnsRawText(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/servers/mc/logs/pod/tail": reply("line one\nline two\n"), + }) + ctx := reader.WithTarget(context.Background(), reader.Target{Cluster: "prod", Server: "mc"}) + got, err := c.PodLogs(ctx, "games", "mc-0", "", 0, false) + if err != nil { + t.Fatalf("PodLogs: %v", err) + } + if got != "line one\nline two\n" { + t.Errorf("PodLogs = %q, want the raw body", got) + } +} + +func TestPodLogsTailClamp(t *testing.T) { + cases := []struct { + in int64 + want string + }{ + {0, "200"}, + {-5, "200"}, + {42, "42"}, + {9999, "5000"}, + } + for _, tt := range cases { + t.Run(tt.want, func(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/servers/mc/logs/pod/tail": reply(""), + }) + ctx := reader.WithTarget(context.Background(), reader.Target{Cluster: "prod", Server: "mc"}) + if _, err := c.PodLogs(ctx, "games", "mc-0", "", tt.in, false); err != nil { + t.Fatalf("PodLogs: %v", err) + } + if got := api.requests()[0].query.Get("tailLines"); got != tt.want { + t.Errorf("tailLines = %q, want %q", got, tt.want) + } + }) + } +} + +func TestPodLogsRequiresServerForGameServerPods(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{}) + _, err := c.PodLogs(clusterCtx("prod"), "games", "mc-0", "", 0, false) + if err == nil || !strings.Contains(err.Error(), "server is required") { + t.Fatalf("want server-required error, got %v", err) + } + if n := len(api.requests()); n != 0 { + t.Errorf("want no API request, got %d", n) + } +} + +func TestListCRDAcrossNamespacesOfOneCluster(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/namespaces": reply(`{"namespaces":["games","ops"]}`), + "/servers": func(r *http.Request) (int, string) { + if r.URL.Query().Get("namespace") == "games" { + return http.StatusOK, `{"items":[{"metadata":{"name":"mc","namespace":"games"}}]}` + } + return http.StatusOK, `{"items":[{"metadata":{"name":"ops-mc","namespace":"ops"}}]}` + }, + }) + list, err := c.ListCRD(clusterCtx("prod"), "GameServer", "", "") + if err != nil { + t.Fatalf("ListCRD: %v", err) + } + if len(list.Items) != 2 { + t.Fatalf("want 2 items, got %d", len(list.Items)) + } + if list.GetKind() != "GameServerList" { + t.Errorf("kind = %q, want GameServerList", list.GetKind()) + } + reqs := api.requests() + if len(reqs) != 3 || reqs[0].path != "/namespaces" { + t.Fatalf("want /namespaces then two /servers calls, got %+v", reqs) + } + assertGETWithAuth(t, reqs) +} + +func TestGameServerForbiddenFallsBackToOwnServers(t *testing.T) { + ownServers := reply(`{"items":[` + + `{"metadata":{"name":"mc","namespace":"games"}},` + + `{"metadata":{"name":"val","namespace":"games-2"}}]}`) + + t.Run("named namespace keeps only that namespace", func(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/servers": fail(http.StatusForbidden, "no access to games-2"), + "/users/me/servers": ownServers, + }) + list, err := c.ListCRD(clusterCtx("prod"), "GameServer", "games", "") + if err != nil { + t.Fatalf("ListCRD: %v", err) + } + if len(list.Items) != 1 || list.Items[0].GetName() != "mc" { + t.Errorf("want only mc, got %d items", len(list.Items)) + } + reqs := api.requests() + if last := reqs[len(reqs)-1]; last.path != "/users/me/servers" { + t.Errorf("last request = %s, want /users/me/servers", last.path) + } + }) + + t.Run("all namespaces when the namespace list is forbidden", func(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/namespaces": fail(http.StatusForbidden, "no namespace list"), + "/users/me/servers": ownServers, + }) + list, err := c.ListCRD(clusterCtx("prod"), "GameServer", "", "") + if err != nil { + t.Fatalf("ListCRD: %v", err) + } + if len(list.Items) != 2 { + t.Errorf("want both own servers, got %d", len(list.Items)) + } + }) +} + +func TestAPIErrorMessages(t *testing.T) { + leak := "bad token " + testToken + cases := []struct { + status int + want string + }{ + {http.StatusUnauthorized, "not authenticated: the MCP token is missing, expired or revoked"}, + {http.StatusForbidden, "permission denied: bad token [redacted]"}, + {http.StatusNotFound, "not found: bad token [redacted]"}, + {http.StatusInternalServerError, "gameplane api /pods/mc-0: Internal Server Error: bad token [redacted]"}, + } + for _, tt := range cases { + t.Run(http.StatusText(tt.status), func(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{"/pods/mc-0": fail(tt.status, leak)}) + _, err := c.GetPod(clusterCtx("prod"), "games", "mc-0") + if err == nil { + t.Fatal("want error") + } + if err.Error() != tt.want { + t.Errorf("error = %q, want %q", err.Error(), tt.want) + } + if strings.Contains(err.Error(), testToken) { + t.Errorf("token leaked into error: %q", err.Error()) + } + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Status != tt.status { + t.Errorf("want *APIError with status %d, got %v", tt.status, err) + } + }) + } +} + +func TestAPIErrorMessageIsBounded(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/pods/big": fail(http.StatusForbidden, strings.Repeat("x", 1000)), + }) + _, err := c.GetPod(clusterCtx("prod"), "games", "big") + var apiErr *APIError + if !errors.As(err, &apiErr) { + t.Fatalf("want *APIError, got %v", err) + } + if len(apiErr.Message) > maxMessageBytes { + t.Errorf("message is %d bytes, want at most %d", len(apiErr.Message), maxMessageBytes) + } +} + +func TestServerEventsConvertToCoreEvents(t *testing.T) { + body := `[` + + `{"id":"ev-1","time":"2026-03-04T05:06:07Z","type":"Warning","reason":"BackOff",` + + `"message":"restarting","source":"kubelet","object":"Pod/mc-0","count":3},` + + `{"id":"ev-2","time":"not-a-time","type":"Normal","reason":"Started",` + + `"message":"ok","source":"kubelet","object":"GameServer/mc","count":1}]` + c, _ := newTestClient(t, map[string]handlerFunc{"/servers/mc/events": reply(body)}) + ctx := reader.WithTarget(context.Background(), reader.Target{Cluster: "prod", Server: "mc"}) + + list, err := c.ListEvents(ctx, "games", "") + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if len(list.Items) != 2 { + t.Fatalf("want 2 events, got %d", len(list.Items)) + } + + e := list.Items[0] + if e.Name != "ev-1" || e.Namespace != "games" { + t.Errorf("name/namespace = %s/%s, want ev-1/games", e.Name, e.Namespace) + } + if e.Type != "Warning" || e.Reason != "BackOff" || e.Message != "restarting" { + t.Errorf("type/reason/message = %q/%q/%q", e.Type, e.Reason, e.Message) + } + if e.Source.Component != "kubelet" { + t.Errorf("source component = %q, want kubelet", e.Source.Component) + } + if e.Count != 3 { + t.Errorf("count = %d, want 3", e.Count) + } + if want := time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC); !e.LastTimestamp.Time.Equal(want) { + t.Errorf("last timestamp = %v, want %v", e.LastTimestamp.Time, want) + } + if e.InvolvedObject.Kind != "Pod" || e.InvolvedObject.Name != "mc-0" || e.InvolvedObject.Namespace != "games" { + t.Errorf("involved object = %+v", e.InvolvedObject) + } + + bad := list.Items[1] + if !bad.LastTimestamp.IsZero() { + t.Errorf("malformed time should leave the timestamp zero, got %v", bad.LastTimestamp.Time) + } + if bad.InvolvedObject.Kind != "GameServer" || bad.InvolvedObject.Name != "mc" { + t.Errorf("involved object = %+v, want GameServer/mc", bad.InvolvedObject) + } +} + +func TestNewValidatesURLAndToken(t *testing.T) { + cases := []struct { + name string + url string + token string + ok bool + }{ + {"https host", "https://panel.example.com", "gpmcp_x", true}, + {"http localhost", "http://localhost:8080", "gpmcp_x", true}, + {"http IPv4 loopback", "http://127.0.0.1:8080", "gpmcp_x", true}, + {"http IPv6 loopback", "http://[::1]:8080", "gpmcp_x", true}, + {"http remote host", "http://panel.example.com", "gpmcp_x", false}, + {"http private address", "http://10.0.0.5", "gpmcp_x", false}, + {"ftp scheme", "ftp://localhost", "gpmcp_x", false}, + {"no host", "https://", "gpmcp_x", false}, + {"credentials in URL", "https://user:pw@panel.example.com", "gpmcp_x", false}, + {"token without prefix", "https://panel.example.com", "abc", false}, + {"empty token", "https://panel.example.com", "", false}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + c, err := New(tt.url, tt.token, "") + if (err == nil) != tt.ok { + t.Fatalf("New(%q) error = %v, want ok=%v", tt.url, err, tt.ok) + } + if err == nil && c == nil { + t.Fatal("New returned a nil client without an error") + } + }) + } +} + +func TestNewRejectsBadCAFiles(t *testing.T) { + dir := t.TempDir() + if _, err := New("https://panel.example.com", testToken, filepath.Join(dir, "missing.pem")); err == nil { + t.Error("want error for a missing CA file") + } + garbage := filepath.Join(dir, "garbage.pem") + if err := os.WriteFile(garbage, []byte("not a certificate"), 0o600); err != nil { + t.Fatalf("write: %v", err) + } + if _, err := New("https://panel.example.com", testToken, garbage); err == nil { + t.Error("want error for a CA file without PEM certificates") + } +} + +func TestNewTrustsPrivateCAFile(t *testing.T) { + api := &fakeAPI{routes: map[string]handlerFunc{ + "/pods/mc-0": reply(`{"metadata":{"name":"mc-0","namespace":"games"}}`), + }} + srv := httptest.NewTLSServer(api) + t.Cleanup(srv.Close) + + caPath := filepath.Join(t.TempDir(), "ca.pem") + f, err := os.Create(caPath) + if err != nil { + t.Fatalf("create CA file: %v", err) + } + if err := pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}); err != nil { + t.Fatalf("encode CA: %v", err) + } + if err := f.Close(); err != nil { + t.Fatalf("close CA file: %v", err) + } + + trusted, err := New(srv.URL, testToken, caPath) + if err != nil { + t.Fatalf("New with CA: %v", err) + } + pod, err := trusted.GetPod(clusterCtx("prod"), "games", "mc-0") + if err != nil { + t.Fatalf("GetPod over TLS with the CA: %v", err) + } + if pod.Name != "mc-0" { + t.Errorf("pod name = %q, want mc-0", pod.Name) + } + + untrusted, err := New(srv.URL, testToken, "") + if err != nil { + t.Fatalf("New without CA: %v", err) + } + if _, err := untrusted.GetPod(clusterCtx("prod"), "games", "mc-0"); err == nil { + t.Error("want a TLS verification failure without the CA") + } +} diff --git a/internal/panel/fanout.go b/internal/panel/fanout.go new file mode 100644 index 0000000..43d0627 --- /dev/null +++ b/internal/panel/fanout.go @@ -0,0 +1,181 @@ +package panel + +import ( + "context" + "errors" + "net/http" + "strings" + "sync" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +// clusterResult is one cluster's successful list result, in /clusters order. +type clusterResult[T any] struct { + id string + val T +} + +// fanOut runs fn once per registered cluster, at most c.fanout at a time, each +// under its own c.perCluster timeout. It returns the successful results and the +// IDs of clusters that failed for any reason other than 403 or 404; those two +// are skipped silently. An error from /clusters itself is returned. +func fanOut[T any](ctx context.Context, c *Client, fn func(context.Context) (T, error)) ([]clusterResult[T], []string, error) { + var reg struct { + Items []struct { + Name string `json:"name"` + } `json:"items"` + } + if err := c.get(ctx, "/clusters", nil, ®); err != nil { + return nil, nil, err + } + + parent := reader.TargetFrom(ctx) + ids := make([]string, 0, len(reg.Items)) + seen := make(map[string]bool, len(reg.Items)) + for _, it := range reg.Items { + id := strings.TrimSpace(it.Name) + if id == "" || seen[id] { + continue + } + seen[id] = true + ids = append(ids, id) + } + + width := c.fanout + if width < 1 { + width = 1 + } + timeout := c.perCluster + if timeout <= 0 { + timeout = defaultPerCluster + } + + results := make([]clusterResult[T], len(ids)) + errs := make([]error, len(ids)) + sem := make(chan struct{}, width) + var wg sync.WaitGroup + for i, id := range ids { + wg.Add(1) + go func() { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + + cctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cctx = reader.WithTarget(cctx, reader.Target{Cluster: id, Server: parent.Server}) + val, err := fn(cctx) + results[i] = clusterResult[T]{id: id, val: val} + errs[i] = err + }() + } + wg.Wait() + + var ok []clusterResult[T] + var unavailable []string + for i := range ids { + switch { + case errs[i] == nil: + ok = append(ok, results[i]) + case isSkippedStatus(errs[i]): + default: + unavailable = append(unavailable, ids[i]) + } + } + return ok, unavailable, nil +} + +// isSkippedStatus reports whether err is a 403 or 404 from the API. +func isSkippedStatus(err error) bool { + var apiErr *APIError + if !errors.As(err, &apiErr) { + return false + } + return apiErr.Status == http.StatusForbidden || apiErr.Status == http.StatusNotFound +} + +// annotateCluster sets the cluster annotation on an object's annotation map. +func annotateCluster(anns map[string]string, id string) map[string]string { + if anns == nil { + anns = map[string]string{} + } + anns[clusterAnnotation] = id + return anns +} + +// unavailableNotice is the resource version that reports clusters whose +// results are missing from a merged list. +func unavailableNotice(ids []string) string { + return "unavailable clusters: " + strings.Join(ids, ", ") +} + +// listCRDAcross merges kind across every cluster, annotating each item. +func (c *Client) listCRDAcross(ctx context.Context, k kindInfo, ns, sel string) (*unstructured.UnstructuredList, error) { + results, unavailable, err := fanOut(ctx, c, func(ctx context.Context) (*unstructured.UnstructuredList, error) { + return c.listCRDLocal(ctx, k, ns, sel) + }) + if err != nil { + return nil, err + } + var items []unstructured.Unstructured + for _, r := range results { + for i := range r.val.Items { + it := r.val.Items[i] + it.SetAnnotations(annotateCluster(it.GetAnnotations(), r.id)) + items = append(items, it) + } + } + merged := unstructuredList(k.kind, items) + if len(unavailable) > 0 { + merged.SetResourceVersion(unavailableNotice(unavailable)) + } + return merged, nil +} + +// listPodsAcross merges pods across every cluster, annotating each pod. +func (c *Client) listPodsAcross(ctx context.Context, ns, sel string) (*corev1.PodList, error) { + results, unavailable, err := fanOut(ctx, c, func(ctx context.Context) (*corev1.PodList, error) { + return c.listPodsLocal(ctx, ns, sel) + }) + if err != nil { + return nil, err + } + merged := &corev1.PodList{} + for _, r := range results { + for i := range r.val.Items { + p := r.val.Items[i] + p.Annotations = annotateCluster(p.Annotations, r.id) + merged.Items = append(merged.Items, p) + } + } + if len(unavailable) > 0 { + merged.ResourceVersion = unavailableNotice(unavailable) + } + return merged, nil +} + +// listEventsAcross merges events across every cluster, annotating each event. +func (c *Client) listEventsAcross(ctx context.Context, ns, fsel string) (*corev1.EventList, error) { + results, unavailable, err := fanOut(ctx, c, func(ctx context.Context) (*corev1.EventList, error) { + return c.listEventsLocal(ctx, ns, fsel) + }) + if err != nil { + return nil, err + } + merged := &corev1.EventList{} + for _, r := range results { + for i := range r.val.Items { + e := r.val.Items[i] + e.Annotations = annotateCluster(e.Annotations, r.id) + merged.Items = append(merged.Items, e) + } + } + if len(unavailable) > 0 { + merged.ResourceVersion = unavailableNotice(unavailable) + } + return merged, nil +} diff --git a/internal/panel/fanout_test.go b/internal/panel/fanout_test.go new file mode 100644 index 0000000..b564fcf --- /dev/null +++ b/internal/panel/fanout_test.go @@ -0,0 +1,187 @@ +package panel + +import ( + "context" + "net/http" + "testing" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +const clustersReply = `{"items":[{"name":"east"},{"name":"west"}]}` + +func TestFanOutMergesAndAnnotatesClusters(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(clustersReply), + "/pods": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"mc-east","namespace":"games"}}]}`), + "west": reply(`{"items":[{"metadata":{"name":"mc-west","namespace":"games"}}]}`), + }), + }) + + pods, err := c.ListPods(context.Background(), "games", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if len(pods.Items) != 2 { + t.Fatalf("want 2 pods, got %d", len(pods.Items)) + } + wantCluster := map[string]string{"mc-east": "east", "mc-west": "west"} + for _, p := range pods.Items { + if got := p.Annotations[clusterAnnotation]; got != wantCluster[p.Name] { + t.Errorf("pod %s annotation = %q, want %q", p.Name, got, wantCluster[p.Name]) + } + } + if pods.ResourceVersion != "" { + t.Errorf("nothing unavailable, want empty resource version, got %q", pods.ResourceVersion) + } + + reqs := api.requests() + clusterCalls := 0 + for _, r := range reqs { + if r.path == "/clusters" { + clusterCalls++ + } + } + if clusterCalls != 1 { + t.Errorf("want one /clusters call, got %d", clusterCalls) + } + assertGETWithAuth(t, reqs) +} + +func TestFanOutAnnotatesUnstructuredAndEvents(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(clustersReply), + "/templates": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"mc-java"}}]}`), + "west": reply(`{"items":[{"metadata":{"name":"mc-bedrock"}}]}`), + }), + "/kube-events": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"ev1","namespace":"games"},"reason":"Started"}]}`), + "west": reply(`{"items":[]}`), + }), + }) + ctx := context.Background() + + tmpls, err := c.ListCRD(ctx, "GameTemplate", "", "") + if err != nil { + t.Fatalf("ListCRD: %v", err) + } + if len(tmpls.Items) != 2 { + t.Fatalf("want 2 templates, got %d", len(tmpls.Items)) + } + wantCluster := map[string]string{"mc-java": "east", "mc-bedrock": "west"} + for _, it := range tmpls.Items { + if got := it.GetAnnotations()[clusterAnnotation]; got != wantCluster[it.GetName()] { + t.Errorf("template %s annotation = %q, want %q", it.GetName(), got, wantCluster[it.GetName()]) + } + } + + events, err := c.ListEvents(ctx, "games", "") + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if len(events.Items) != 1 { + t.Fatalf("want 1 event, got %d", len(events.Items)) + } + if got := events.Items[0].Annotations[clusterAnnotation]; got != "east" { + t.Errorf("event annotation = %q, want east", got) + } +} + +func TestFanOutReportsUnavailableClusters(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(`{"items":[{"name":"east"},{"name":"bad"}]}`), + "/pods": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"mc-east","namespace":"games"}}]}`), + "bad": fail(http.StatusInternalServerError, "boom"), + }), + }) + + pods, err := c.ListPods(context.Background(), "games", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if len(pods.Items) != 1 || pods.Items[0].Name != "mc-east" { + t.Errorf("want only mc-east, got %d items", len(pods.Items)) + } + if want := "unavailable clusters: bad"; pods.ResourceVersion != want { + t.Errorf("resource version = %q, want %q", pods.ResourceVersion, want) + } +} + +func TestFanOutSkipsForbiddenAndMissingClustersSilently(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(`{"items":[{"name":"east"},{"name":"locked"},{"name":"gone"}]}`), + "/pods": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"mc-east","namespace":"games"}}]}`), + "locked": fail(http.StatusForbidden, "no access"), + "gone": fail(http.StatusNotFound, "no such cluster"), + }), + }) + + pods, err := c.ListPods(context.Background(), "games", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if len(pods.Items) != 1 { + t.Errorf("want 1 pod, got %d", len(pods.Items)) + } + if pods.ResourceVersion != "" { + t.Errorf("403 and 404 clusters are skipped silently, want empty resource version, got %q", pods.ResourceVersion) + } +} + +func TestExplicitClusterIsASingleRequest(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(clustersReply), + "/pods": reply(`{"items":[{"metadata":{"name":"mc-east","namespace":"games"}}]}`), + }) + + pods, err := c.ListPods(clusterCtx("east"), "games", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if len(pods.Items) != 1 { + t.Errorf("want 1 pod, got %d", len(pods.Items)) + } + reqs := api.requests() + if len(reqs) != 1 { + t.Fatalf("want exactly 1 request, got %d: %+v", len(reqs), reqs) + } + if reqs[0].path != "/pods" || reqs[0].query.Get("cluster") != "east" { + t.Errorf("request = %s cluster=%q, want /pods cluster=east", reqs[0].path, reqs[0].query.Get("cluster")) + } +} + +func TestFanOutReturnsClusterListError(t *testing.T) { + c, _ := newTestClient(t, map[string]handlerFunc{ + "/clusters": fail(http.StatusInternalServerError, "registry down"), + }) + if _, err := c.ListPods(context.Background(), "games", ""); err == nil { + t.Fatal("want the /clusters error to be returned") + } +} + +// Ensure the fan-out context keeps the server target from the caller. +func TestFanOutKeepsServerTarget(t *testing.T) { + c, api := newTestClient(t, map[string]handlerFunc{ + "/clusters": reply(`{"items":[{"name":"east"}]}`), + "/servers/mc/pods": byCluster(map[string]handlerFunc{ + "east": reply(`{"items":[{"metadata":{"name":"mc-0","namespace":"games"}}]}`), + }), + }) + ctx := reader.WithTarget(context.Background(), reader.Target{Server: "mc"}) + pods, err := c.ListPods(ctx, "games", "") + if err != nil { + t.Fatalf("ListPods: %v", err) + } + if len(pods.Items) != 1 { + t.Errorf("want 1 pod, got %d", len(pods.Items)) + } + for _, r := range api.requests() { + if r.path == "/pods" { + t.Errorf("server target was dropped: request went to /pods") + } + } +} diff --git a/internal/panel/source_test.go b/internal/panel/source_test.go new file mode 100644 index 0000000..8c5de8f --- /dev/null +++ b/internal/panel/source_test.go @@ -0,0 +1,64 @@ +package panel + +import ( + "os" + "regexp" + "strconv" + "strings" + "testing" +) + +// The tripwire reads this package's own non-test sources and fails on any +// request shape other than a GET issued from get. +var ( + httpMethodRef = regexp.MustCompile(`http\.Method\w*`) + bannedVerbCall = regexp.MustCompile(`\.(Post|PostForm|Put|Patch|Delete|Head)\(`) + doCall = regexp.MustCompile(`\.Do\(`) + newRequestCall = regexp.MustCompile(`http\.NewRequest\(`) + funcDecl = regexp.MustCompile(`^func (?:\([^)]*\)\s*)?(\w+)`) +) + +func TestPanelSourceOnlyIssuesGET(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatalf("read package dir: %v", err) + } + checked := 0 + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + checked++ + data, err := os.ReadFile(name) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + current := "" + for i, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "func ") { + if m := funcDecl.FindStringSubmatch(line); m != nil { + current = m[1] + } + } + where := name + ":" + strconv.Itoa(i+1) + for _, ref := range httpMethodRef.FindAllString(line, -1) { + if ref != "http.MethodGet" { + t.Errorf("%s uses %s; the panel client may only issue GET", where, ref) + } + } + if newRequestCall.MatchString(line) { + t.Errorf("%s calls http.NewRequest; use http.NewRequestWithContext in get", where) + } + if m := bannedVerbCall.FindString(line); m != "" { + t.Errorf("%s calls %s; the panel client may only issue GET", where, m) + } + if doCall.MatchString(line) && current != "get" { + t.Errorf("%s calls Do outside get (in %s)", where, current) + } + } + } + if checked == 0 { + t.Fatal("no non-test sources found; the tripwire checked nothing") + } +} diff --git a/internal/reader/reader.go b/internal/reader/reader.go new file mode 100644 index 0000000..a817404 --- /dev/null +++ b/internal/reader/reader.go @@ -0,0 +1,45 @@ +// Package reader defines the read-only surface every MCP tool handler uses. +// +// Two implementations satisfy Reader: kube.Client (break-glass mode, reads the +// local cluster with the kubeconfig's own credentials) and panel.Client +// (per-user mode, reads through the Gameplane API as the MCP token's user). +// Both expose only List/Get-shaped methods, so a handler that holds a Reader +// cannot issue a mutating call through it. +package reader + +import ( + "context" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +// Target carries per-call selection that the tool arguments supply. It +// travels in the context so the Reader signatures stay unchanged. +type Target struct { + Cluster string // registered cluster ID; empty = all permitted clusters (lists) or the local cluster (gets) + Server string // GameServer name the call is about; empty = none +} + +type targetKey struct{} + +// WithTarget returns a copy of ctx that carries t. +func WithTarget(ctx context.Context, t Target) context.Context { + return context.WithValue(ctx, targetKey{}, t) +} + +// TargetFrom returns the Target carried by ctx, or the zero Target. +func TargetFrom(ctx context.Context) Target { + t, _ := ctx.Value(targetKey{}).(Target) + return t +} + +// Reader is implemented by kube.Client (break-glass) and panel.Client (per-user). +type Reader interface { + ListCRD(ctx context.Context, kind, namespace, labelSelector string) (*unstructured.UnstructuredList, error) + GetCRD(ctx context.Context, kind, namespace, name string) (*unstructured.Unstructured, error) + ListPods(ctx context.Context, namespace, labelSelector string) (*corev1.PodList, error) + GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error) + ListEvents(ctx context.Context, namespace, fieldSelector string) (*corev1.EventList, error) + PodLogs(ctx context.Context, namespace, pod, container string, tailLines int64, previous bool) (string, error) +} diff --git a/main.go b/main.go index ca2b61d..1f2d559 100644 --- a/main.go +++ b/main.go @@ -7,24 +7,26 @@ // // That is a hard invariant, held by two layers: // 1. The handler boundary: every tool handler in this package (tools.go, -// fixadvice.go) takes a *kube.Client (internal/kube/client.go), whose -// only exported methods are List/Get-shaped (ListCRD, GetCRD, ListPods, -// GetPod, ListEvents, PodLogs). The typed and dynamic Kubernetes -// clientsets behind it are unexported fields in a different package, -// so a handler that holds only the *kube.Client cannot call -// Create/Update/Delete/Patch/Apply through it. The boundary is on the -// *kube.Client, not on this package: runServe loads the *rest.Config -// itself, so keeping handlers on the *kube.Client (and having no -// mutating call site anywhere in this module) is a code convention, -// not a compile-time guarantee. main_test.go's -// TestClientHasNoMutatingMethods is a tripwire on kube.Client's -// exported method set. -// 2. By RBAC: the Helm chart's mcpServer.enabled ClusterRole grants only -// get/list/watch (plus get on pods/log) — see -// charts/gameplane/templates/mcp-server.yaml. This is the authoritative -// layer and the only one that stops mutation by any code in the -// process: the API server rejects a write from this ServiceAccount -// whatever client makes it. +// fixadvice.go) takes a reader.Reader (internal/reader). Its two +// implementations expose only List/Get-shaped methods (ListCRD, GetCRD, +// ListPods, GetPod, ListEvents, PodLogs): the break-glass *kube.Client +// (internal/kube) and the per-user *panel.Client (internal/panel), which +// issues only GET requests against the Gameplane API. A handler that +// holds a reader.Reader cannot call Create/Update/Delete/Patch/Apply +// through it. This is a code convention enforced by the method sets, +// not a compile-time guarantee: runServe loads the *rest.Config itself. +// main_test.go's TestClientHasNoMutatingMethods and +// panel_invariants_test.go's TestPanelClientHasNoMutatingMethods are +// tripwires on the two exported method sets. +// 2. By RBAC or by the API: in break-glass mode the Helm chart's +// mcp-server ServiceAccount holds only get/list/watch (plus get on +// pods/log), as namespaced Roles in the release namespace and each managed +// game namespace plus a ClusterRole for the cluster-scoped kinds — see +// charts/gameplane/templates/mcp-server.yaml. In per-user mode the process +// holds no Kubernetes permissions at all: the Gameplane API applies the +// token's user, namespace and per-cluster grants, and accepts only GET +// from the MCP token. The API server (or the Gameplane API) rejects a +// write whatever client makes it. // // A third, cosmetic layer: every tool this server installs (tools.go) // carries ReadOnlyHint: true, and main_test.go's @@ -36,29 +38,41 @@ // is deliberately standalone (own module, like audit-syslog-bridge and // telemetry-receiver) so it can run anywhere: in-cluster via the Helm // chart's mcpServer.enabled, or locally against a kubeconfig for a dev -// cluster. +// cluster, or on a laptop against a Gameplane API in per-user mode. // // Two subcommands: // // idle (default, no args) — block until terminated. This is what the // Helm Deployment runs as its long-lived container process, purely // so there is always a live container to `kubectl exec` into. -// serve — run the actual MCP stdio session for one client. Point an MCP -// host's launcher at: +// serve — run the actual MCP stdio session for one client. Flags: +// --panel-url (env GAMEPLANE_PANEL_URL) Gameplane API base URL. +// Set: per-user mode, token from GAMEPLANE_MCP_TOKEN. +// Unset: break-glass mode against the kubeconfig. +// --panel-ca (env GAMEPLANE_PANEL_CA) PEM CA bundle for a private +// panel certificate (per-user mode). +// Break-glass mode also reads GAMEPLANE_MCP_NAMESPACES, a +// comma-separated namespace allow-list; unset means unrestricted. +// Point an MCP host's launcher at, for example: // kubectl exec -i deploy/gameplane-mcp-server -n -- /mcp-server serve // Each exec spawns an independent, isolated session sharing the // pod's ServiceAccount credentials and network access — concurrent // sessions don't interfere with each other or with the idle // placeholder process. +// +// Stdout is the MCP stream, so every log line goes to stderr. package main import ( "context" "errors" + "flag" "fmt" "log/slog" + "net/url" "os" "os/signal" + "strings" "syscall" ctrl "sigs.k8s.io/controller-runtime" @@ -66,12 +80,17 @@ import ( "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/GameplanePanel/gameplane/mcp-server/internal/kube" + "github.com/GameplanePanel/gameplane/mcp-server/internal/panel" + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" ) // Version is set at build time via -ldflags "-X main.Version=...". var Version = "dev" func main() { + // stdout carries the MCP stream; diagnostics must go to stderr. + slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, nil))) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() @@ -85,7 +104,7 @@ func main() { case "idle": runIdle(ctx) case "serve": - err = runServe(ctx) + err = runServe(ctx, os.Args[2:]) default: slog.Error("unknown subcommand", "name", cmd) os.Exit(2) @@ -106,28 +125,70 @@ func runIdle(ctx context.Context) { slog.Info("mcp-server idle: shutting down") } -// runServe builds a cluster client and runs one MCP session over stdio -// until the client disconnects or ctx is cancelled. -func runServe(ctx context.Context) error { - cfg, err := ctrl.GetConfig() - if err != nil { - return fmt.Errorf("load kubeconfig: %w", err) +// runServe picks a reader for the session (per-user panel client when a panel +// URL is set, otherwise break-glass kube client), then runs one MCP session +// over stdio until the client disconnects or ctx is cancelled. +func runServe(ctx context.Context, args []string) error { + fs := flag.NewFlagSet("serve", flag.ContinueOnError) + panelURL := fs.String("panel-url", os.Getenv("GAMEPLANE_PANEL_URL"), "Gameplane API base URL; when set, serve in per-user mode") + panelCA := fs.String("panel-ca", os.Getenv("GAMEPLANE_PANEL_CA"), "PEM CA bundle for a private Gameplane API certificate (per-user mode)") + if err := fs.Parse(args); err != nil { + return fmt.Errorf("parse serve flags: %w", err) } - client, err := kube.New(cfg) - if err != nil { - return fmt.Errorf("build kubernetes client: %w", err) + + var rd reader.Reader + if *panelURL != "" { + token := os.Getenv("GAMEPLANE_MCP_TOKEN") + if token == "" { + return errors.New("GAMEPLANE_MCP_TOKEN is required when GAMEPLANE_PANEL_URL is set") + } + pc, err := panel.New(*panelURL, token, *panelCA) + if err != nil { + return fmt.Errorf("build panel client: %w", err) + } + slog.Info("mcp-server serve: per-user mode", "panel", redactURL(*panelURL)) + rd = pc + } else { + cfg, err := ctrl.GetConfig() + if err != nil { + return fmt.Errorf("load kubeconfig: %w", err) + } + client, err := kube.New(cfg) + if err != nil { + return fmt.Errorf("build kubernetes client: %w", err) + } + nss := kube.ParseNamespaces(os.Getenv("GAMEPLANE_MCP_NAMESPACES")) + client.WithNamespaces(nss) + scope := "unrestricted" + if len(nss) > 0 { + scope = strings.Join(nss, ",") + } + slog.Info("mcp-server serve: break-glass mode", "namespaces", scope) + rd = client } - server := newMCPServer(client) + server := newMCPServer(rd) if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil && !errors.Is(err, context.Canceled) { return fmt.Errorf("mcp session: %w", err) } return nil } +// redactURL returns raw without its query, fragment or user info, for logging. +func redactURL(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + u.RawQuery = "" + u.Fragment = "" + u.User = nil + return u.String() +} + // newMCPServer builds the MCP server and installs every read-only tool // against c. -func newMCPServer(c *kube.Client) *mcp.Server { +func newMCPServer(c reader.Reader) *mcp.Server { server := mcp.NewServer(&mcp.Implementation{ Name: "gameplane-mcp-server", Version: Version, @@ -135,7 +196,11 @@ func newMCPServer(c *kube.Client) *mcp.Server { Instructions: "Strictly read-only access to a Gameplane cluster: list/get 7 of " + "Gameplane's 9 CRDs (not Cluster or NetworkCapture), Pods, Events, and pod " + "logs, and get suggested fixes as text via propose_fix. No tool here ever " + - "creates, updates, patches, deletes, or applies anything.", + "creates, updates, patches, deletes, or applies anything. In per-user mode " + + "reads go through the Gameplane API as the token's user, across the clusters " + + "that user may read (pass cluster to pick one; list results are annotated " + + "gameplane.local/cluster). In break-glass mode reads go to the local " + + "cluster's Gameplane namespaces only.", }) registerTools(server, c) return server diff --git a/panel_invariants_test.go b/panel_invariants_test.go new file mode 100644 index 0000000..c9222ee --- /dev/null +++ b/panel_invariants_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "reflect" + "strings" + "testing" + + "github.com/GameplanePanel/gameplane/mcp-server/internal/kube" + "github.com/GameplanePanel/gameplane/mcp-server/internal/panel" + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" +) + +// panelMutatingVerbs is the denylist for the per-user client's exported +// method set. The per-user client only ever reads, so none of these may +// appear as a method-name prefix. +var panelMutatingVerbs = []string{"Create", "Update", "Delete", "Patch", "Apply", "Post", "Put"} + +// TestPanelClientHasNoMutatingMethods is the per-user counterpart of +// TestClientHasNoMutatingMethods: the panel client's only request builder is +// get, which issues GET (internal/panel/source_test.go enforces that), and +// its exported surface must not look like a write either. +func TestPanelClientHasNoMutatingMethods(t *testing.T) { + typ := reflect.TypeOf(&panel.Client{}) + for i := 0; i < typ.NumMethod(); i++ { + name := typ.Method(i).Name + for _, verb := range panelMutatingVerbs { + if strings.HasPrefix(name, verb) { + t.Errorf("panel.Client has mutating-looking method %q (matches verb %q)", name, verb) + } + } + } +} + +// TestReadersImplementInterface checks both reader implementations at compile +// time and at run time, so a signature drift in either shows up here. +func TestReadersImplementInterface(t *testing.T) { + var _ reader.Reader = (*kube.Client)(nil) + var _ reader.Reader = (*panel.Client)(nil) + + readerType := reflect.TypeOf((*reader.Reader)(nil)).Elem() + for _, typ := range []reflect.Type{reflect.TypeOf(&kube.Client{}), reflect.TypeOf(&panel.Client{})} { + if !typ.Implements(readerType) { + t.Errorf("%s does not implement reader.Reader", typ) + } + } +} diff --git a/specs.md b/specs.md index ec2af12..92499a0 100644 --- a/specs.md +++ b/specs.md @@ -7,48 +7,71 @@ ## Purpose -Optional, strictly **read-only** Model Context Protocol (MCP) server that exposes cluster state from a Gameplane deployment. Lets an AI assistant read 7 of Gameplane's 9 CRDs (not Cluster or NetworkCapture), Pods, Events, and pod logs, and receive suggested fixes as plain text (YAML and/or `kubectl` commands) for a human operator to review and apply. Speaks MCP (JSON-RPC 2.0) over stdio, not a network port. +Optional, strictly **read-only** Model Context Protocol (MCP) server that exposes Gameplane state to an AI assistant. It reads 7 of Gameplane's 9 CRDs (not Cluster or NetworkCapture), Pods, Events, and pod logs, and returns suggested fixes as plain text (YAML and/or `kubectl` commands) for a human operator to review and apply. It runs in one of two modes: + +- **Per-user** (`GAMEPLANE_PANEL_URL` set): reads through the Gameplane API as the owner of an MCP token, across the clusters that user may read. The process holds no Kubernetes credentials. +- **Break-glass** (no panel URL): reads the local cluster directly with the process's Kubernetes credentials, optionally limited to a namespace allow-list. For administrators; works while the API is down. + +It speaks MCP (JSON-RPC 2.0) over stdio, not a network port. ## Responsibilities 1. **Expose read-only MCP tools** — 7 tools listed below, all List/Get-shaped or text-generating. -2. **Guarantee read-only operation** — through three independent enforcement layers (see Key Invariants). +2. **Guarantee read-only operation** — through layered enforcement (see Key Invariants). 3. **Index 7 of Gameplane's 9 CRDs** — GameServer, GameTemplate, Backup, BackupSchedule, Restore, Module, ModuleSource (not Cluster or NetworkCapture), by name and optional label selector. -4. **Expose core Kubernetes resources** — Pods, Events, and pod logs, scoped to namespace (or all namespaces). -5. **Generate fix suggestions** — the `propose_fix` tool matches symptoms against heuristic keyword rules and returns suggested diagnostics and remediation steps as plain text. -6. **Support two subcommands** — `idle` (the default, long-lived Deployment process) and `serve` (per-client MCP session over stdio). +4. **Expose core Kubernetes resources** — Pods, Events, and pod logs, scoped to namespace (or all namespaces in the selected scope). +5. **Select the read scope per call** — an optional `cluster` argument (per-user mode) and `server` argument carried to the readers through `reader.Target` in the request context. +6. **Generate fix suggestions** — the `propose_fix` tool matches symptoms against heuristic keyword rules and returns suggested diagnostics and remediation steps as plain text. +7. **Support two subcommands** — `idle` (the default, long-lived Deployment process) and `serve` (per-client MCP session over stdio, in either mode). ## Non-goals / boundaries -- **No mutations** — never creates, updates, patches, deletes, or applies anything. Guarded structurally and by RBAC. -- **No HTTP port** — stdio-only transport, no listening socket. +- **No mutations** — never creates, updates, patches, deletes, or applies anything. Guarded structurally, by RBAC (break-glass) and by the API's token guard (per-user). +- **No HTTP port** — stdio-only transport, no listening socket. The per-user client is an outbound HTTPS client only. - **No LLM calls** — fix suggestions are deterministic, keyword-matched heuristic text. -- **No config management** — reads Kubernetes objects as-is; does not validate them, enforce schemas, or trigger reconciliation. +- **No config management** — reads Kubernetes objects and API responses as-is; does not validate them, enforce schemas, or trigger reconciliation. +- **No cross-cluster writes or gets** — cross-cluster fan-out applies to lists only. - For run instructions and Helm values, see `mcp-server/README.md`. ## Directory & package layout ``` mcp-server/ -├── main.go # Entry point; idle/serve subcommands; newMCPServer -├── tools.go # Tool registration; 7 handler functions; readOnlyTool helper +├── main.go # Entry point; idle/serve subcommands (serve flags, mode selection); newMCPServer +├── tools.go # Tool registration; 7 handler functions taking reader.Reader; readOnlyTool helper ├── fixadvice.go # Heuristic advice text; buildFixSuggestion; matchFixRules -├── main_test.go # Tool-set registration tests; client invariant tripwire test +├── main_test.go # Tool-set registration tests; kube client invariant tripwire +├── panel_invariants_test.go # Panel client invariant tripwire; both clients satisfy reader.Reader +├── internal/reader/ +│ └── reader.go # Reader interface (six read methods); Target and WithTarget/TargetFrom context helpers ├── internal/kube/ -│ ├── client.go # Read-only Client struct; List/Get methods; CRDKinds registry +│ ├── client.go # Break-glass Client; namespace allow-list (WithNamespaces, ParseNamespaces); List/Get methods; CRDKinds registry +│ ├── allowlist_test.go # Allow-list and cluster-rejection tests (fake clientsets) │ └── client_test.go # Fake client tests +├── internal/panel/ +│ ├── client.go # Per-user Client; New; single GET request helper (get); kind→path table; per-kind reads +│ ├── fanout.go # Cross-cluster fan-out for list calls; cluster annotation; unavailable-cluster notice +│ ├── client_test.go # httptest-based path, header, error and conversion tests +│ ├── fanout_test.go # Fan-out merge, unavailable and skipped-cluster tests +│ └── source_test.go # Source tripwire: GET-only HTTP usage in the package ├── go.mod # Dependencies ├── go.sum ├── .testcoverage.yml # Coverage gate (70%) -└── README.md # Run instructions; RBAC blast radius; transport details +└── README.md # Run instructions; two modes; RBAC scope; transport details ``` ## External interface / contracts ### Subcommands -- **`idle`** (default, no args) — blocks indefinitely until signaled (SIGTERM/SIGINT). Performs no cluster access. Used as the Helm Deployment's container process so a live pod exists for `kubectl exec` to attach to. -- **`serve`** — builds a Kubernetes client (via `ctrl.GetConfig()`, supports in-cluster or kubeconfig), runs one MCP session over stdio until the client disconnects. Paired with `kubectl exec -i deploy/gameplane-mcp-server -n -- /mcp-server serve`. +- **`idle`** (default, no args) — blocks indefinitely until signaled (SIGTERM/SIGINT). Performs no cluster or API access. Used as the Helm Deployment's container process so a live pod exists for `kubectl exec` to attach to. +- **`serve [--panel-url URL] [--panel-ca FILE]`** — runs one MCP session over stdio until the client disconnects. Flags are parsed with `flag.NewFlagSet("serve", flag.ContinueOnError)`. + - `--panel-url` (env `GAMEPLANE_PANEL_URL`): when set, per-user mode. The URL is parsed and must use `https`, or `http` for a `localhost` or loopback host. Userinfo and query are rejected or stripped. Logged with the query removed. + - `--panel-ca` (env `GAMEPLANE_PANEL_CA`): PEM CA bundle appended to the system cert pool, TLS 1.2 minimum. Per-user mode only. + - `GAMEPLANE_MCP_TOKEN` (environment only, no flag): required in per-user mode and must start with `gpmcp_`. Its absence is a start-up error. It never appears in logs or errors. + - Break-glass (no panel URL): builds the Kubernetes client via `ctrl.GetConfig()` (in-cluster or kubeconfig) and applies the namespace allow-list from `GAMEPLANE_MCP_NAMESPACES` (comma-separated; unset means unrestricted). + - Logging: `slog` writes to stderr, since stdout is the MCP stream. `main` sets the default handler first. + - Usage example: `kubectl exec -i deploy/gameplane-mcp-server -n -- /mcp-server serve` (break-glass), or `GAMEPLANE_PANEL_URL=… GAMEPLANE_MCP_TOKEN=gpmcp_… mcp-server serve` (per-user). ### Registered tools (7 total) @@ -56,105 +79,126 @@ From `tools.go` `registeredToolNames`: | Tool | Input | Output | |---|---|---| -| `list_gameplane_resources` | `kind` (e.g., "GameServer"), optional `namespace`, optional `labelSelector` | Unstructured list of CRD objects as JSON | -| `get_gameplane_resource` | `kind`, optional `namespace`, `name` | Single Gameplane CRD object as JSON | -| `list_pods` | Optional `namespace`, optional `labelSelector` | Core Pod list as JSON | -| `get_pod` | `namespace`, `name` | Single Pod (spec+status) as JSON | -| `list_events` | Optional `namespace`, optional `fieldSelector`, optional `labelSelector` | Core Event list as JSON | -| `get_pod_logs` | `namespace`, `pod`, optional `container`, optional `tailLines` (capped 5000), optional `previous` | Log text (up to 256 KiB of the newest bytes; when truncated, prefixed with a notice) | -| `propose_fix` | Optional `kind`/`namespace`/`name`, required `symptom` (free text) | Suggested diagnostics + fix text (never applies anything) | +| `list_gameplane_resources` | `kind` (e.g., "GameServer"), optional `namespace`, optional `labelSelector`, optional `cluster` | Unstructured list of CRD objects as JSON | +| `get_gameplane_resource` | `kind`, optional `namespace`, `name`, optional `cluster` | Single Gameplane CRD object as JSON | +| `list_pods` | Optional `namespace`, optional `labelSelector`, optional `cluster`, optional `server` | Core Pod list as JSON | +| `get_pod` | `namespace`, `name`, optional `cluster` | Single Pod (spec+status) as JSON | +| `list_events` | Optional `namespace`, optional `fieldSelector`, optional `labelSelector`, optional `cluster`, optional `server` | Core Event list as JSON | +| `get_pod_logs` | `namespace`, `pod`, optional `container`, optional `tailLines` (capped 5000), optional `previous`, optional `cluster`, optional `server` | Log text (up to 256 KiB of the newest bytes; when truncated, prefixed with a notice) | +| `propose_fix` | Optional `kind`/`namespace`/`name`, optional `cluster`, required `symptom` (free text) | Suggested diagnostics + fix text (never applies anything) | + +**Scope arguments** (all optional, carried to the reader as `reader.Target`): + +- `cluster` — a registered cluster ID. Per-user mode only. Break-glass mode rejects any non-empty value with `errClusterNotAvailable`. Empty: list calls fan out across every cluster the user may read, each item annotated `gameplane.local/cluster`; get calls and log reads use the local cluster. +- `server` — a GameServer name. Accepted by `list_pods`, `list_events` and `get_pod_logs`. Per-user mode uses it to route pod, event and log reads through `/servers/{name}/…`. Break-glass mode ignores it. In per-user mode `get_pod_logs` requires it for game server pods. -Pod logs read the complete finite Kubernetes tail response while retaining only a 256 KiB rolling buffer. Long lines can make the requested tail exceed 4 MiB; the returned suffix still includes the actual final bytes. Request cancellation and stream read failures return errors instead of presenting partial output as the newest logs. +Pod logs read the complete finite Kubernetes tail response while retaining only a 256 KiB rolling buffer. Long lines can make the requested tail exceed 4 MiB; the returned suffix still includes the actual final bytes. Request cancellation and stream read failures return errors instead of presenting partial output as the newest logs. In per-user mode, logs come from the API's server-log route (`/servers/{name}/logs/pod/tail`), or from `/admin/system-logs/{api|operator}` for the Gameplane API and operator pods. Tail length is clamped: 0 becomes 200, values above 5000 become 5000. **Artifact scope:** - **7 of Gameplane's 9 CRDs** (not Cluster or NetworkCapture): GameServer, GameTemplate, Backup, BackupSchedule, Restore, Module, ModuleSource (4 namespaced, 3 cluster-scoped; verified against `CRDKinds` in `internal/kube/client.go`). - **Core resources**: `v1` Pods, Events, `pods/log` subresource. - **No write verbs**: no Create/Update/Patch/Delete/Apply anywhere. +### Reader contract (`internal/reader`) + +- `Reader` interface: `ListCRD`, `GetCRD`, `ListPods`, `GetPod`, `ListEvents`, `PodLogs`. Implemented by `*kube.Client` and `*panel.Client`. Both satisfy it, checked by `var _` assertions and `TestReadersImplementInterface`. +- `Target{Cluster, Server}` travels in the context (`WithTarget` / `TargetFrom`, unexported context key). Each tool handler sets it from its input before calling the reader. + +### Per-user API contract (`internal/panel`) + +- Every request is a `GET` to the Gameplane API, with `Authorization: Bearer `, an `X-Gameplane-MCP-Session` header (random per process), and `Accept: application/json`. `cluster=` is added to the query whenever the target names one. +- Kind to path: GameServer `servers`, GameTemplate `templates`, Backup `backups`, BackupSchedule `schedules`, Restore `restores`, Module `modules`, ModuleSource `modules/sources` (list-only; `GetCRD` lists and matches by name). Unknown kinds return an error listing the known kinds. +- Namespaced kinds: GameServer, Backup, BackupSchedule, Restore. An empty namespace on a namespaced kind loops over `/namespaces` for the selected cluster. For GameServer, a 403 on that namespace listing falls back to `/users/me/servers`, filtered to the namespace when one is given. +- Pods and events: `/pods`, `/servers/{name}/pods`, `/pods/{name}`, `/kube-events`, and `/servers/{name}/events`. The last returns rows that are converted to `corev1.Event`. With a `server` argument and no namespace, the server routes are called once without a namespace, so the API uses its default games namespace; pass `namespace` for a server in another managed namespace. +- Non-2xx responses become `*APIError{Status, Path, Message}`. Message is the body trimmed to 300 bytes, with the token redacted if echoed. 401 reads "not authenticated: the MCP token is missing, expired or revoked"; 403 and 404 prefix the message with "permission denied" and "not found"; other statuses use the generic form. +- Responses are capped at 32 MiB. + ### Transport -**MCP over stdio only**. The server uses `mcp.StdioTransport` and never opens a listening socket. A client connects by spawning the process with stdin/stdout/stderr piped to the MCP JSON-RPC stream. +**MCP over stdio only**. The server uses `mcp.StdioTransport` and never opens a listening socket. The per-user client makes outbound HTTPS requests only. A client connects by spawning the process with stdin/stdout/stderr piped to the MCP JSON-RPC stream. ## Key invariants -The read-only guarantee rests on **two enforcing layers** (the handler boundary and RBAC) plus a test tripwire. Only RBAC stops mutation by any code in the process: - -### 1. Handler boundary (`kube.Client`) - -**Source**: `mcp-server/internal/kube/client.go` (the `Client` struct, `New`, `NewFrom`), `mcp-server/main.go` (package doc comment and `runServe`). - -- The `kube.Client` struct (in package `internal/kube`) holds two unexported fields: - - `typed kubernetes.Interface` — typed clientset (supports all verbs) - - `dynamic dynamic.Interface` — dynamic client (supports all verbs) -- The **only exported methods on `Client`** are: - - `ListCRD`, `GetCRD` (CRD reads) - - `ListPods`, `GetPod` (Pod reads) - - `ListEvents` (Event reads) - - `PodLogs` (log reads) -- Every MCP tool handler lives in `package main` (`tools.go`, `fixadvice.go`) and receives `*kube.Client` as input. -- **What the boundary enforces**: a caller that holds only a `*kube.Client` cannot reach its unexported clientsets, so no tool handler can call `Create`, `Update`, `Delete`, `Patch`, or `Apply` through it. -- **What it does not enforce**: the boundary is on the `*kube.Client`, not on `package main`. `runServe` loads the `*rest.Config` itself (`ctrl.GetConfig()`) and passes it to `kube.New`. Keeping every handler on the `*kube.Client`, and having no mutating call site anywhere in the module, is a code convention checked in review, not a compile-time guarantee. Layer 2 is what stops mutation. - -### 2. RBAC backstop (authoritative) - -**Source**: `charts/gameplane/templates/mcp-server.yaml` lines 22–36. - -The Helm chart installs a `ClusterRole` with **only read verbs**: - -```yaml -rules: - - apiGroups: ["gameplane.local"] - resources: [gameservers, gametemplates, backups, backupschedules, restores, modules, modulesources] - verbs: [get, list, watch] - - apiGroups: [""] - resources: [pods, events] - verbs: [get, list, watch] - - apiGroups: [""] - resources: [pods/log] - verbs: [get] -``` +The read-only guarantee rests on layered enforcement: the handler boundary (method sets), the authoritative backstop (RBAC in break-glass mode, the API's token guard in per-user mode), and test tripwires. + +### 1. Handler boundary (`reader.Reader`) + +**Source**: `mcp-server/internal/reader/reader.go`, `mcp-server/internal/kube/client.go`, `mcp-server/internal/panel/client.go`, `mcp-server/main.go` (package doc comment and `runServe`). + +- Every tool handler (`tools.go`, `fixadvice.go`) takes a `reader.Reader`. Its method set is the six List/Get-shaped methods only. +- **Break-glass `kube.Client`** holds two unexported fields, `typed kubernetes.Interface` and `dynamic dynamic.Interface`, and its only exported methods are the six reader methods plus `New`, `NewFrom`, `WithNamespaces` and `ParseNamespaces`. +- **Per-user `panel.Client`** holds an HTTP client, base URL, token and session ID. Its only exported methods are the six reader methods plus `New`. Every request is built in one unexported helper, `get`, which uses `http.NewRequestWithContext(ctx, http.MethodGet, …)`. +- **What the boundary enforces**: a caller that holds only a `reader.Reader` cannot reach the Kubernetes clientsets or the panel's request builder, so no tool handler can call a mutating method through it. +- **What it does not enforce**: the boundary is a method-set convention, not a compile-time guarantee. `runServe` loads the `*rest.Config` itself (`ctrl.GetConfig()`). Layer 2 is what stops mutation. + +### 2. Backstop -- **No create/update/patch/delete verbs anywhere**. -- The ServiceAccount (`gameplane-mcp-server`) is bound to this role; any attempt to mutate (even if code somehow tried) is rejected by the API server with 403 Forbidden. -- This is the **authoritative** layer and the only one that stops mutation by any code in the process: the API server rejects a write from this ServiceAccount whatever client makes it. It covers the in-cluster ServiceAccount; a standalone run against a kubeconfig has that kubeconfig user's permissions instead. +**Break-glass — RBAC (authoritative)**: **Source**: `charts/gameplane/templates/mcp-server.yaml`. -### 3. Test tripwire (visible guarantee) +- Namespaced Roles in the release namespace and in each managed game namespace grant pods, events and `pods/log` reads. In game namespaces they also grant GameServer, Backup, BackupSchedule and Restore reads. A ClusterRole covers only GameTemplate, Module and ModuleSource. +- Every verb is `get`/`list`/`watch`, except `get` on `pods/log`. No create/update/patch/delete verb appears anywhere. +- The ServiceAccount (`gameplane-mcp-server`) is bound to these grants. Any write is rejected by the API server with 403 Forbidden, whatever code issues it. +- A standalone run against a kubeconfig has that kubeconfig user's permissions instead. -**Source**: `mcp-server/main_test.go` lines 28–50 and 68–104. +**Per-user — Gameplane API (authoritative)**: the process holds no Kubernetes permissions. The API applies the token user's roles, namespace grants and per-cluster grants. Its MCP-token guard accepts only `GET` on a fixed route list. The panel client's own `GET`-only rule is a defence in depth on top of that. -Two tests catch regressions: +### 3. Break-glass namespace allow-list -- **`TestClientHasNoMutatingMethods`** (lines 40–50): reflects over `kube.Client`'s method set; asserts no exported method name starts with Create, Update, Delete, Patch, or Apply. Catches a future mistake in `internal/kube/client.go` immediately. -- **`TestRegisteredToolsAreReadOnly`** (lines 73–104): connects a real MCP client over in-memory transports; asserts: +**Source**: `mcp-server/internal/kube/client.go`. + +- `WithNamespaces` sets an allow-list (trimmed, empties and duplicates dropped). `ParseNamespaces` splits the comma-separated environment value. An empty list means unrestricted, which is today's behaviour. +- When the list is set, an explicit namespace outside it returns `ErrNamespaceNotInScope` (wrapped with `%w`) before any API call. That applies to namespaced `ListCRD`/`GetCRD`, `ListPods`, `GetPod`, `ListEvents` and `PodLogs`. +- An empty namespace on `ListPods`, `ListEvents` and namespaced `ListCRD` loops over the allow-list in order and merges the items. A namespace that returns NotFound or Forbidden is skipped. If any were skipped, the merged list's resource version reads `skipped namespaces: `. Other errors are returned wrapped. +- With an allow-list set, `GetPod` and `PodLogs` need an explicit namespace (`namespace is required`), because a get has no namespace to loop over. +- Cluster-scoped kinds are unaffected. +- Break-glass rejects a non-empty `cluster` target with `errClusterNotAvailable` on every method. The `server` target is ignored. + +### 4. Per-user read rules + +**Source**: `mcp-server/internal/panel/client.go`, `mcp-server/internal/panel/fanout.go`. + +- Cross-cluster fan-out (`ListCRD`, `ListPods`, `ListEvents` with no `cluster` target): `/clusters` lists the clusters, and the same list runs for each at most 4 at a time, with a 10-second timeout per cluster. Items are annotated `gameplane.local/cluster`. A cluster that returns 403 or 404 is skipped silently. Any other failure marks the cluster unavailable, and the merged list's resource version reads `unavailable clusters: `. An error from `/clusters` itself is returned. +- Gets and logs never fan out. They use the selected cluster, or the local one when none is named. +- With an explicit `cluster`, a list is one request, with no `/clusters` call. + +### 5. Test tripwires (visible guarantees) + +- **`TestClientHasNoMutatingMethods`** (`main_test.go`): reflects over `kube.Client`'s method set and asserts no exported method name starts with Create, Update, Delete, Patch or Apply. +- **`TestPanelClientHasNoMutatingMethods`** (`panel_invariants_test.go`): the same check over `panel.Client`'s method set. +- **`TestReadersImplementInterface`** (`panel_invariants_test.go`): asserts both clients satisfy `reader.Reader`. +- **`internal/panel/source_test.go`**: reads the package's non-test `.go` files and fails if any contains an `http.Method` constant other than `http.MethodGet`, an `http.NewRequest(` call without `WithContext`, or a `.Post(`, `.PostForm(` or `.Do(` call outside the `get` helper. +- **`TestRegisteredToolsAreReadOnly`** (`main_test.go`): connects a real MCP client over in-memory transports; asserts: 1. Every registered tool name does not contain a mutating verb (case-insensitive substring search). 2. Every tool carries `Annotations.ReadOnlyHint = true`. 3. No tool has `DestructiveHint = true`. - 4. The tool set matches `registeredToolNames` exactly (from `tools.go` line 27). + 4. The tool set matches `registeredToolNames` exactly (from `tools.go`). -This test catches accidental registration of a mutating tool before it ships. - -**Note**: These tests are **visible guarantees** (for auditing), not enforcement. Layer 1 keeps tool handlers on read-only methods; layer 2 (RBAC) is the layer that stops mutation. +These tests are **visible guarantees** (for auditing), not enforcement. The method sets keep handlers on read-only operations; RBAC (break-glass) and the API's token guard (per-user) are what stop mutation. ## Dependencies -From `go.mod` (verified): +From `go.mod`: | Dependency | Version | Purpose | |---|---|---| | `github.com/modelcontextprotocol/go-sdk` | v1.8.0 | MCP protocol implementation (Server, tools, stdio transport) | | `k8s.io/api` | v0.37.0 | Kubernetes API types (corev1) | -| `k8s.io/apimachinery` | v0.37.0 | Kubernetes meta types, label/field selectors, dynamic client | +| `k8s.io/apimachinery` | v0.37.0 | Kubernetes meta types, label/field selectors, unstructured objects | | `k8s.io/client-go` | v0.37.0 | Kubernetes typed clientset, dynamic client, rest.Config | | `sigs.k8s.io/controller-runtime` | v0.25.1 | `ctrl.GetConfig()` for kubeconfig loading | +The per-user client uses only the standard library (`net/http`, `crypto/tls`, `crypto/x509`). + **Why these versions?** Kept in step with the Gameplane operator's Kubernetes dependencies; Dependabot in this repository proposes updates. ## Security considerations -1. **Read-only blast radius**: The ClusterRole grants get/list/watch cluster-wide (all namespaces), not just `gameplane-games`. Pod logs in any namespace may contain application secrets (API keys, connection strings); this is an accepted tradeoff on an opt-in component. -2. **No listening port**: No network surface to expose; reachable only via `kubectl exec`. -3. **Deployment model**: Opt-in via `mcpServer.enabled=true` in the Helm chart. Admin responsibility to decide if this is acceptable for their cluster. -4. **See [`docs/security.md`](https://github.com/GameplanePanel/Gameplane/blob/master/docs/security.md)** for the full threat model and per-cluster decisions (especially if cohabiting with unrelated sensitive workloads). +1. **Break-glass blast radius**: bounded by the chart's namespaced Roles (release namespace and managed game namespaces) and the ClusterRole for cluster-scoped kinds only. Setting `GAMEPLANE_MCP_NAMESPACES` further narrows reads in the process. A standalone run with no allow-list uses the kubeconfig's own permissions. Pod logs in any namespace the process can read may contain application secrets (API keys, connection strings); this is an accepted tradeoff on an opt-in, admin-only component. +2. **Per-user exposure**: the process holds a bearer MCP token (`gpmcp_…`) that carries the user's read access. Anyone with the token can read what that user can. The token is read from the environment only, never logged, and never echoed in errors. Revoke or expire it in the dashboard if it leaks. +3. **Transport security**: the panel URL must be `https`, except for a loopback host. A private CA is supported with `--panel-ca`. TLS minimum is 1.2. +4. **No listening port**: No network surface to expose. Reachable only via `kubectl exec` (break-glass) or the MCP host's spawned process (per-user). +5. **Deployment model**: Opt-in via `mcpServer.enabled=true` in the Helm chart (break-glass). Per-user mode runs wherever the operator chooses, with a token. Admin responsibility to decide if each is acceptable for their cluster. +6. **See [`docs/security.md`](https://github.com/GameplanePanel/Gameplane/blob/master/docs/security.md)** for the full threat model and per-cluster decisions (especially if cohabiting with unrelated sensitive workloads). ## Testing & coverage @@ -162,9 +206,19 @@ From `go.mod` (verified): - **Threshold**: 70% (from `.testcoverage.yml`). - **Measured against**: package-level aggregate (not per-file). -- **What's covered**: tool registration, read-only invariant tripwires (main_test.go), CRD/Pod/Event/log client helpers against fake clientsets, propose_fix heuristic advice text. +- **What's covered**: tool registration, read-only invariant tripwires, CRD/Pod/Event/log helpers against fake clientsets (break-glass), namespace allow-list behaviour, the per-user HTTP client against `httptest` servers, cross-cluster fan-out, propose_fix heuristic advice text. - **Uncovered**: main()/run() process wiring (signal handling, stdio transport) — not unit-testable. +### Test files + +- `main_test.go` — tool registration, registry, read-only tripwires, idle/serve wiring. +- `panel_invariants_test.go` — panel method-set tripwire and interface assertions. +- `internal/kube/allowlist_test.go` — out-of-scope namespace per method returns `ErrNamespaceNotInScope`; empty namespace merges only allowed namespaces; `Target.Cluster` set returns `errClusterNotAvailable`; `ParseNamespaces` normalises input; no allow-list lists across all namespaces. +- `internal/kube/client_test.go`, `log_tail_test.go` — break-glass client against fake clientsets; log tail helpers. +- `internal/panel/client_test.go` — each reader method's path and query; bearer and session headers; GET only; 401/403/404 messages; token absent from errors; server event conversion; GameServer 403 fallback to `/users/me/servers`; `New` URL and token validation; log tail clamp and system-logs routing; server-required error. +- `internal/panel/fanout_test.go` — two clusters merged and annotated; a 500 cluster listed as unavailable; a 403 cluster skipped silently; explicit `cluster` gives a single request with no `/clusters` call. +- `internal/panel/source_test.go` — source-level GET-only tripwire. + ### Test commands Run from this repository's root (CI runs the same through Gameplane's shared `go-component.yaml` workflow): @@ -175,9 +229,7 @@ go test -race ./... ### Key test cases -From `main_test.go`: - -- `TestClientHasNoMutatingMethods` — lint tripwire on Client's exported method set. +- `TestClientHasNoMutatingMethods` / `TestPanelClientHasNoMutatingMethods` — lint tripwires on both clients' exported method sets. - `TestRegisteredToolsAreReadOnly` — over-the-wire check: tool names, ReadOnlyHint, exact registry. - `TestToolsListAndGetHappyPath` — happy-path tests for list/get tools using fake clientsets. - `TestProposeFixTool` — propose_fix heuristic matching and fallback advice. @@ -185,8 +237,7 @@ From `main_test.go`: ## References -- **[`README.md`](README.md)** — run instructions, transport details, RBAC blast radius, tool descriptions. -- **`charts/gameplane/templates/mcp-server.yaml`** — Helm template (ServiceAccount, ClusterRole, Deployment). +- **[`README.md`](README.md)** — run instructions, two modes, RBAC scope, transport details, tool descriptions. +- **`charts/gameplane/templates/mcp-server.yaml`** — Helm template (ServiceAccount, namespaced Roles, ClusterRole, Deployment). - **[`docs/security.md`](https://github.com/GameplanePanel/Gameplane/blob/master/docs/security.md)** — threat model, mcp-server section, admin decision guidance. - **Model Context Protocol spec** — https://modelcontextprotocol.io/ - diff --git a/tools.go b/tools.go index 3999c8f..3e8a752 100644 --- a/tools.go +++ b/tools.go @@ -1,9 +1,10 @@ // Tool registration for the Gameplane MCP server. Every tool here is // List/Get-shaped (or, for propose_fix, pure text generation) — see the // package doc comment in main.go for why that's a hard invariant, not a -// convention: every handler below takes a *kube.Client, whose only exported -// methods are List/Get-shaped, so there is no mutating call these handlers -// could make even if they tried. readOnlyTool() below is the one place a +// convention: every handler below takes a reader.Reader (internal/reader), +// whose implementations (the break-glass *kube.Client and the per-user +// *panel.Client) expose only List/Get-shaped methods, so there is no mutating +// call these handlers could make even if they tried. readOnlyTool() below is the one place a // tool gets built, so there's a single spot to audit. package main @@ -19,7 +20,7 @@ import ( "github.com/modelcontextprotocol/go-sdk/mcp" - "github.com/GameplanePanel/gameplane/mcp-server/internal/kube" + "github.com/GameplanePanel/gameplane/mcp-server/internal/reader" ) // maxListEvents is the maximum number of events to include in list responses. @@ -58,7 +59,7 @@ func readOnlyTool(name, description string) *mcp.Tool { } // registerTools installs every tool on s, backed by c. -func registerTools(s *mcp.Server, c *kube.Client) { +func registerTools(s *mcp.Server, c reader.Reader) { mcp.AddTool(s, readOnlyTool( "list_gameplane_resources", "List objects of one Gameplane CRD kind (GameServer, GameTemplate, Backup, "+ @@ -106,13 +107,15 @@ func registerTools(s *mcp.Server, c *kube.Client) { // --- list_gameplane_resources --- type listResourcesInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` Kind string `json:"kind" jsonschema:"Gameplane CRD kind to list: GameServer, GameTemplate, Backup, BackupSchedule, Restore, Module, or ModuleSource."` Namespace string `json:"namespace,omitempty" jsonschema:"Namespace to list within. Ignored for cluster-scoped kinds (GameTemplate, Module, ModuleSource). Empty lists across all namespaces for namespaced kinds."` LabelSelector string `json:"labelSelector,omitempty" jsonschema:"Optional Kubernetes label selector. Most Gameplane CRD objects carry no labels; Backups created by a BackupSchedule are the exception, e.g. 'gameplane.local/backup-schedule=nightly'."` } -func listResourcesHandler(c *kube.Client) mcp.ToolHandlerFor[listResourcesInput, any] { +func listResourcesHandler(c reader.Reader) mcp.ToolHandlerFor[listResourcesInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in listResourcesInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster}) list, err := c.ListCRD(ctx, in.Kind, in.Namespace, in.LabelSelector) if err != nil { return nil, nil, err @@ -132,13 +135,15 @@ func listResourcesHandler(c *kube.Client) mcp.ToolHandlerFor[listResourcesInput, // --- get_gameplane_resource --- type getResourceInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` Kind string `json:"kind" jsonschema:"Gameplane CRD kind: GameServer, GameTemplate, Backup, BackupSchedule, Restore, Module, or ModuleSource."` Namespace string `json:"namespace,omitempty" jsonschema:"Namespace containing the object. Required for namespaced kinds (GameServer, Backup, BackupSchedule, Restore); ignored for cluster-scoped kinds."` Name string `json:"name" jsonschema:"Object name."` } -func getResourceHandler(c *kube.Client) mcp.ToolHandlerFor[getResourceInput, any] { +func getResourceHandler(c reader.Reader) mcp.ToolHandlerFor[getResourceInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in getResourceInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster}) obj, err := c.GetCRD(ctx, in.Kind, in.Namespace, in.Name) if err != nil { return nil, nil, err @@ -158,12 +163,15 @@ func getResourceHandler(c *kube.Client) mcp.ToolHandlerFor[getResourceInput, any // --- list_pods --- type listPodsInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` + Server string `json:"server,omitempty" jsonschema:"Optional GameServer name. Per-user mode uses it to read that server's pods, events and logs; required by get_pod_logs in per-user mode for game server pods."` Namespace string `json:"namespace,omitempty" jsonschema:"Namespace to list within. Empty lists across all namespaces."` LabelSelector string `json:"labelSelector,omitempty" jsonschema:"Optional Kubernetes label selector, e.g. 'app.kubernetes.io/instance=my-server' to match a GameServer's pod."` } -func listPodsHandler(c *kube.Client) mcp.ToolHandlerFor[listPodsInput, any] { +func listPodsHandler(c reader.Reader) mcp.ToolHandlerFor[listPodsInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in listPodsInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster, Server: in.Server}) list, err := c.ListPods(ctx, in.Namespace, in.LabelSelector) if err != nil { return nil, nil, err @@ -183,12 +191,14 @@ func listPodsHandler(c *kube.Client) mcp.ToolHandlerFor[listPodsInput, any] { // --- get_pod --- type getPodInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` Namespace string `json:"namespace" jsonschema:"Namespace containing the pod."` Name string `json:"name" jsonschema:"Pod name."` } -func getPodHandler(c *kube.Client) mcp.ToolHandlerFor[getPodInput, any] { +func getPodHandler(c reader.Reader) mcp.ToolHandlerFor[getPodInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in getPodInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster}) pod, err := c.GetPod(ctx, in.Namespace, in.Name) if err != nil { return nil, nil, err @@ -208,13 +218,16 @@ func getPodHandler(c *kube.Client) mcp.ToolHandlerFor[getPodInput, any] { // --- list_events --- type listEventsInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` + Server string `json:"server,omitempty" jsonschema:"Optional GameServer name. Per-user mode uses it to read that server's pods, events and logs; required by get_pod_logs in per-user mode for game server pods."` Namespace string `json:"namespace,omitempty" jsonschema:"Namespace to list within. Empty lists across all namespaces."` FieldSelector string `json:"fieldSelector,omitempty" jsonschema:"Optional field selector, e.g. 'involvedObject.name=my-server,involvedObject.kind=GameServer'."` LabelSelector string `json:"labelSelector,omitempty" jsonschema:"Optional label selector."` } -func listEventsHandler(c *kube.Client) mcp.ToolHandlerFor[listEventsInput, any] { +func listEventsHandler(c reader.Reader) mcp.ToolHandlerFor[listEventsInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in listEventsInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster, Server: in.Server}) list, err := c.ListEvents(ctx, in.Namespace, in.FieldSelector) if err != nil { return nil, nil, err @@ -300,6 +313,8 @@ func eventTime(e *corev1.Event) time.Time { // --- get_pod_logs --- type getPodLogsInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` + Server string `json:"server,omitempty" jsonschema:"Optional GameServer name. Per-user mode uses it to read that server's pods, events and logs; required by get_pod_logs in per-user mode for game server pods."` Namespace string `json:"namespace" jsonschema:"Namespace containing the pod."` Pod string `json:"pod" jsonschema:"Pod name."` Container string `json:"container,omitempty" jsonschema:"Container name. Required if the pod has more than one container."` @@ -307,8 +322,9 @@ type getPodLogsInput struct { Previous bool `json:"previous,omitempty" jsonschema:"If true, fetch logs from the previous (crashed) instance of the container instead of the current one."` } -func getPodLogsHandler(c *kube.Client) mcp.ToolHandlerFor[getPodLogsInput, any] { +func getPodLogsHandler(c reader.Reader) mcp.ToolHandlerFor[getPodLogsInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in getPodLogsInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster, Server: in.Server}) logs, err := c.PodLogs(ctx, in.Namespace, in.Pod, in.Container, in.TailLines, in.Previous) if err != nil { return nil, nil, err @@ -320,14 +336,16 @@ func getPodLogsHandler(c *kube.Client) mcp.ToolHandlerFor[getPodLogsInput, any] // --- propose_fix --- type proposeFixInput struct { + Cluster string `json:"cluster,omitempty" jsonschema:"Optional registered cluster ID. Per-user mode only. Empty: lists cover every cluster you may read (each item is annotated gameplane.local/cluster); gets use the local cluster."` Kind string `json:"kind,omitempty" jsonschema:"Optional: the Gameplane CRD kind the symptom concerns (GameServer, Backup, BackupSchedule, Restore, GameTemplate, Module, ModuleSource), or 'Pod'."` Namespace string `json:"namespace,omitempty" jsonschema:"Optional: namespace of the resource the symptom concerns."` Name string `json:"name,omitempty" jsonschema:"Optional: name of the resource the symptom concerns."` Symptom string `json:"symptom" jsonschema:"Required. Free-text description of the observed problem, e.g. 'GameServer stuck in Pending for 10 minutes' or 'CrashLoopBackOff on the agent container'."` } -func proposeFixHandler(c *kube.Client) mcp.ToolHandlerFor[proposeFixInput, any] { +func proposeFixHandler(c reader.Reader) mcp.ToolHandlerFor[proposeFixInput, any] { return func(ctx context.Context, _ *mcp.CallToolRequest, in proposeFixInput) (*mcp.CallToolResult, any, error) { + ctx = reader.WithTarget(ctx, reader.Target{Cluster: in.Cluster}) text := buildFixSuggestion(ctx, c, in) return textResult(text), nil, nil } From 9d8f2d5c2a07a9f7293dfa9e3769e0aca7b8525f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:00:23 +0000 Subject: [PATCH 2/3] test: check the skip note, not the fake client's resource version The fake dynamic client sets its own resourceVersion on unrestricted lists, so assert only that no skipped-namespaces note is present. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- internal/kube/allowlist_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/kube/allowlist_test.go b/internal/kube/allowlist_test.go index b17faae..640e0b6 100644 --- a/internal/kube/allowlist_test.go +++ b/internal/kube/allowlist_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "slices" + "strings" "testing" corev1 "k8s.io/api/core/v1" @@ -334,7 +335,8 @@ func TestNoNamespacesListsAcrossAllNamespaces(t *testing.T) { if got := crdNames(servers); !slices.Equal(got, []string{"hidden", "mc", "val"}) { t.Errorf("want every GameServer, got %v", got) } - if servers.GetResourceVersion() != "" { + // The fake client sets its own resource version; only the skip note matters. + if strings.HasPrefix(servers.GetResourceVersion(), "skipped namespaces") { t.Errorf("unrestricted list must not carry a skip note, got %q", servers.GetResourceVersion()) } } From 5e4ebb236ef1606702d6c09cef75122db7e1af01 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:05:07 +0000 Subject: [PATCH 3/3] fix: clean the panel CA path before reading it (gosec G304) Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- internal/panel/client.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/panel/client.go b/internal/panel/client.go index ea53f59..8fef961 100644 --- a/internal/panel/client.go +++ b/internal/panel/client.go @@ -18,6 +18,7 @@ import ( "net/http" "net/url" "os" + "path/filepath" "strconv" "strings" "time" @@ -146,7 +147,8 @@ func certPool(caFile string) (*x509.CertPool, error) { if err != nil || pool == nil { pool = x509.NewCertPool() } - pemBytes, err := os.ReadFile(caFile) + // caFile comes from the operator's own --panel-ca flag or environment. + pemBytes, err := os.ReadFile(filepath.Clean(caFile)) if err != nil { return nil, fmt.Errorf("read panel CA file: %w", err) }