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
1 change: 1 addition & 0 deletions changelog.d/security-admin-mcp-request-path-elements.md
Original file line number Diff line number Diff line change
@@ -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/../<name>` is `/api/<name>`. 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.
6 changes: 6 additions & 0 deletions src/cmd/hive-admin-mcp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
105 changes: 105 additions & 0 deletions src/cmd/hive-admin-mcp/request_path_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
8 changes: 8 additions & 0 deletions src/pkg/adminmcp/adminmcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
46 changes: 46 additions & 0 deletions src/pkg/adminmcp/request_path.go
Original file line number Diff line number Diff line change
@@ -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/../<name>" is
// "/api/<name>" 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
}
136 changes: 136 additions & 0 deletions src/pkg/adminmcp/request_path_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
3 changes: 3 additions & 0 deletions src/pkg/dashboard/admin_mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/dashboard/admin_mcp_diag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions src/pkg/dashboard/admin_mcp_request_path_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading