Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
31 changes: 30 additions & 1 deletion internal/panel/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

Expand All @@ -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
}

Expand Down
80 changes: 80 additions & 0 deletions internal/panel/hardening_test.go
Original file line number Diff line number Diff line change
@@ -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, _ *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)
}
})
}
7 changes: 7 additions & 0 deletions internal/panel/source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand Down
18 changes: 18 additions & 0 deletions main_serve_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
3 changes: 3 additions & 0 deletions specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down