From 4fb4e1f04c82dc05a3c462ec2740b6f4e954358a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:29:18 +0000 Subject: [PATCH 1/2] fix: cap per-user logs, never follow redirects, refuse token without panel URL Per-user mode now trims pod logs to the newest 256 KiB client-side like break-glass, does not follow redirects that could resend the bearer token, and a GAMEPLANE_MCP_TOKEN without GAMEPLANE_PANEL_URL is a start-up error instead of a silent fall back to break-glass. The GET-only source tripwire also catches string-literal methods. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- README.md | 2 +- internal/panel/client.go | 31 ++++++++++++- internal/panel/hardening_test.go | 80 ++++++++++++++++++++++++++++++++ internal/panel/source_test.go | 7 +++ main.go | 4 ++ main_serve_test.go | 18 +++++++ specs.md | 3 ++ 7 files changed, 143 insertions(+), 2 deletions(-) create mode 100644 internal/panel/hardening_test.go create mode 100644 main_serve_test.go diff --git a/README.md b/README.md index 868b733..5e56a36 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Options for `serve` (each also has an environment variable): 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. + `gpmcp_`. The token is never written to logs or error messages. A token without `GAMEPLANE_PANEL_URL` is a start-up error: `serve` refuses to start rather than fall back to break-glass mode. 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. diff --git a/internal/panel/client.go b/internal/panel/client.go index 8fef961..e896a75 100644 --- a/internal/panel/client.go +++ b/internal/panel/client.go @@ -119,6 +119,16 @@ func New(baseURL, token, caFile string) (*Client, error) { tr = tr.Clone() tr.TLSClientConfig = tlsCfg + // The API never redirects these GETs; following one could resend the + // bearer token to another scheme or path. + httpClient := &http.Client{ + Timeout: requestTimeout, + Transport: tr, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } + raw := make([]byte, 16) if _, err := rand.Read(raw); err != nil { return nil, fmt.Errorf("generate session ID: %w", err) @@ -128,7 +138,7 @@ func New(baseURL, token, caFile string) (*Client, error) { base: u, token: token, session: base64.RawURLEncoding.EncodeToString(raw), - hc: &http.Client{Timeout: requestTimeout, Transport: tr}, + hc: httpClient, fanout: defaultFanout, perCluster: defaultPerCluster, }, nil @@ -580,6 +590,23 @@ func (c *Client) eventsIn(ctx context.Context, ns, fsel string) (*corev1.EventLi return out, nil } +const maxLogBytes = 256 << 10 + +const truncatedLogNotice = "[gameplane-mcp: log output truncated to the newest 256 KiB]\n" + +// keepNewestLog enforces the same 256 KiB newest-bytes bound as break-glass +// mode, so a misbehaving API cannot flood the transcript. +func keepNewestLog(s string) string { + if len(s) <= maxLogBytes { + return s + } + cut := len(s) - maxLogBytes + for cut < len(s) && !utf8.RuneStart(s[cut]) { + cut++ + } + return truncatedLogNotice + s[cut:] +} + // 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. @@ -608,6 +635,7 @@ func (c *Client) PodLogs(ctx context.Context, namespace, pod, container string, if err := c.get(ctx, "/servers/"+url.PathEscape(srv)+"/logs/pod/tail", q, &logs); err != nil { return "", err } + logs = keepNewestLog(logs) return logs, nil } @@ -626,6 +654,7 @@ func (c *Client) PodLogs(ctx context.Context, namespace, pod, container string, if err := c.get(ctx, path, q, &logs); err != nil { return "", err } + logs = keepNewestLog(logs) return logs, nil } diff --git a/internal/panel/hardening_test.go b/internal/panel/hardening_test.go new file mode 100644 index 0000000..63c2beb --- /dev/null +++ b/internal/panel/hardening_test.go @@ -0,0 +1,80 @@ +package panel + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "unicode/utf8" +) + +// TestClientDoesNotFollowRedirects serves a 302 from a GET route and checks +// the client returns that 302 as an API error instead of following it to the +// redirect target. +func TestClientDoesNotFollowRedirects(t *testing.T) { + var targetHit atomic.Bool + mux := http.NewServeMux() + mux.HandleFunc("/servers", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/elsewhere", http.StatusFound) + }) + mux.HandleFunc("/elsewhere", func(w http.ResponseWriter, r *http.Request) { + targetHit.Store(true) + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + c, err := New(srv.URL, testToken, "") + if err != nil { + t.Fatalf("New: %v", err) + } + var body string + err = c.get(context.Background(), "/servers", nil, &body) + if err == nil { + t.Fatal("get succeeded on a 302; the redirect must not be followed to a 200") + } + if got := statusOf(err); got != http.StatusFound { + t.Errorf("status = %d, want %d (the redirect returned as-is)", got, http.StatusFound) + } + if targetHit.Load() { + t.Error("redirect target was requested; the client must not follow redirects") + } +} + +func TestKeepNewestLog(t *testing.T) { + t.Run("oversized keeps newest bytes behind the notice", func(t *testing.T) { + in := strings.Repeat("a", 300<<10) + "END" + got := keepNewestLog(in) + if !strings.HasPrefix(got, truncatedLogNotice) { + t.Fatalf("output does not start with the truncation notice: %q", got[:min(len(got), 80)]) + } + if limit := maxLogBytes + len(truncatedLogNotice); len(got) > limit { + t.Errorf("len = %d, want <= %d", len(got), limit) + } + if !strings.HasSuffix(got, "END") { + t.Error("output does not end with the newest bytes") + } + }) + + t.Run("cut lands on a rune boundary", func(t *testing.T) { + // Three-byte runes put the naive cut mid-rune, so the cut must move forward. + in := strings.Repeat("€", 150<<10) + got := keepNewestLog(in) + payload := strings.TrimPrefix(got, truncatedLogNotice) + if !utf8.ValidString(payload) { + t.Error("truncated output splits a multi-byte rune") + } + if len(got) > maxLogBytes+len(truncatedLogNotice) { + t.Errorf("len = %d, want <= %d", len(got), maxLogBytes+len(truncatedLogNotice)) + } + }) + + t.Run("short input unchanged", func(t *testing.T) { + in := "line 1\nline 2\n" + if got := keepNewestLog(in); got != in { + t.Errorf("keepNewestLog(%q) = %q, want it unchanged", in, got) + } + }) +} diff --git a/internal/panel/source_test.go b/internal/panel/source_test.go index 8c5de8f..719dbfd 100644 --- a/internal/panel/source_test.go +++ b/internal/panel/source_test.go @@ -18,6 +18,10 @@ var ( funcDecl = regexp.MustCompile(`^func (?:\([^)]*\)\s*)?(\w+)`) ) +// newRequestLiteralMethod catches a string literal passed as the method of +// NewRequestWithContext; the method must be an http.Method constant. +var newRequestLiteralMethod = regexp.MustCompile(`NewRequestWithContext\([^,]*,\s*"`) + func TestPanelSourceOnlyIssuesGET(t *testing.T) { entries, err := os.ReadDir(".") if err != nil { @@ -50,6 +54,9 @@ func TestPanelSourceOnlyIssuesGET(t *testing.T) { if newRequestCall.MatchString(line) { t.Errorf("%s calls http.NewRequest; use http.NewRequestWithContext in get", where) } + if newRequestLiteralMethod.MatchString(line) { + t.Errorf("%s passes a string literal as the NewRequestWithContext method; use http.MethodGet", where) + } if m := bannedVerbCall.FindString(line); m != "" { t.Errorf("%s calls %s; the panel client may only issue GET", where, m) } diff --git a/main.go b/main.go index 1f2d559..c69531f 100644 --- a/main.go +++ b/main.go @@ -137,6 +137,10 @@ func runServe(ctx context.Context, args []string) error { } var rd reader.Reader + if *panelURL == "" && os.Getenv("GAMEPLANE_MCP_TOKEN") != "" { + return errors.New("GAMEPLANE_MCP_TOKEN is set but GAMEPLANE_PANEL_URL is not; refusing to fall back to break-glass mode") + } + if *panelURL != "" { token := os.Getenv("GAMEPLANE_MCP_TOKEN") if token == "" { diff --git a/main_serve_test.go b/main_serve_test.go new file mode 100644 index 0000000..a5c7f27 --- /dev/null +++ b/main_serve_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "context" + "strings" + "testing" +) + +// A token without a panel URL must stop start-up rather than silently fall +// back to break-glass mode against the local kubeconfig. +func TestRunServeRefusesTokenWithoutPanelURL(t *testing.T) { + t.Setenv("GAMEPLANE_PANEL_URL", "") + t.Setenv("GAMEPLANE_MCP_TOKEN", "gpmcp_x") + err := runServe(context.Background(), nil) + if err == nil || !strings.Contains(err.Error(), "GAMEPLANE_PANEL_URL") { + t.Fatalf("runServe error = %v, want one naming GAMEPLANE_PANEL_URL", err) + } +} diff --git a/specs.md b/specs.md index fec81f0..2ee17cd 100644 --- a/specs.md +++ b/specs.md @@ -11,6 +11,7 @@ Optional, strictly **read-only** Model Context Protocol (MCP) server that expose - **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. +- A `GAMEPLANE_MCP_TOKEN` without `GAMEPLANE_PANEL_URL` is a start-up error. `serve` refuses to start rather than fall back to break-glass mode with a token set. It speaks MCP (JSON-RPC 2.0) over stdio, not a network port. @@ -112,6 +113,8 @@ Pod logs read the complete finite Kubernetes tail response while retaining only - 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. +- Redirects are not followed. The client's `CheckRedirect` returns `http.ErrUseLastResponse`, so a 3xx comes back as an `*APIError`. The API never redirects these GETs, and following one could resend the bearer token to another scheme or path. +- Per-user pod logs are capped client-side to the newest 256 KiB, with the same truncation notice as break-glass mode, even when the API returns more. ### Transport From 5b7e047997520dccb2f7e04508d544c7b64eb872 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:32:35 +0000 Subject: [PATCH 2/2] test: rename unused handler parameter (revive) Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- internal/panel/hardening_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/panel/hardening_test.go b/internal/panel/hardening_test.go index 63c2beb..cbece66 100644 --- a/internal/panel/hardening_test.go +++ b/internal/panel/hardening_test.go @@ -19,7 +19,7 @@ func TestClientDoesNotFollowRedirects(t *testing.T) { mux.HandleFunc("/servers", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/elsewhere", http.StatusFound) }) - mux.HandleFunc("/elsewhere", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/elsewhere", func(w http.ResponseWriter, _ *http.Request) { targetHit.Store(true) w.WriteHeader(http.StatusOK) })