Compare commits

..
Author SHA1 Message Date
BaaRai 73ab430c6a fix(server): keep the capture CA and index out of the workspace file API
The workspace file manager roots every path at the data directory, so the
capture proxy CA private key under traffic/_ca and the SQLite exchange index
under traffic/_index were listable, downloadable, overwritable and deletable
through /api/workspace/*. Refuse those two subtrees after resolving the path,
so a symlink alias or a Windows spelling a trailing dot cannot reach them.
2026-11-20 01:23:50 +01:00
4 changed files with 113 additions and 219 deletions
+10 -86
View File
@@ -17,7 +17,6 @@ import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
@@ -102,66 +101,6 @@ func normalizeHeaders(headers map[string]string) (map[string]string, error) {
return out, nil
}
// originKey returns the scheme, host and effective port of u, in a form two
// URLs can be compared with. Empty means u is not an absolute http(s) URL with
// a host.
func originKey(u *url.URL) string {
if u == nil {
return ""
}
scheme := strings.ToLower(u.Scheme)
var port string
switch scheme {
case "http":
port = "80"
case "https":
port = "443"
default:
return ""
}
host := strings.ToLower(u.Hostname())
if host == "" {
return ""
}
if p := u.Port(); p != "" {
port = p
}
return scheme + "://" + net.JoinHostPort(host, port)
}
// sameOrigin reports whether u has the same scheme, host and effective port as
// base.
func sameOrigin(base, u *url.URL) bool {
key := originKey(base)
return key != "" && key == originKey(u)
}
// redirectPolicy refuses a redirect that leaves the origin of the configured
// endpoint, so a remote MCP server cannot retarget authenticated requests.
func redirectPolicy(base *url.URL) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("mcp: stopped after 10 redirects")
}
if !sameOrigin(base, req.URL) {
return fmt.Errorf("mcp: refusing a redirect to another origin: %s", req.URL.Redacted())
}
return nil
}
}
// parseMCPURL parses and validates a configured MCP endpoint URL.
func parseMCPURL(raw string) (*url.URL, error) {
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("mcp url: %w", err)
}
if originKey(u) == "" {
return nil, fmt.Errorf("mcp url must be an absolute http or https URL with a host: %q", raw)
}
return u, nil
}
// New connects to a remote MCP endpoint and performs the initialize handshake.
// headers are sent on every request (Authorization, custom API keys, …).
// When insecure is true, TLS certificate verification is skipped so servers that
@@ -178,11 +117,7 @@ func New(ctx context.Context, server, url string, headers map[string]string, ins
if timeoutSeconds > 0 {
timeout = time.Duration(timeoutSeconds) * time.Second
}
base, err := parseMCPURL(url)
if err != nil {
return nil, err
}
hc := &http.Client{Timeout: timeout, CheckRedirect: redirectPolicy(base)}
hc := &http.Client{Timeout: timeout}
if insecure {
hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
}
@@ -207,11 +142,7 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
if err != nil {
return nil, err
}
base, err := parseMCPURL(sseURL)
if err != nil {
return nil, err
}
hc := &http.Client{CheckRedirect: redirectPolicy(base)} // the SSE stream is intentionally long-lived.
hc := &http.Client{} // the SSE stream is intentionally long-lived.
if insecure {
hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
}
@@ -236,7 +167,7 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
return nil, fmt.Errorf("mcp sse http %d: %s", resp.StatusCode, readSnippet(resp.Body))
}
reader := bufio.NewReader(resp.Body)
endpoint, err := readSSEEndpoint(reader, base)
endpoint, err := readSSEEndpoint(reader, sseURL)
if err != nil {
resp.Body.Close()
cancel()
@@ -264,11 +195,7 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
return c, nil
}
// readSSEEndpoint reads the message endpoint announced by the SSE stream. The
// endpoint must stay on the origin of the configured SSE URL: the POSTs that
// follow carry the operator's headers, and a remote server must not be able to
// retarget them.
func readSSEEndpoint(r *bufio.Reader, base *url.URL) (string, error) {
func readSSEEndpoint(r *bufio.Reader, base string) (string, error) {
for {
line, err := r.ReadString('\n')
if err != nil {
@@ -286,17 +213,14 @@ func readSSEEndpoint(r *bufio.Reader, base *url.URL) (string, error) {
if err != nil {
return "", fmt.Errorf("mcp sse endpoint URL: %w", err)
}
if u.User != nil {
return "", errors.New("mcp sse endpoint must not carry userinfo")
}
abs := u
if !u.IsAbs() {
abs = base.ResolveReference(u)
b, err := url.Parse(base)
if err != nil {
return "", err
}
candidate = b.ResolveReference(u).String()
}
if !sameOrigin(base, abs) {
return "", fmt.Errorf("mcp sse endpoint %q is not on the configured origin", abs.Redacted())
}
return abs.String(), nil
return candidate, nil
}
}
-133
View File
@@ -1,13 +1,11 @@
package mcphttp
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
@@ -107,134 +105,3 @@ func TestLegacySSEClientDiscoverAndCall(t *testing.T) {
t.Fatalf("Call() = %q, %v", got, err)
}
}
func TestReadSSEEndpointSameOrigin(t *testing.T) {
base, err := url.Parse("https://mcp.example.com:8443/sse")
if err != nil {
t.Fatal(err)
}
read := func(line string) (string, error) {
stream := "event: endpoint\ndata: " + line + "\n\n"
return readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base)
}
for _, line := range []string{
"/message?sessionId=1",
"https://mcp.example.com:8443/message",
"HTTPS://MCP.EXAMPLE.COM:8443/message",
"//mcp.example.com:8443/message",
} {
got, err := read(line)
if err != nil {
t.Errorf("%q: %v", line, err)
continue
}
u, err := url.Parse(got)
if err != nil || !sameOrigin(base, u) {
t.Errorf("%q: resolved to %q, not the configured origin", line, got)
}
}
for _, line := range []string{
"https://evil.example/message",
"http://mcp.example.com:8443/message",
"https://mcp.example.com:444/message",
"//evil.example/message",
"http://user:pass@mcp.example.com:8443/message",
"ftp://mcp.example.com/message",
} {
if got, err := read(line); err == nil {
t.Errorf("%q: accepted as %q, want a refusal", line, got)
}
}
}
func TestReadSSEEndpointDefaultPort(t *testing.T) {
base, err := url.Parse("https://mcp.example.com/sse")
if err != nil {
t.Fatal(err)
}
stream := "data: https://mcp.example.com:443/message\n\n"
if _, err := readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base); err != nil {
t.Fatalf("explicit default port refused: %v", err)
}
}
func TestParseMCPURL(t *testing.T) {
for _, raw := range []string{"ftp://x/y", "not-a-url", "http:///nohost", ""} {
if _, err := parseMCPURL(raw); err == nil {
t.Errorf("%q accepted, want a refusal", raw)
}
}
for _, raw := range []string{"http://x/y", "https://x:8443/y"} {
if _, err := parseMCPURL(raw); err != nil {
t.Errorf("%q refused: %v", raw, err)
}
}
}
func TestLegacySSERefusesCrossOriginEndpoint(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "event: endpoint\ndata: http://evil.invalid/message\n\n")
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := NewSSE(ctx, "test", srv.URL+"/sse", nil, false); err == nil {
t.Fatal("cross-origin SSE endpoint accepted")
}
}
func TestMCPClientRefusesCrossOriginRedirect(t *testing.T) {
var hits int
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits++
}))
defer target.Close()
src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL+"/steal", http.StatusFound)
}))
defer src.Close()
base, err := url.Parse(src.URL + "/sse")
if err != nil {
t.Fatal(err)
}
hc := &http.Client{CheckRedirect: redirectPolicy(base)}
resp, err := hc.Get(src.URL + "/sse")
if err == nil {
resp.Body.Close()
t.Fatal("cross-origin redirect accepted")
}
if hits != 0 {
t.Fatalf("redirect target was reached %d times", hits)
}
}
func TestMCPClientAllowsSameOriginRedirect(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/sse2", http.StatusFound)
})
mux.HandleFunc("/sse2", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := httptest.NewServer(mux)
defer srv.Close()
base, err := url.Parse(srv.URL + "/sse")
if err != nil {
t.Fatal(err)
}
hc := &http.Client{CheckRedirect: redirectPolicy(base)}
resp, err := hc.Get(srv.URL + "/sse")
if err != nil {
t.Fatalf("same-origin redirect refused: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status %d", resp.StatusCode)
}
}
+35
View File
@@ -31,9 +31,44 @@ func (s *Server) wsResolveConfined(rel string) (confinedPath, bool) {
if err != nil {
return confinedPath{}, false
}
if workspacePathDenied(cp.realRoot, cp.realPath) {
return confinedPath{}, false
}
return cp, true
}
// workspaceDeniedPrefixes are platform-internal subtrees under the data dir
// that the workspace file manager must not expose. traffic/_ca holds the
// capture proxy CA private key; traffic/_index holds the SQLite exchange index.
var workspaceDeniedPrefixes = []string{"traffic/_ca", "traffic/_index"}
// workspacePathDenied reports whether realPath lands in a platform-internal
// subtree. It compares the canonicalized path relative to the real root, so a
// symlink alias cannot reach a denied directory. Segments are lower-cased and
// trailing dots/spaces are trimmed because Windows resolves those spellings to
// the same directory.
func workspacePathDenied(realRoot, realPath string) bool {
rel, err := filepath.Rel(realRoot, realPath)
if err != nil {
return true // fail closed
}
rel = filepath.ToSlash(rel)
if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
return true // outside the root: fail closed
}
segs := strings.Split(rel, "/")
for i, seg := range segs {
segs[i] = strings.ToLower(strings.TrimRight(seg, ". "))
}
rel = strings.Join(segs, "/")
for _, prefix := range workspaceDeniedPrefixes {
if rel == prefix || strings.HasPrefix(rel, prefix+"/") {
return true
}
}
return false
}
// wsResolve maps a user-supplied relative path to an absolute path INSIDE the work
// dir. It returns ok=false if the path would escape the root (including via symlinks).
func (s *Server) wsResolve(rel string) (string, bool) {
+68
View File
@@ -0,0 +1,68 @@
package server
import (
"os"
"path/filepath"
"testing"
)
func TestWorkspaceDeniesPlatformPaths(t *testing.T) {
dir := t.TempDir()
for _, p := range []string{"traffic/_ca", "traffic/_index", "traffic/host", "other"} {
if err := os.MkdirAll(filepath.Join(dir, p), 0o755); err != nil {
t.Fatal(err)
}
}
key := filepath.Join(dir, "traffic", "_ca", "mitmproxy-ca.pem")
if err := os.WriteFile(key, []byte("key"), 0o600); err != nil {
t.Fatal(err)
}
s := &Server{m: &Manager{dir: dir}}
for _, rel := range []string{
"traffic/_ca",
"traffic/_ca/mitmproxy-ca.pem",
"traffic/_index",
"traffic/_index/index.sqlite",
"TRAFFIC/_CA/mitmproxy-ca.pem",
"traffic/_ca.",
"traffic/_ca./mitmproxy-ca.pem",
} {
if _, ok := s.wsResolveConfined(rel); ok {
t.Errorf("%q resolved, want a refusal", rel)
}
}
for _, rel := range []string{"", "traffic", "traffic/host", "traffic/_caX", "other"} {
if _, ok := s.wsResolveConfined(rel); !ok {
t.Errorf("%q refused, want a resolution", rel)
}
}
link := filepath.Join(dir, "alias")
if err := os.Symlink(filepath.Join(dir, "traffic", "_ca"), link); err == nil {
if _, ok := s.wsResolveConfined("alias/mitmproxy-ca.pem"); ok {
t.Error("symlink alias to traffic/_ca resolved")
}
}
}
func TestWorkspacePathDenied(t *testing.T) {
root := filepath.Clean("/data")
for _, tc := range []struct {
path string
want bool
}{
{"/data/traffic/_ca", true},
{"/data/traffic/_ca/x", true},
{"/data/traffic/_index/index.sqlite", true},
{"/data/traffic/_caX", false},
{"/data/traffic", false},
{"/data/other", false},
{"/elsewhere/traffic/_ca", true}, // outside the root: fail closed
} {
if got := workspacePathDenied(root, filepath.FromSlash(tc.path)); got != tc.want {
t.Errorf("workspacePathDenied(%q) = %v, want %v", tc.path, got, tc.want)
}
}
}