High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(mcp): refuse an oversize or short read instead of handing a truncated body on as a success (PIN-304)
Luigi Agostia633d11557af
diff --git a/internal/activity/context.go b/internal/activity/context.goindex b801eaa9..b9362fc0 100644--- a/internal/activity/context.go+++ b/internal/activity/context.go@@ -268,6 +268,15 @@ func initialAction(r *http.Request) string {return ""}+// replayedBody hands the downstream handler the bytes already read followed by the+// rest of the stream, and closes the original. It is a ReadCloser rather than a+// NopCloser over a buffer because the request body is not fully in memory: only the+// peek is.+type replayedBody struct {+ io.Reader+ io.Closer+}+func initialURL(r *http.Request) string {if u := strings.TrimSpace(r.URL.Query().Get("url")); u != "" {return sanitizeActivityURL(u)@@ -275,9 +284,19 @@ func initialURL(r *http.Request) string {return ""}+// activityPeekBytes bounds what the enrichment reads from a request body. It is a+// budget for THIS function's parse, never a limit on the request: the peeked bytes+// are put back in front of the rest, so the handler always sees every byte the+// client sent. Substituting the peek for the body truncated an oversize action or+// navigate payload and then reported the client's own JSON as invalid.+const activityPeekBytes = 8 << 10+// EnrichRouteActivity peeks at the request body for action and navigate-// requests to extract kind, ref, and url for the activity stream. The body-// is restored for the downstream proxy handler.+// requests to extract kind, ref, and url for the activity stream. The body is+// restored in full for the downstream handler: what was read is replayed ahead of+// whatever is still unread, so enrichment costs the request nothing. A payload+// whose first activityPeekBytes are not a complete JSON object simply enriches+// nothing — the activity row loses a field, the request keeps its bytes.func EnrichRouteActivity(r *http.Request) {if r == nil || r.Body == nil || r.Method != http.MethodPost {return@@ -289,11 +308,16 @@ func EnrichRouteActivity(r *http.Request) {return}- body, err := io.ReadAll(io.LimitReader(r.Body, 8<<10))- if err != nil || len(body) == 0 {+ original := r.Body+ peeked, err := io.ReadAll(io.LimitReader(original, activityPeekBytes))+ r.Body = replayedBody{+ Reader: io.MultiReader(bytes.NewReader(peeked), original),+ Closer: original,+ }+ if err != nil || len(peeked) == 0 {return}- r.Body = io.NopCloser(bytes.NewReader(body))+ body := peekedvar peek struct {Kind string `json:"kind"`diff --git a/internal/activity/context_test.go b/internal/activity/context_test.goindex 5efb28a7..fafa1e97 100644--- a/internal/activity/context_test.go+++ b/internal/activity/context_test.go@@ -2,9 +2,12 @@ package activityimport ("context"+ "encoding/json"+ "io""net/http""net/http/httptest""net/url"+ "strings""testing""github.com/pinchtab/pinchtab/internal/authn"@@ -199,3 +202,45 @@ func TestPropagateHeadersUsesAgentIDHeader(t *testing.T) {t.Fatalf("X-PinchTab-Agent-Id = %q, want empty", got)}}++// The enrichment peek is a budget for this package's own parse, never a limit on+// the request. Substituting the peeked bytes for r.Body truncated any action or+// navigate payload over the budget — the routes agents spend their traffic on —+// and the handler then reported the client's own JSON as invalid.+func TestAnOversizeRouteBodyReachesTheHandlerIntact(t *testing.T) {+ filler := strings.Repeat("x", activityPeekBytes*2)+ payload := `{"kind":"fill","ref":"e5","text":"` + filler + `"}`++ req := httptest.NewRequest(http.MethodPost, "/action", strings.NewReader(payload))+ EnrichRouteActivity(req)++ seen, err := io.ReadAll(req.Body)+ if err != nil {+ t.Fatalf("the restored body could not be read: %v", err)+ }+ if string(seen) != payload {+ t.Fatalf("the handler saw %d of %d bytes; the middleware must peek without consuming", len(seen), len(payload))+ }+ var decoded map[string]any+ if err := json.Unmarshal(seen, &decoded); err != nil {+ t.Errorf("the body the handler received no longer parses (%v); PinchTab would report the client's payload as invalid", err)+ }+}++// A body within the budget still enriches, so the fix above did not turn the+// peek off.+func TestASmallRouteBodyStillEnrichesTheActivityRow(t *testing.T) {+ req := httptest.NewRequest(http.MethodPost, "/action", strings.NewReader(`{"kind":"click","ref":"e5"}`))+ state := &requestState{}+ req = req.WithContext(context.WithValue(req.Context(), requestStateKey{}, state))++ EnrichRouteActivity(req)++ if state.event.Action != "click" || state.event.Ref != "e5" {+ t.Errorf("action=%q ref=%q, want the peeked values", state.event.Action, state.event.Ref)+ }+ seen, _ := io.ReadAll(req.Body)+ if string(seen) != `{"kind":"click","ref":"e5"}` {+ t.Errorf("the enriched request lost its body: %q", string(seen))+ }+}diff --git a/internal/cli/apiclient/diagnostics.go b/internal/cli/apiclient/diagnostics.goindex 65893888..3ad1bad4 100644--- a/internal/cli/apiclient/diagnostics.go+++ b/internal/cli/apiclient/diagnostics.go@@ -42,6 +42,10 @@ func CheckServerAndGuide(client *http.Client, base, token string) bool {}if resp.StatusCode >= 400 {+ // The read error is discarded on purpose here, unlike in the transport: this+ // body is only interpolated into an error message the caller is already+ // failing on, so a partial read costs a few characters of context and+ // nothing else.body, _ := io.ReadAll(resp.Body)fmt.Fprintf(os.Stderr, "Server error %d: %s\n", resp.StatusCode, string(body))return falsediff --git a/internal/cli/apiclient/transport.go b/internal/cli/apiclient/transport.goindex 5c00ced1..aa1be074 100644--- a/internal/cli/apiclient/transport.go+++ b/internal/cli/apiclient/transport.go@@ -3,6 +3,7 @@ package apiclientimport ("bytes""encoding/json"+ "fmt""io""net/http""net/url"@@ -56,7 +57,13 @@ func doRequest(client *http.Client, token string, r request) (int, []byte, errorif r.respHeaders != nil {*r.respHeaders = resp.Header}- body, _ := io.ReadAll(resp.Body)+ // A short read is a failed request, never a body: a connection dropping+ // mid-response would otherwise reach the caller as a fragment carrying its+ // status, and the CLI would parse or print the fragment as the answer.+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return resp.StatusCode, nil, fmt.Errorf("read response from %s: %w", r.url, err)+ }return resp.StatusCode, body, nil}diff --git a/internal/cli/apiclient/transport_test.go b/internal/cli/apiclient/transport_test.gonew file mode 100644index 00000000..58917206--- /dev/null+++ b/internal/cli/apiclient/transport_test.go@@ -0,0 +1,66 @@+package apiclient++import (+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// A connection that drops mid-body used to reach the caller as a fragment+// carrying the response's status and no error, and the CLI parsed or printed the+// fragment as the answer. One rule, shared with the MCP client: a short read must+// never become a successful body.+func TestAShortReadIsAFailedRequestRatherThanAPartialBody(t *testing.T) {+ listener, err := net.Listen("tcp4", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = listener.Close() }()++ go func() {+ conn, err := listener.Accept()+ if err != nil {+ return+ }+ buf := make([]byte, 4096)+ _, _ = conn.Read(buf)+ // A length the body never reaches, then the connection dies.+ _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 4096\r\n\r\n"))+ _, _ = conn.Write([]byte(`{"tabs":[`))+ _ = conn.Close()+ }()++ url := fmt.Sprintf("http://%s/tabs", listener.Addr().String())+ code, body, err := doRequest(http.DefaultClient, "", request{method: http.MethodGet, url: url})++ if err == nil {+ t.Fatalf("a truncated response was reported as a success: code %d, %d bytes (%q)", code, len(body), string(body))+ }+ if len(body) != 0 {+ t.Errorf("the failed read still handed back %d bytes for the caller to parse", len(body))+ }+ if !strings.Contains(err.Error(), "/tabs") {+ t.Errorf("the error %q does not name the request that failed", err)+ }+}++// The whole body of a healthy response still comes back, so the guard above is a+// failure rule and not a smaller limit.+func TestACompleteResponseIsStillReturnedWhole(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = io.WriteString(w, `{"tabs":[]}`)+ }))+ defer srv.Close()++ code, body, err := doRequest(http.DefaultClient, "", request{method: http.MethodGet, url: srv.URL + "/tabs"})+ if err != nil {+ t.Fatalf("a complete response was refused: %v", err)+ }+ if code != http.StatusOK || string(body) != `{"tabs":[]}` {+ t.Errorf("code %d body %q, want 200 and the whole body", code, string(body))+ }+}diff --git a/internal/mcp/client.go b/internal/mcp/client.goindex 7597cdfd..011c8115 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -104,13 +104,50 @@ func (c *Client) doWithHeaders(req *http.Request) ([]byte, int, http.Header, err}defer func() { _ = resp.Body.Close() }()- body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) // 10 MB limit+ body, err := io.ReadAll(io.LimitReader(resp.Body, MaxResponseBytes+1))if err != nil {return nil, resp.StatusCode, resp.Header, fmt.Errorf("read response: %w", err)}+ if len(body) > MaxResponseBytes {+ return nil, resp.StatusCode, resp.Header, oversizeResponseError(req.URL.Path, resp.ContentLength)+ }return body, resp.StatusCode, resp.Header, nil}+// MaxResponseBytes caps what the MCP server will read from one PinchTab response.+// The read takes MaxResponseBytes+1 and refuses above the cap — the module's idiom+// wherever a limit exists — because a body cut at exactly the cap is indistinguishable+// from a whole one, and the consumer here is a language model that cannot tell a+// truncated base64 image from a complete one.+const MaxResponseBytes = 10 << 20++// oversizeResponseError refuses the read and tells the agent how to ask for less.+// A refusal an agent cannot act on is retried verbatim, so the remedy is keyed to the+// endpoint that produced the body rather than being a generic "too large".+func oversizeResponseError(path string, contentLength int64) error {+ seen := "more than"+ if contentLength >= 0 {+ seen = fmt.Sprintf("%d bytes, over", contentLength)+ }+ return fmt.Errorf("%s returned %s the %d-byte response limit and was refused rather than truncated; %s",+ path, seen, MaxResponseBytes, oversizeRemedy(path))+}++// oversizeRemedy names the narrowing argument of the tool that reaches each path.+func oversizeRemedy(path string) string {+ switch {+ case strings.HasSuffix(path, "/screenshot"):+ return "retry with beyondViewport=false, a lower quality, or a selector so only one element is captured"+ case strings.HasSuffix(path, "/capture"):+ return "retry with beyondViewport=false, a lower quality, or interactiveOnly so the snapshot half is smaller"+ case strings.HasSuffix(path, "/snapshot"), strings.HasSuffix(path, "/text"),+ strings.HasSuffix(path, "/html"), strings.HasSuffix(path, "/scrape"):+ return "retry with a selector, a smaller depth, or interactiveOnly to read one region instead of the page"+ default:+ return "retry asking for less of the page"+ }+}+// GetCapturingVocab performs a GET and records the response's vocabulary token// under tabKey, so a later interaction on the same tab echoes it. tabKey is the// tab as the caller addresses it (the tabId argument, possibly empty), which isdiff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.goindex b66eb87e..218602e1 100644--- a/internal/mcp/client_test.go+++ b/internal/mcp/client_test.go@@ -1,13 +1,17 @@package mcpimport (+ "bytes""context"+ "encoding/json""io""net/http""net/http/httptest""net/url""strings""testing"++ "github.com/mark3labs/mcp-go/mcp")func TestNewClient(t *testing.T) {@@ -157,3 +161,122 @@ func TestClientDashboardProfilesURL(t *testing.T) {t.Fatalf("dashboardProfilesURL = %q, want %q", got, want)}}++// A body cut at exactly the cap is indistinguishable from a whole one, and the+// consumer here is a model: a truncated 10 MB base64 image arrived as a+// successful text block that nothing on the path could see was incomplete.+func TestAnOversizeResponseIsRefusedRatherThanTruncated(t *testing.T) {+ const sent = MaxResponseBytes + (1 << 20)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(200)+ _, _ = io.WriteString(w, `{"format":"png","base64":"`)+ _, _ = w.Write(bytes.Repeat([]byte("A"), sent))+ }))+ defer srv.Close()++ c := NewClient(srv.URL, "")+ body, code, err := c.Get(context.Background(), "/screenshot", nil)++ if err == nil {+ t.Fatalf("an oversize response was accepted: %d bytes, code %d", len(body), code)+ }+ if len(body) != 0 {+ t.Errorf("a refused read still returned %d bytes; a partial body must never reach a caller", len(body))+ }+ for _, want := range []string{"/screenshot", "10485760", "beyondViewport=false"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("the refusal %q does not carry %q — an agent that cannot act on it retries the same call", err, want)+ }+ }+}++// A body exactly at the limit is whole and must still be served: reading limit+1+// is a detection scheme, not a smaller limit.+func TestAResponseExactlyAtTheLimitIsServed(t *testing.T) {+ payload := bytes.Repeat([]byte("B"), MaxResponseBytes)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write(payload)+ }))+ defer srv.Close()++ body, _, err := NewClient(srv.URL, "").Get(context.Background(), "/text", nil)+ if err != nil {+ t.Fatalf("a body at exactly the limit was refused: %v", err)+ }+ if len(body) != MaxResponseBytes {+ t.Errorf("read %d bytes, want the whole %d", len(body), MaxResponseBytes)+ }+}++// The whole path, as the agent sees it: the tool must answer with an error+// result, and must not spend the model's context on megabytes of truncated+// base64 dressed as text.+func TestTheScreenshotToolReportsAnOversizeResponseAsAnError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = io.WriteString(w, `{"format":"png","base64":"`)+ _, _ = w.Write(bytes.Repeat([]byte("A"), MaxResponseBytes+(1<<20)))+ }))+ defer srv.Close()++ result, err := handleScreenshot(NewClient(srv.URL, ""))(context.Background(), mcp.CallToolRequest{})+ if err != nil {+ t.Fatalf("handler returned a transport error instead of a tool result: %v", err)+ }+ if !result.IsError {+ t.Fatal("the oversize response reached the agent as a success")+ }+ encoded, err := json.Marshal(result.Content)+ if err != nil {+ t.Fatal(err)+ }+ if len(encoded) > maxEchoedScreenshotBytes {+ t.Errorf("the result carries %d bytes of content; a refusal must not echo the payload it refused", len(encoded))+ }+}++// The fallback exists for a small error envelope or an unmodelled field, and+// still serves that case — the refusal above must not have swallowed it.+func TestTheScreenshotFallbackStillSurfacesASmallUnparseableBody(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = io.WriteString(w, `{"error":"screenshot failed: tab crashed"}`)+ }))+ defer srv.Close()++ result, err := handleScreenshot(NewClient(srv.URL, ""))(context.Background(), mcp.CallToolRequest{})+ if err != nil {+ t.Fatal(err)+ }+ encoded, err := json.Marshal(result.Content)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(encoded), "tab crashed") {+ t.Errorf("the small-envelope fallback stopped surfacing the server's reason: %s", encoded)+ }+}++// Below the client's limit and above an envelope: a damaged image payload that+// does not parse. The old fallback echoed it verbatim as text, which is the same+// defect one layer down from the truncation this card removes.+func TestTheScreenshotFallbackRefusesABodyTooLargeToBeAnEnvelope(t *testing.T) {+ damaged := append([]byte(`{"format":"png","base64":"`), bytes.Repeat([]byte("A"), 100<<10)...)++ result, err := screenshotResult(damaged, false)+ if err != nil {+ t.Fatal(err)+ }+ if !result.IsError {+ t.Fatal("a damaged multi-kilobyte payload was reported as a success")+ }+ encoded, err := json.Marshal(result.Content)+ if err != nil {+ t.Fatal(err)+ }+ if len(encoded) > maxEchoedScreenshotBytes {+ t.Errorf("the refusal echoed %d bytes of the payload it refused", len(encoded))+ }+ if !strings.Contains(string(encoded), "beyondViewport=false") {+ t.Errorf("the refusal does not tell the agent how to ask for less: %s", encoded)+ }+}diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex 1a91ce97..6cd8bd49 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -225,12 +225,22 @@ func handleScreenshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mc}}+// maxEchoedScreenshotBytes bounds the raw-bytes fallback below. An error envelope+// or an unrecognised field is small; anything of image scale that failed to parse+// is a damaged payload, and echoing it verbatim spends the model's context on+// megabytes of base64 that mean nothing.+const maxEchoedScreenshotBytes = 8 << 10+// screenshotResult turns the /screenshot JSON envelope into an MCP image// result so clients can render the picture natively. The text portion is// always a JSON object `{"format", "annotations": [...]}` so downstream-// callers can parse one stable schema regardless of `annotate`. On any parse-// hiccup we fall back to the raw bytes so error envelopes and future fields-// still surface.+// callers can parse one stable schema regardless of `annotate`.+//+// On a parse hiccup it falls back to the raw bytes, which serves the case it was+// written for — a small error envelope, or a future field this struct does not+// model. It refuses the other case that reaches the same branch: a body too large+// to be either, which is a damaged image payload and is reported as one instead of+// being handed to the model as text.func screenshotResult(body []byte, annotate bool) (*mcp.CallToolResult, error) {var env struct {Format string `json:"format"`@@ -238,6 +248,11 @@ func screenshotResult(body []byte, annotate bool) (*mcp.CallToolResult, error) {Annotations json.RawMessage `json:"annotations,omitempty"`}if err := json.Unmarshal(body, &env); err != nil || env.Base64 == "" {+ if len(body) > maxEchoedScreenshotBytes {+ return mcp.NewToolResultError(fmt.Sprintf(+ "the screenshot response was %d bytes and carried no readable image; it is not echoed because a damaged image payload is not readable text — retry with beyondViewport=false, a lower quality, or a selector",+ len(body))), nil+ }return resultFromBytes(body, 200)}diff --git a/internal/mcp/short_read_census_test.go b/internal/mcp/short_read_census_test.gonew file mode 100644index 00000000..25d91dc8--- /dev/null+++ b/internal/mcp/short_read_census_test.go@@ -0,0 +1,103 @@+package mcp++import (+ "sort"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// One rule, module-wide: a short read must never become a successful body. Every+// capped read is classified here, because the discriminator is not whether the+// call writes limit+1 — it is whether the truncated value is then consumed as if+// it were whole. This client capped at exactly the limit and handed a model a+// truncated base64 image as a success; the activity middleware capped the INBOUND+// body and substituted the peek for it, so an oversize action reached the handler+// mangled and PinchTab blamed the client for the JSON it had cut.+//+// The census is the record of the two permanent exclusions as well as the guard,+// so a later sweep meets their reasons where it would look rather than re-opening+// them from the outside.+const (+ refusesOverTheCap = "reads limit+1 and refuses above it"+ peeksWithoutTaking = "peeks a prefix and leaves the stream whole for its consumer"+ unreachableCap = "the cap cannot be reached by anything that passed the guard in front of it"+ loudOnTruncation = "a truncated value cannot parse, so the request is refused rather than accepted"+)++var cappedReads = map[string]string{+ "internal/mcp/client.go": refusesOverTheCap,+ "internal/handlers/download_fetch.go": refusesOverTheCap,+ "internal/orchestrator/tab_extract.go": refusesOverTheCap,+ "internal/bridge/runtime/cdp_url.go": refusesOverTheCap,+ "internal/activity/context.go": peeksWithoutTaking,+ // Permanent: isSmallJSON gates the read on Content-Length >= 0 && <= 64 KB+ // against the same 64 KB cap, so the limit is unreachable. That is a property+ // of the input, not a promise about future behaviour.+ "internal/proxy/proxy.go": unreachableCap,+ // Loud but misattributed, and left as it is: a truncated config PUT does not+ // parse, so it answers 400 rather than writing a partial config. The only cost+ // is that bad_config_json blames the client for a truncation PinchTab performed.+ "internal/dashboard/config_api.go": loudOnTruncation,+}++func TestEveryCappedReadIsClassified(t *testing.T) {+ var found []string+ for _, file := range srccensus.Tree(t, "../..", 200) {+ if strings.Contains(file.Text, "io.LimitReader(") {+ found = append(found, file.Name)+ }+ }+ sort.Strings(found)+ if len(found) < len(cappedReads) {+ t.Fatalf("found %d capped reads for %d classified; the census is matching almost nothing and would pass vacuously", len(found), len(cappedReads))+ }++ for _, name := range found {+ if _, ok := cappedReads[name]; !ok {+ t.Errorf("%s caps a read and is not classified; say which it is — %q, %q, or an exclusion with the reason the truncated value is never consumed as whole",+ name, refusesOverTheCap, peeksWithoutTaking)+ }+ }+ for name := range cappedReads {+ if !containsName(found, name) {+ t.Errorf("%s is classified here and no longer caps a read; drop the entry rather than leaving the census guarding one site fewer than it claims", name)+ }+ }++ // The two sites this card fixed carry the rule's own idiom, so a revert is+ // visible here as well as in the behaviour tests.+ for name, want := range map[string]string{+ "internal/mcp/client.go": "MaxResponseBytes+1",+ "internal/activity/context.go": "io.MultiReader",+ } {+ if !fileText(t, name).Contains(want) {+ t.Errorf("%s no longer carries %q; the classification above says it refuses or replays, and it does neither", name, want)+ }+ }+}++func containsName(names []string, want string) bool {+ for _, name := range names {+ if name == want {+ return true+ }+ }+ return false+}++type censusText string++func (c censusText) Contains(want string) bool { return strings.Contains(string(c), want) }++func fileText(t *testing.T, name string) censusText {+ t.Helper()+ for _, file := range srccensus.Tree(t, "../..", 200) {+ if file.Name == name {+ return censusText(file.Text)+ }+ }+ t.Fatalf("%s is not in the module source any more", name)+ return ""+}