diff --git a/changelog.d/security-admin-mcp-request-path-elements.md b/changelog.d/security-admin-mcp-request-path-elements.md new file mode 100644 index 0000000000..d8e9e052a4 --- /dev/null +++ b/changelog.d/security-admin-mcp-request-path-elements.md @@ -0,0 +1 @@ +- Admin MCP: a name of `.` or `..` can no longer steer a request to a different endpoint. Agent, run, repository, contributor and plan names go into the request path, and `.` and `..` survive URL escaping. The hive's router answers such a path with a redirect to the cleaned path, which is another route: `/api/kick/../status` is `/api/status`, and `/api/model/../` is `/api/`. The stdio binary (`hive-admin-mcp`) followed that redirect with the same method, body and token, so with writes enabled a registered operation such as `agent.model` could be previewed and confirmed into a `POST` the admin MCP does not offer, including ones its exclusion catalogue refuses, and a read tool could return another endpoint's data under the wrong name. Over the HTTP endpoint the redirect was not followed and the caller only saw "HTTP 307". Both transports now refuse a request path with an empty, `.` or `..` element before anything is sent, for every read and write, and `write_confirm` refuses a stored confirmation that carries one. Re-extract or rebuild `hive-admin-mcp` to get the fix on stdio. diff --git a/src/cmd/hive-admin-mcp/main.go b/src/cmd/hive-admin-mcp/main.go index de4fefa091..5b0c36d103 100644 --- a/src/cmd/hive-admin-mcp/main.go +++ b/src/cmd/hive-admin-mcp/main.go @@ -285,6 +285,9 @@ func (p readProvider) callWrite(ctx context.Context, tool string, args map[strin } func (p readProvider) ExecuteWrite(ctx context.Context, req adminmcp.WriteRequest) (any, error) { + if err := adminmcp.CheckRequestPath(req.Path); err != nil { + return nil, err + } client, _, err := p.roster.activeClient() if err != nil { return nil, err @@ -393,6 +396,9 @@ func (p readProvider) Read(ctx context.Context, tool string, args map[string]any // their query as a "?..." suffix; hivectl.Client takes the query separately // and would percent-encode a "?" left in the path (#9160). func getPath(ctx context.Context, client *hivectl.Client, path string) (any, error) { + if err := adminmcp.CheckRequestPath(path); err != nil { + return nil, err + } apiPath, rawQuery, _ := strings.Cut(path, "?") query, err := url.ParseQuery(rawQuery) if err != nil { diff --git a/src/cmd/hive-admin-mcp/request_path_test.go b/src/cmd/hive-admin-mcp/request_path_test.go new file mode 100644 index 0000000000..4f9360688d --- /dev/null +++ b/src/cmd/hive-admin-mcp/request_path_test.go @@ -0,0 +1,105 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/adminmcp" +) + +// hubCounting serves every route and counts the requests that reach it. +func hubCounting(t *testing.T) (*httptest.Server, *atomic.Int64, *atomic.Value) { + t.Helper() + var hits atomic.Int64 + var last atomic.Value + last.Store("") + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + last.Store(r.Method + " " + r.URL.Path) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true}`)) + }) + // Registered as on the hive, so the router's redirect to the cleaned + // path would land on a real handler. + mux.HandleFunc("POST /api/model/{agent}/{model}", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + last.Store("model " + r.PathValue("agent")) + _, _ = w.Write([]byte(`{"ok":true}`)) + }) + mux.HandleFunc("POST /api/self-upgrade", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + last.Store("SELF-UPGRADE") + _, _ = w.Write([]byte(`{"status":"upgrading"}`)) + }) + mux.HandleFunc("GET /api/kick/{agent}/status", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + last.Store("kick-status " + r.PathValue("agent")) + _, _ = w.Write([]byte(`{"status":"delivered"}`)) + }) + mux.HandleFunc("GET /api/status", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + last.Store("FLEET-STATUS") + _, _ = w.Write([]byte(`{"agents":[]}`)) + }) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + return server, &hits, &last +} + +// agent.model with agent ".." and model "self-upgrade" built the path +// /api/model/../self-upgrade. The hive's router redirects that to +// /api/self-upgrade and the stdio client followed the redirect with the same +// method and token, so a registered write ran an operation the admin MCP +// excludes. +func TestStdioWriteWithDotNameNeverReachesTheHive(t *testing.T) { + server, hits, last := hubCounting(t) + r := &roster{hives: []hiveConfig{{Name: "active", Address: server.URL, Token: "token"}}, active: 0, timeout: time.Second} + p := readProvider{roster: r, writesEnabled: true, pendingStore: adminmcp.NewMemoryPendingStore()} + + _, err := p.callWrite(context.Background(), adminmcp.ToolWritePreview, map[string]any{"operation": adminmcp.WriteOpAgentModel, "args": map[string]any{"agent": "..", "model": "self-upgrade"}}) + if !errors.Is(err, adminmcp.ErrRequestPath) { + t.Fatalf("preview = %v, want ErrRequestPath", err) + } + // The client itself refuses the path, whatever previewed it. + if _, err := p.ExecuteWrite(context.Background(), adminmcp.WriteRequest{Method: http.MethodPost, Path: "/api/model/../self-upgrade"}); !errors.Is(err, adminmcp.ErrRequestPath) { + t.Fatalf("ExecuteWrite = %v, want ErrRequestPath", err) + } + if n := hits.Load(); n != 0 { + t.Fatalf("%d request(s) reached the hive; the last was %q", n, last.Load()) + } +} + +// agent_nudge_status with agent ".." built /api/kick/../status and came back +// with the whole fleet status as if it were that agent's nudge outcome. +func TestStdioReadWithDotNameNeverReachesTheHive(t *testing.T) { + server, hits, last := hubCounting(t) + r := &roster{hives: []hiveConfig{{Name: "active", Address: server.URL, Token: "token"}}, active: 0, timeout: time.Second} + p := readProvider{roster: r} + for tool, args := range map[string]map[string]any{ + adminmcp.ToolAgentNudgeStatus: {"agent": ".."}, + adminmcp.ToolSettingsRead: {"section": "agent_variables", "agent": ".."}, + adminmcp.ToolAgentKicksList: {"agent": ".."}, + adminmcp.ToolAgentKickRead: {"agent": "scanner", "kick_id": "."}, + adminmcp.ToolRunDetailRead: {"run": ".."}, + } { + if _, err := p.Read(context.Background(), tool, args); !errors.Is(err, adminmcp.ErrRequestPath) { + t.Errorf("%s %v = %v, want ErrRequestPath", tool, args, err) + } + } + if n := hits.Load(); n != 0 { + t.Fatalf("%d request(s) reached the hive; the last was %q", n, last.Load()) + } + // An ordinary name still reads. + if _, err := p.Read(context.Background(), adminmcp.ToolAgentNudgeStatus, map[string]any{"agent": "scanner"}); err != nil { + t.Fatal(err) + } + if got := last.Load(); got != "kick-status scanner" { + t.Fatalf("an ordinary read reached %q", got) + } +} diff --git a/src/pkg/adminmcp/adminmcp.go b/src/pkg/adminmcp/adminmcp.go index 56e761a9bb..bb1c762364 100644 --- a/src/pkg/adminmcp/adminmcp.go +++ b/src/pkg/adminmcp/adminmcp.go @@ -503,6 +503,9 @@ func (h *Handler) PreviewWrite(ctx context.Context, args map[string]any) (any, e if err != nil { return nil, err } + if err := CheckRequestPath(preview.Request.Path); err != nil { + return nil, err + } if err := rejectUnpersistablePreview(op.Name(), opArgs, preview); err != nil { return nil, err } @@ -550,6 +553,11 @@ func (h *Handler) ConfirmWrite(ctx context.Context, args map[string]any) (any, e if preview.Request.Method != pending.Preview.Request.Method || preview.Request.Path != pending.Preview.Request.Path { return nil, fmt.Errorf("write preview changed since confirmation was issued") } + // Checked again here: a confirmation stored before this check existed + // must not be executed either. + if err := CheckRequestPath(pending.Preview.Request.Path); err != nil { + return nil, err + } result, err := h.WriteClient.ExecuteWrite(ctx, pending.Preview.Request) if err != nil { return nil, err diff --git a/src/pkg/adminmcp/request_path.go b/src/pkg/adminmcp/request_path.go new file mode 100644 index 0000000000..452aaaee39 --- /dev/null +++ b/src/pkg/adminmcp/request_path.go @@ -0,0 +1,46 @@ +package adminmcp + +import ( + "errors" + "fmt" + "net/url" + "strings" +) + +// ErrRequestPath is returned for a request path the admin MCP will not send. +var ErrRequestPath = errors.New("admin MCP request path refused") + +// CheckRequestPath refuses a request path that has an empty, "." or ".." +// element. +// +// Every path the admin MCP sends is a fixed route with names from the caller +// in it: an agent, a run, a repository, a contributor, a plan. Those names are +// escaped with url.PathEscape, which leaves "." and ".." as they are. The +// hive's router does not serve a path that holds such an element: it answers +// with a redirect to the cleaned path, and the cleaned path is another route. +// "/api/kick/../status" is "/api/status", and "/api/model/../" is +// "/api/" for any name. The stdio client follows that redirect with the +// same method, body and credentials, so a name of ".." turned a listed +// operation into a request for an endpoint the admin MCP does not offer, +// including ones it excludes. Over HTTP the redirect is not followed and the +// caller saw only "HTTP 307". +// +// No agent, run, repository, contributor or plan is named "", "." or "..", so +// such a path is refused before anything is sent. Both transports call this +// for every read and every write. +func CheckRequestPath(path string) error { + rawPath, _, _ := strings.Cut(path, "?") + if !strings.HasPrefix(rawPath, "/") { + return fmt.Errorf("%w: %q is not an absolute path", ErrRequestPath, rawPath) + } + for _, element := range strings.Split(rawPath[1:], "/") { + decoded := element + if unescaped, err := url.PathUnescape(element); err == nil { + decoded = unescaped + } + if decoded == "" || decoded == "." || decoded == ".." { + return fmt.Errorf("%w: %q has an empty, \".\" or \"..\" element; an agent, run, repository, contributor or plan name cannot be empty, \".\" or \"..\"", ErrRequestPath, rawPath) + } + } + return nil +} diff --git a/src/pkg/adminmcp/request_path_test.go b/src/pkg/adminmcp/request_path_test.go new file mode 100644 index 0000000000..88692cd093 --- /dev/null +++ b/src/pkg/adminmcp/request_path_test.go @@ -0,0 +1,136 @@ +package adminmcp + +import ( + "context" + "errors" + "testing" +) + +func TestCheckRequestPath(t *testing.T) { + for _, path := range []string{ + "/api/status", + "/api/status/summary", + "/api/kick/scanner/status", + "/api/agents/team%2Fscanner/log", + "/api/model/scanner/kiro-api-key%2Fclaude-opus-5:high", + "/api/runs/org%2Frepo%237/detail", + "/api/overview/issues.json?repo=org%2Frepo&stale=true", + "/api/logs/read?include=..&exclude=.", + "/api/config/agent/.hidden/prompt", + "/api/config/agent/a..b/prompt", + "/api/config/agent/.../prompt", + "/api/agents/%252e%252e/log", + } { + if err := CheckRequestPath(path); err != nil { + t.Errorf("CheckRequestPath(%q) = %v, want it allowed", path, err) + } + } + for _, path := range []string{ + "/api/kick/../status", + "/api/kick/./status", + "/api/model/../self-upgrade", + "/api/agents/..", + "/api/agents/.", + "/api/config/agent/%2e%2e/prompt", + "/api/config/agent/%2E./prompt", + "/api/repos//repo/items/1/hold", + "/api/pause/", + "/api/plan/../approve?x=1", + "api/status", + "", + } { + err := CheckRequestPath(path) + if !errors.Is(err, ErrRequestPath) { + t.Errorf("CheckRequestPath(%q) = %v, want ErrRequestPath", path, err) + } + } +} + +// A name of "." or ".." in a write's arguments was escaped into the request +// path as it was, and the path then named a different endpoint: +// agent.model with agent ".." and model "self-upgrade" asked for +// POST /api/model/../self-upgrade, which is POST /api/self-upgrade. +func TestWritePreviewRefusesDotNames(t *testing.T) { + for _, tc := range []struct { + op string + args map[string]any + }{ + {WriteOpAgentModel, map[string]any{"agent": "..", "model": "self-upgrade"}}, + {WriteOpAgentBackend, map[string]any{"agent": "..", "backend": "backup"}}, + {WriteOpAgentEffort, map[string]any{"agent": "..", "effort": "release-channel"}}, + {WriteOpAgentModel, map[string]any{"agent": "scanner", "model": ".."}}, + {WriteOpAgentPause, map[string]any{"agent": ".."}}, + {WriteOpAgentResume, map[string]any{"agent": "."}}, + {WriteOpAgentNudge, map[string]any{"agent": "..", "prompt": "hello"}}, + {WriteOpAgentRestart, map[string]any{"agent": ".."}}, + {WriteOpAgentRemove, map[string]any{"agent": ".."}}, + {WriteOpAgentInteractionTier, map[string]any{"agent": "..", "tier": "ADVISORY"}}, + {WriteOpPlanApprove, map[string]any{"epic_id": ".."}}, + {WriteOpPlanReject, map[string]any{"epic_id": "."}}, + {WriteOpRepositoryItemHold, map[string]any{"owner": "..", "repo": "repo", "number": float64(1), "held": true}}, + {WriteOpRepositoryItemHold, map[string]any{"owner": "org", "repo": "..", "number": float64(1), "held": true}}, + {WriteOpContributorTrust, map[string]any{"contributor_id": "..", "tier": "trusted"}}, + {WriteOpContributorAgentRole, map[string]any{"contributor_id": "..", "agent_role": "architect"}}, + {WriteOpContributorRoleGrants, map[string]any{"contributor_id": "..", "agent_role_grants": []any{"architect"}}}, + {WriteOpContributorRevoke, map[string]any{"contributor_id": ".."}}, + {WriteOpContributorRequeue, map[string]any{"contributor_id": ".."}}, + {WriteOpContributorDelete, map[string]any{"contributor_id": ".."}}, + } { + provider := &writeProvider{} + store := NewMemoryPendingStore() + h := NewHandler(provider, WithWritesEnabled(true), WithPendingStore(store), WithHiveID("hive-a")) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": tc.op, "args": tc.args}) + if !errors.Is(err, ErrRequestPath) { + t.Errorf("%s %v: preview = %v, want ErrRequestPath", tc.op, tc.args, err) + } + if pending, _ := store.List(context.Background()); len(pending) != 0 { + t.Errorf("%s %v: a confirmation was stored for a refused path", tc.op, tc.args) + } + } +} + +// A confirmation that was stored before the check existed is not executed. +func TestWriteConfirmRefusesStoredDotPath(t *testing.T) { + provider := &writeProvider{} + store := NewMemoryPendingStore() + h := NewHandler(provider, WithWritesEnabled(true), WithPendingStore(store), WithHiveID("hive-a")) + args := map[string]any{"agent": "..", "model": "self-upgrade"} + preview, err := agentModelOp{}.Preview(context.Background(), args) + if err != nil { + t.Fatal(err) + } + now := h.now() + if err := store.Put(context.Background(), PendingConfirmation{ID: "old", Operation: WriteOpAgentModel, Args: args, Preview: preview, Hive: "hive-a", CreatedAt: now, ExpiresAt: now.Add(DefaultConfirmationTTL)}); err != nil { + t.Fatal(err) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": "old"}); !errors.Is(err, ErrRequestPath) { + t.Fatalf("confirm = %v, want ErrRequestPath", err) + } + if len(provider.requests) != 0 { + t.Fatalf("a refused path was executed: %+v", provider.requests) + } +} + +// Ordinary names, including ones that need escaping, are not affected. +func TestWritePreviewStillAcceptsOrdinaryNames(t *testing.T) { + for _, tc := range []struct { + op string + args map[string]any + path string + }{ + {WriteOpAgentModel, map[string]any{"agent": "team/scanner", "model": "kiro-api-key/claude-opus-5:high"}, "/api/model/team%2Fscanner/kiro-api-key%2Fclaude-opus-5:high"}, + {WriteOpAgentPause, map[string]any{"agent": ".hidden"}, "/api/pause/.hidden"}, + {WriteOpPlanApprove, map[string]any{"epic_id": "epic..1"}, "/api/plan/epic..1/approve"}, + {WriteOpRepositoryItemHold, map[string]any{"owner": "org", "repo": ".github", "number": float64(3), "held": true}, "/api/repos/org/.github/items/3/hold"}, + } { + h := NewHandler(&writeProvider{}, WithWritesEnabled(true), WithHiveID("hive-a")) + previewed, err := h.PreviewWrite(context.Background(), map[string]any{"operation": tc.op, "args": tc.args}) + if err != nil { + t.Errorf("%s %v: %v", tc.op, tc.args, err) + continue + } + if got := previewed.(map[string]any)["preview"].(WritePreview).Request.Path; got != tc.path { + t.Errorf("%s: path = %s, want %s", tc.op, got, tc.path) + } + } +} diff --git a/src/pkg/dashboard/admin_mcp.go b/src/pkg/dashboard/admin_mcp.go index 1804fbca06..e9f97aff18 100644 --- a/src/pkg/dashboard/admin_mcp.go +++ b/src/pkg/dashboard/admin_mcp.go @@ -178,6 +178,9 @@ func (p dashboardAdminMCPProvider) get(tool, path string) (any, error) { // getVerified is get with the verified-owner marker set on the inner request // when ownerVerified is true; callers pass p.ownerVerified, never a constant. func (p dashboardAdminMCPProvider) getVerified(tool, path string, ownerVerified bool) (any, error) { + if err := adminmcp.CheckRequestPath(path); err != nil { + return nil, err + } rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, path, nil) if p.user != "" { diff --git a/src/pkg/dashboard/admin_mcp_diag.go b/src/pkg/dashboard/admin_mcp_diag.go index 8b87b6c6e7..859e108575 100644 --- a/src/pkg/dashboard/admin_mcp_diag.go +++ b/src/pkg/dashboard/admin_mcp_diag.go @@ -26,6 +26,9 @@ func (p dashboardAdminMCPProvider) readDiag(tool string, args map[string]any) (a if err != nil { return nil, err } + if err := adminmcp.CheckRequestPath(path); err != nil { + return nil, err + } owner := adminmcp.DiagOwnerTool(tool) if owner && !p.ownerVerified { return nil, adminmcp.ErrOwnerUnverified diff --git a/src/pkg/dashboard/admin_mcp_request_path_test.go b/src/pkg/dashboard/admin_mcp_request_path_test.go new file mode 100644 index 0000000000..54eff04651 --- /dev/null +++ b/src/pkg/dashboard/admin_mcp_request_path_test.go @@ -0,0 +1,39 @@ +package dashboard + +import ( + "context" + "errors" + "net/http" + "testing" + + "github.com/hivecommons/hive/pkg/adminmcp" +) + +// Over the HTTP endpoint a "." or ".." name reached the dashboard router, +// which answered with a redirect to another route. The redirect is not +// followed in-process, so the caller got "Hive API returned HTTP 307" with a +// link to the other route. The name is now refused before the router sees it. +func TestDashboardAdminMCPRefusesDotNamesBeforeRouting(t *testing.T) { + routed := 0 + s := &Server{mux: http.NewServeMux()} + s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + routed++ + _, _ = w.Write([]byte(`{}`)) + }) + p := dashboardAdminMCPProvider{server: s, role: "owner", ownerVerified: true} + for tool, args := range map[string]map[string]any{ + adminmcp.ToolAgentNudgeStatus: {"agent": ".."}, + adminmcp.ToolSettingsRead: {"section": "agent", "agent": ".."}, + adminmcp.ToolAgentLogRead: {"agent": "."}, + adminmcp.ToolAgentKicksList: {"agent": ".."}, + adminmcp.ToolRunLogRead: {"run": ".."}, + } { + _, err := p.Read(context.Background(), tool, args) + if !errors.Is(err, adminmcp.ErrRequestPath) { + t.Errorf("%s %v = %v, want ErrRequestPath", tool, args, err) + } + } + if routed != 0 { + t.Fatalf("%d refused read(s) reached the dashboard router", routed) + } +}