Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: stream record_stop to disk, validate output path, extend proxy timeout

Mario5202f2daf2af
diff --git a/internal/mcp/client.go b/internal/mcp/client.go
index 85cdd449..31b9a17f 100644
--- a/internal/mcp/client.go
+++ b/internal/mcp/client.go
@@ -90,6 +90,37 @@ func (c *Client) Delete(ctx context.Context, path string, query url.Values) ([]b
return c.do(req)
}
+// PostStream performs a POST request and returns the response body as a
+// ReadCloser so the caller can stream large responses directly to disk.
+// The caller must close the returned body.
+func (c *Client) PostStream(ctx context.Context, path string, payload any) (io.ReadCloser, int, error) {
+ var body io.Reader
+ if payload != nil {
+ b, err := json.Marshal(payload)
+ if err != nil {
+ return nil, 0, fmt.Errorf("marshal payload: %w", err)
+ }
+ body = bytes.NewReader(b)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url(path), body)
+ if err != nil {
+ return nil, 0, err
+ }
+ if payload != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if c.Token != "" {
+ req.Header.Set("Authorization", "Bearer "+c.Token)
+ }
+ req.Header.Set(activity.HeaderAgentID, "mcp")
+ req.Header.Set(activity.HeaderPTSource, "mcp")
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, 0, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)
+ }
+ return resp.Body, resp.StatusCode, nil
+}
+
// Post performs a POST request with a JSON body.
func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, int, error) {
var body io.Reader
diff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.go
index b66eb87e..dd697057 100644
--- a/internal/mcp/client_test.go
+++ b/internal/mcp/client_test.go
@@ -123,6 +123,29 @@ func TestClientPostNilPayload(t *testing.T) {
}
}
+func TestClientPostStreamReturnsReadableBody(t *testing.T) {
+ payload := strings.Repeat("X", 64*1024) // 64 KB — exceeds the 10 MB LimitReader test boundary
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, payload)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "tok")
+ body, code, err := c.PostStream(context.Background(), "/record/stop", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = body.Close() }()
+ if code != 200 {
+ t.Fatalf("code = %d", code)
+ }
+ data, _ := io.ReadAll(body)
+ if len(data) != len(payload) {
+ t.Fatalf("read %d bytes, want %d", len(data), len(payload))
+ }
+}
+
func TestClientAuthHeaderAbsentWhenNoToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h := r.Header.Get("Authorization"); h != "" {
diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.go
index decf069e..41170e36 100644
--- a/internal/mcp/handlers_record.go
+++ b/internal/mcp/handlers_record.go
@@ -3,12 +3,17 @@ package mcp
import (
"context"
"fmt"
+ "io"
"os"
"path/filepath"
"github.com/mark3labs/mcp-go/mcp"
)
+// maxRecordFileBytes caps the output file written by record_stop to prevent
+// unbounded disk writes (matches the server-side maxOutputBytes).
+const maxRecordFileBytes = 256 << 20 // 256 MiB
+
func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file, err := r.RequireString("file")
@@ -58,26 +63,93 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
return mcp.NewToolResultError("file parameter is required"), nil
}
- body, code, err := c.Post(ctx, "/record/stop", map[string]any{})
+ dest, err := safeRecordPath(file)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
+
+ body, code, err := c.PostStream(ctx, "/record/stop", map[string]any{})
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ defer func() { _ = body.Close() }()
+
if code >= 400 {
- return resultFromBytes(body, code)
+ errBody, _ := io.ReadAll(io.LimitReader(body, 10<<20))
+ return resultFromBytes(errBody, code)
}
- if err := os.WriteFile(file, body, 0600); err != nil {
+ n, err := streamToFile(dest, body)
+ if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("write file: %v", err)), nil
}
return jsonResult(map[string]any{
"status": "saved",
- "file": file,
- "bytes": len(body),
+ "file": dest,
+ "bytes": n,
})
}
}
+// safeRecordPath validates a recording output path to prevent arbitrary file
+// overwrites. It requires an absolute path with a supported extension, rejects
+// symlinks and path traversal, and refuses to overwrite existing files.
+func safeRecordPath(file string) (string, error) {
+ cleaned := filepath.Clean(file)
+ if !filepath.IsAbs(cleaned) {
+ return "", fmt.Errorf("file must be an absolute path, got %q", file)
+ }
+
+ ext := filepath.Ext(cleaned)
+ switch ext {
+ case ".gif", ".webm", ".mp4":
+ default:
+ return "", fmt.Errorf("unsupported extension %q — use .gif, .webm, or .mp4", ext)
+ }
+
+ dir := filepath.Dir(cleaned)
+ dirInfo, err := os.Lstat(dir)
+ if err != nil {
+ return "", fmt.Errorf("output directory: %w", err)
+ }
+ if dirInfo.Mode()&os.ModeSymlink != 0 {
+ return "", fmt.Errorf("output directory %q is a symlink", dir)
+ }
+
+ if info, err := os.Lstat(cleaned); err == nil {
+ if info.Mode()&os.ModeSymlink != 0 {
+ return "", fmt.Errorf("refusing to follow symlink at %q", cleaned)
+ }
+ return "", fmt.Errorf("file already exists at %q — remove it first or choose another path", cleaned)
+ }
+
+ return cleaned, nil
+}
+
+// streamToFile writes from r to path using O_CREATE|O_EXCL (no overwrite),
+// capped at maxRecordFileBytes. Returns the number of bytes written.
+func streamToFile(path string, r io.Reader) (int64, error) {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err != nil {
+ return 0, err
+ }
+
+ n, copyErr := io.Copy(f, io.LimitReader(r, maxRecordFileBytes+1))
+ if closeErr := f.Close(); closeErr != nil && copyErr == nil {
+ copyErr = closeErr
+ }
+ if copyErr != nil {
+ _ = os.Remove(path)
+ return 0, copyErr
+ }
+ if n > maxRecordFileBytes {
+ _ = os.Remove(path)
+ return 0, fmt.Errorf("recording exceeds %d MiB limit", maxRecordFileBytes>>20)
+ }
+ return n, nil
+}
+
func handleRecordStatus(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
body, code, err := c.Get(ctx, "/record/status", nil)
diff --git a/internal/mcp/handlers_record_test.go b/internal/mcp/handlers_record_test.go
new file mode 100644
index 00000000..f3d1ce87
--- /dev/null
+++ b/internal/mcp/handlers_record_test.go
@@ -0,0 +1,95 @@
+package mcp
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestSafeRecordPath_RejectsRelativePath(t *testing.T) {
+ _, err := safeRecordPath("relative/output.gif")
+ if err == nil || !strings.Contains(err.Error(), "absolute path") {
+ t.Fatalf("expected absolute path error, got %v", err)
+ }
+}
+
+func TestSafeRecordPath_RejectsBadExtension(t *testing.T) {
+ _, err := safeRecordPath("/tmp/output.txt")
+ if err == nil || !strings.Contains(err.Error(), "unsupported extension") {
+ t.Fatalf("expected extension error, got %v", err)
+ }
+}
+
+func TestSafeRecordPath_RejectsExistingFile(t *testing.T) {
+ f := filepath.Join(t.TempDir(), "existing.gif")
+ if err := os.WriteFile(f, []byte("data"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ _, err := safeRecordPath(f)
+ if err == nil || !strings.Contains(err.Error(), "already exists") {
+ t.Fatalf("expected exists error, got %v", err)
+ }
+}
+
+func TestSafeRecordPath_RejectsSymlink(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "real.gif")
+ link := filepath.Join(dir, "link.gif")
+ if err := os.WriteFile(target, []byte("data"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ _, err := safeRecordPath(link)
+ if err == nil || !strings.Contains(err.Error(), "symlink") {
+ t.Fatalf("expected symlink error, got %v", err)
+ }
+}
+
+func TestSafeRecordPath_AcceptsValidPath(t *testing.T) {
+ dir := t.TempDir()
+ for _, ext := range []string{".gif", ".webm", ".mp4"} {
+ path := filepath.Join(dir, "out"+ext)
+ got, err := safeRecordPath(path)
+ if err != nil {
+ t.Fatalf("ext %s: unexpected error: %v", ext, err)
+ }
+ if got != path {
+ t.Fatalf("ext %s: got %q, want %q", ext, got, path)
+ }
+ }
+}
+
+func TestStreamToFile_WritesAndCaps(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "out.gif")
+
+ data := strings.NewReader("hello recording data")
+ n, err := streamToFile(path, data)
+ if err != nil {
+ t.Fatalf("streamToFile() error = %v", err)
+ }
+ if n != 20 {
+ t.Fatalf("wrote %d bytes, want 20", n)
+ }
+
+ got, _ := os.ReadFile(path)
+ if string(got) != "hello recording data" {
+ t.Fatalf("file content = %q", got)
+ }
+}
+
+func TestStreamToFile_RefusesOverwrite(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "out.gif")
+ if err := os.WriteFile(path, []byte("existing"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err := streamToFile(path, strings.NewReader("new data"))
+ if err == nil {
+ t.Fatal("expected error for existing file")
+ }
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index ffbd63ec..67b2a8a0 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -45,6 +45,7 @@ type Orchestrator struct {
runner HostRunner
mu sync.RWMutex
client *http.Client
+ longClient *http.Client // for routes that can take minutes (e.g. record/stop encoding)
childAuthToken string
allowEvaluate bool
internalToken string
@@ -170,6 +171,7 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator
// - Short timeout (<5s) would break first-request scenarios
// See: internal/orchestrator/health.go (monitor), internal/bridge/init.go (InitChrome)
client: &http.Client{Timeout: 60 * time.Second},
+ longClient: &http.Client{Timeout: 3 * time.Minute},
childAuthToken: "",
allowEvaluate: false,
internalToken: generateInternalToken(),
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 98a56d29..09e092a3 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -114,10 +114,20 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
o.proxyToURL(w, r, targetURL)
}
+// proxyClientForPath returns the HTTP client to use for the given request path.
+// Encoding-heavy routes like /record/stop get a longer timeout.
+func (o *Orchestrator) proxyClientForPath(path string) *http.Client {
+ if strings.HasSuffix(path, "/record/stop") {
+ return o.longClient
+ }
+ return o.client
+}
+
// proxyToURL proxies an HTTP request to the given target URL.
func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {
+ client := o.proxyClientForPath(r.URL.Path)
iproxy.Forward(w, r, targetURL, iproxy.Options{
- Client: o.client,
+ Client: client,
AllowedURL: func(u *url.URL) bool {
return o.proxyTargetInstance(u) != nil
},