Skip to content

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

refactor: an optional JSON body is decoded by 14 hand-rolled copies with three different presence gates and two oversize statuses; fold them into one decoder per strictness (PIN-371)

Luigi Agosti7930e24e14b4
diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.go
index 8114e8de..a6910843 100644
--- a/internal/handlers/handoff.go
+++ b/internal/handlers/handoff.go
@@ -1,10 +1,7 @@
package handlers
import (
- "encoding/json"
- "errors"
"fmt"
- "io"
"net/http"
"strings"
"time"
@@ -137,8 +134,7 @@ func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {
Reason string `json:"reason"`
TimeoutMs int `json:"timeoutMs"`
}
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ if !decodeOptionalJSON(w, r, &req) {
return
}
@@ -196,8 +192,7 @@ func (h *Handlers) HandleTabResume(w http.ResponseWriter, r *http.Request) {
Status string `json:"status"`
Data map[string]any `json:"resolvedData"`
}
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ if !decodeOptionalJSON(w, r, &req) {
return
}
diff --git a/internal/handlers/limits.go b/internal/handlers/limits.go
index 1bc19198..b45f5a10 100644
--- a/internal/handlers/limits.go
+++ b/internal/handlers/limits.go
@@ -1,3 +1,22 @@
package handlers
-const maxBodySize = 1 << 20
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+const maxBodySize = httpx.DefaultMaxJSONBodyBytes
+
+func decodeOptionalJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
+ err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(dst)
+ if err == nil || errors.Is(err, io.EOF) {
+ return true
+ }
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), fmt.Errorf("decode: %w", err))
+ return false
+}
diff --git a/internal/handlers/limits_test.go b/internal/handlers/limits_test.go
new file mode 100644
index 00000000..9b796c13
--- /dev/null
+++ b/internal/handlers/limits_test.go
@@ -0,0 +1,39 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/httpx/httpxtest"
+)
+
+func TestDecodeOptionalJSONDecodesEachBodyShapeLeniently(t *testing.T) {
+ type payload struct {
+ TabID string `json:"tabId"`
+ }
+ for _, c := range httpxtest.OptionalBodyCases() {
+ t.Run(c.Name, func(t *testing.T) {
+ var got payload
+ w := httptest.NewRecorder()
+
+ ok := decodeOptionalJSON(w, c.Request(http.MethodPost, "/", `{"tabId":"tab1"}`), &got)
+
+ want := payload{}
+ if c.Name == "chunked valid payload" {
+ want.TabID = "tab1"
+ }
+ if proceeds := c.Lenient == httpxtest.Proceeds; ok != proceeds || (ok && got != want) {
+ t.Fatalf("ok=%v decoded %+v, want ok=%v %+v", ok, got, proceeds, want)
+ }
+ c.Check(t, false, w)
+ })
+ }
+}
+
+func TestMaxBodySizeIsTheSharedJSONBodyLimit(t *testing.T) {
+ if maxBodySize != httpx.DefaultMaxJSONBodyBytes {
+ t.Fatalf("maxBodySize = %d, want httpx.DefaultMaxJSONBodyBytes (%d)", maxBodySize, httpx.DefaultMaxJSONBodyBytes)
+ }
+}
diff --git a/internal/handlers/network_route.go b/internal/handlers/network_route.go
index 39920195..e4b335ac 100644
--- a/internal/handlers/network_route.go
+++ b/internal/handlers/network_route.go
@@ -3,9 +3,7 @@ package handlers
import (
"context"
"encoding/json"
- "errors"
"fmt"
- "io"
"net/http"
"github.com/pinchtab/pinchtab/internal/bridge"
@@ -190,12 +188,11 @@ func (h *Handlers) handleNetworkUnrouteFor(w http.ResponseWriter, r *http.Reques
}
pattern := r.URL.Query().Get("pattern")
- if pattern == "" && httpx.MayHaveBody(r) {
+ if pattern == "" {
var body struct {
Pattern string `json:"pattern"`
}
- if err := json.NewDecoder(r.Body).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode body: %w", err))
+ if !decodeOptionalJSON(w, r, &body) {
return
}
pattern = body.Pattern
diff --git a/internal/handlers/optional_body_sites_test.go b/internal/handlers/optional_body_sites_test.go
new file mode 100644
index 00000000..d02bb348
--- /dev/null
+++ b/internal/handlers/optional_body_sites_test.go
@@ -0,0 +1,51 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/httpx/httpxtest"
+)
+
+type routeStubBridge struct{ *mockBridge }
+
+func (routeStubBridge) RemoveRouteRule(string, string) (int, error) { return 0, nil }
+
+func (routeStubBridge) ListRouteRules(string) ([]bridge.RouteRule, error) { return nil, nil }
+
+func TestEveryOptionalBodySiteDecodesTheSameWay(t *testing.T) {
+ sites := []struct {
+ name string
+ method string
+ target string
+ payload string
+ strict bool
+ }{
+ {"tab handoff", http.MethodPost, "/tabs/tab1/handoff", `{"reason":"captcha"}`, false},
+ {"tab resume", http.MethodPost, "/tabs/tab1/resume", `{"status":"done"}`, false},
+ {"solve", http.MethodPost, "/solve", `{"maxAttempts":1}`, false},
+ {"tab close", http.MethodPost, "/tabs/tab1/close", `{"tabId":"tab1"}`, false},
+ {"close", http.MethodPost, "/close", `{"tabId":"tab1"}`, false},
+ {"network unroute", http.MethodDelete, "/network/route", `{"pattern":"*.png"}`, false},
+ {"path tab id body adapter", http.MethodPost, "/tabs/tab1/action", `{"kind":"click","ref":"e1"}`, false},
+ {"tab pdf", http.MethodPost, "/tabs/tab1/pdf", `{"landscape":true}`, false},
+ {"record stop", http.MethodPost, "/record/stop", `{"discard":true}`, true},
+ }
+ for _, site := range sites {
+ for _, c := range httpxtest.OptionalBodyCases() {
+ t.Run(site.name+"/"+c.Name, func(t *testing.T) {
+ h := New(routeStubBridge{&mockBridge{}}, &config.RuntimeConfig{AllowScreencast: true, AllowNetworkIntercept: true}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+ w := httptest.NewRecorder()
+
+ mux.ServeHTTP(w, c.Request(site.method, site.target, site.payload))
+
+ c.Check(t, site.strict, w)
+ })
+ }
+ }
+}
diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.go
index ce28e9db..56942b8b 100644
--- a/internal/handlers/pdf.go
+++ b/internal/handlers/pdf.go
@@ -3,10 +3,7 @@ package handlers
import (
"context"
"encoding/base64"
- "encoding/json"
- "errors"
"fmt"
- "io"
"net/http"
"os"
"path/filepath"
@@ -243,32 +240,29 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
provided := ""
if r.Method == http.MethodPost {
var body map[string]any
- if httpx.MayHaveBody(r) {
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
+ if !decodeOptionalJSON(w, r, &body) {
+ return
+ }
+ var err error
+ if provided, err = bodyTabID(body); err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ for key, value := range body {
+ if _, ok := pdfQueryParams[key]; !ok {
+ continue
}
- var err error
- if provided, err = bodyTabID(body); err != nil {
- httpx.Error(w, 400, err)
+ switch v := value.(type) {
+ case string:
+ q.Set(key, v)
+ case bool:
+ q.Set(key, strconv.FormatBool(v))
+ case float64:
+ q.Set(key, strconv.FormatFloat(v, 'f', -1, 64))
+ default:
+ httpx.Error(w, 400, fmt.Errorf("invalid %s type", key))
return
}
- for key, value := range body {
- if _, ok := pdfQueryParams[key]; !ok {
- continue
- }
- switch v := value.(type) {
- case string:
- q.Set(key, v)
- case bool:
- q.Set(key, strconv.FormatBool(v))
- case float64:
- q.Set(key, strconv.FormatFloat(v, 'f', -1, 64))
- default:
- httpx.Error(w, 400, fmt.Errorf("invalid %s type", key))
- return
- }
- }
}
}
tabID, ok := h.requirePathTabIDMatch(w, r, provided)
diff --git a/internal/handlers/record_handlers.go b/internal/handlers/record_handlers.go
index 19661b5e..ed828714 100644
--- a/internal/handlers/record_handlers.go
+++ b/internal/handlers/record_handlers.go
@@ -1,9 +1,7 @@
package handlers
import (
- "errors"
"fmt"
- "io"
"log/slog"
"net/http"
"os"
@@ -114,7 +112,7 @@ func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
var req struct {
Discard bool `json:"discard"`
}
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
return
}
diff --git a/internal/handlers/solver.go b/internal/handlers/solver.go
index ec2325b2..78755ff4 100644
--- a/internal/handlers/solver.go
+++ b/internal/handlers/solver.go
@@ -2,10 +2,7 @@ package handlers
import (
"context"
- "encoding/json"
- "errors"
"fmt"
- "io"
"net/http"
"time"
@@ -53,8 +50,7 @@ func (h *Handlers) HandleSolve(w http.ResponseWriter, r *http.Request) {
Timeout float64 `json:"timeout"`
}
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ if !decodeOptionalJSON(w, r, &req) {
return
}
diff --git a/internal/handlers/tab_body_adapter.go b/internal/handlers/tab_body_adapter.go
index e116ea26..0a28f12b 100644
--- a/internal/handlers/tab_body_adapter.go
+++ b/internal/handlers/tab_body_adapter.go
@@ -3,7 +3,6 @@ package handlers
import (
"bytes"
"encoding/json"
- "errors"
"fmt"
"io"
"net/http"
@@ -75,9 +74,7 @@ func (h *Handlers) withPathTabIDBody(w http.ResponseWriter, r *http.Request, roo
// mutate makes it identical to withPathTabIDBody.
func (h *Handlers) withPathTabIDBodyMutate(w http.ResponseWriter, r *http.Request, mutate func(body map[string]any), root http.HandlerFunc) {
body := map[string]any{}
- dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
- if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ if !decodeOptionalJSON(w, r, &body) {
return
}
provided, err := bodyTabID(body)
diff --git a/internal/handlers/tab_lifecycle.go b/internal/handlers/tab_lifecycle.go
index b169b2ca..3b7cd160 100644
--- a/internal/handlers/tab_lifecycle.go
+++ b/internal/handlers/tab_lifecycle.go
@@ -3,9 +3,7 @@ package handlers
import (
"context"
"encoding/json"
- "errors"
"fmt"
- "io"
"net/http"
"strings"
@@ -131,11 +129,8 @@ func (h *Handlers) HandleTabClose(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
}
- if httpx.MayHaveBody(r) {
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
+ if !decodeOptionalJSON(w, r, &req) {
+ return
}
tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)
if !ok {
@@ -151,8 +146,7 @@ func (h *Handlers) HandleClose(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
}
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ if !decodeOptionalJSON(w, r, &req) {
return
}
diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.go
index c0428678..2cd2a9b0 100644
--- a/internal/httpx/httpx.go
+++ b/internal/httpx/httpx.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log/slog"
"net"
"net/http"
@@ -182,6 +183,13 @@ func DecodeJSONBody(w http.ResponseWriter, r *http.Request, maxBytes int64, dst
return nil
}
+func DecodeOptionalJSONBody(w http.ResponseWriter, r *http.Request, maxBytes int64, dst any) error {
+ if err := DecodeJSONBody(w, r, maxBytes, dst); err != nil && !errors.Is(err, io.EOF) {
+ return err
+ }
+ return nil
+}
+
func clarifyUnknownJSONField(err error, dst any) error {
if !strings.HasPrefix(err.Error(), "json: unknown field ") {
return err
diff --git a/internal/httpx/httpxtest/optional_body.go b/internal/httpx/httpxtest/optional_body.go
new file mode 100644
index 00000000..c03b4bac
--- /dev/null
+++ b/internal/httpx/httpxtest/optional_body.go
@@ -0,0 +1,92 @@
+package httpxtest
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+type Outcome int
+
+const (
+ Proceeds Outcome = iota
+ BadRequest
+ TooLarge
+)
+
+type OptionalBodyCase struct {
+ Name string
+ Body string
+ Chunked bool
+ Absent bool
+ Strict Outcome
+ Lenient Outcome
+ payload bool
+}
+
+func OptionalBodyCases() []OptionalBodyCase {
+ return []OptionalBodyCase{
+ {Name: "no body", Absent: true, Strict: Proceeds, Lenient: Proceeds},
+ {Name: "empty chunked body", Chunked: true, Strict: Proceeds, Lenient: Proceeds},
+ {Name: "chunked valid payload", Chunked: true, payload: true, Strict: Proceeds, Lenient: Proceeds},
+ {Name: "malformed JSON", Body: `{"a":`, Strict: BadRequest, Lenient: BadRequest},
+ {Name: "body over 1 MiB", Body: `{"pad":"` + strings.Repeat("x", 1<<20) + `"}`, Strict: TooLarge, Lenient: TooLarge},
+ {Name: "unknown field", Body: `{"zzUnknownField":1}`, Strict: BadRequest, Lenient: Proceeds},
+ }
+}
+
+func (c OptionalBodyCase) Request(method, target, payload string) *http.Request {
+ if c.Absent {
+ return httptest.NewRequest(method, target, http.NoBody)
+ }
+ body := c.Body
+ if c.payload {
+ body = payload
+ }
+ req := httptest.NewRequest(method, target, io.NopCloser(strings.NewReader(body)))
+ req.Header.Set("Content-Type", "application/json")
+ if c.Chunked {
+ req.ContentLength = -1
+ req.TransferEncoding = []string{"chunked"}
+ }
+ return req
+}
+
+var decodeRefusalMarkers = []string{"decode:", "unexpected EOF", "invalid character", "unknown field", "request body too large", "cannot unmarshal"}
+
+func refusedByDecode(body string) bool {
+ for _, marker := range decodeRefusalMarkers {
+ if strings.Contains(body, marker) {
+ return true
+ }
+ }
+ return false
+}
+
+func (c OptionalBodyCase) Check(t *testing.T, strict bool, w *httptest.ResponseRecorder) {
+ t.Helper()
+ want := c.Lenient
+ if strict {
+ want = c.Strict
+ }
+ body := w.Body.String()
+ if strings.Contains(body, "404 page not found") {
+ t.Fatalf("%s: the request never reached a handler", c.Name)
+ }
+ switch want {
+ case Proceeds:
+ if w.Code == http.StatusRequestEntityTooLarge || refusedByDecode(body) {
+ t.Fatalf("%s: the body decode refused it (%d): %s", c.Name, w.Code, body)
+ }
+ case BadRequest:
+ if w.Code != http.StatusBadRequest || !refusedByDecode(body) {
+ t.Fatalf("%s: got %d %s, want a 400 decode refusal", c.Name, w.Code, body)
+ }
+ case TooLarge:
+ if w.Code != http.StatusRequestEntityTooLarge {
+ t.Fatalf("%s: got %d %.200s, want 413", c.Name, w.Code, body)
+ }
+ }
+}
diff --git a/internal/httpx/optional_body_census_test.go b/internal/httpx/optional_body_census_test.go
new file mode 100644
index 00000000..02c04d18
--- /dev/null
+++ b/internal/httpx/optional_body_census_test.go
@@ -0,0 +1,167 @@
+package httpx
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+var optionalBodyOwners = map[string]bool{
+ "internal/httpx/httpx.go::DecodeOptionalJSONBody": true,
+ "internal/handlers/limits.go::decodeOptionalJSON": true,
+}
+
+func decodeEOFSites(t *testing.T, name, src string) []string {
+ t.Helper()
+ file, err := parser.ParseFile(token.NewFileSet(), name, src, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", name, err)
+ }
+ var sites []string
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ decodeErrs := decodeErrorNames(fn.Body)
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ if subject, ok := eofComparisonSubject(n); ok && decodeErrs[subject] {
+ sites = append(sites, name+"::"+fn.Name.Name)
+ }
+ return true
+ })
+ }
+ return sites
+}
+
+func decodeErrorNames(body *ast.BlockStmt) map[string]bool {
+ names := map[string]bool{}
+ ast.Inspect(body, func(n ast.Node) bool {
+ assign, ok := n.(*ast.AssignStmt)
+ if !ok || len(assign.Rhs) != 1 {
+ return true
+ }
+ call, ok := assign.Rhs[0].(*ast.CallExpr)
+ if !ok || !isDecodeCall(call.Fun) {
+ return true
+ }
+ for _, lhs := range assign.Lhs {
+ if ident, ok := lhs.(*ast.Ident); ok {
+ names[ident.Name] = true
+ }
+ }
+ return true
+ })
+ return names
+}
+
+func isDecodeCall(fun ast.Expr) bool {
+ switch f := fun.(type) {
+ case *ast.SelectorExpr:
+ return f.Sel.Name == "Decode" || f.Sel.Name == "DecodeJSONBody"
+ case *ast.Ident:
+ return f.Name == "DecodeJSONBody"
+ }
+ return false
+}
+
+func isIOEOF(e ast.Expr) bool {
+ sel, ok := e.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "EOF" {
+ return false
+ }
+ pkg, ok := sel.X.(*ast.Ident)
+ return ok && pkg.Name == "io"
+}
+
+func eofComparisonSubject(n ast.Node) (string, bool) {
+ switch e := n.(type) {
+ case *ast.BinaryExpr:
+ if (e.Op == token.EQL || e.Op == token.NEQ) && isIOEOF(e.Y) {
+ if ident, ok := e.X.(*ast.Ident); ok {
+ return ident.Name, true
+ }
+ }
+ case *ast.CallExpr:
+ sel, ok := e.Fun.(*ast.SelectorExpr)
+ if ok && sel.Sel.Name == "Is" && len(e.Args) == 2 && isIOEOF(e.Args[1]) {
+ if ident, ok := e.Args[0].(*ast.Ident); ok {
+ return ident.Name, true
+ }
+ }
+ }
+ return "", false
+}
+
+func TestOnlyTheTwoHelpersTreatADecodeEOFAsAnEmptyBody(t *testing.T) {
+ found := map[string]bool{}
+ sawTokenizer := false
+ for _, file := range srccensus.Tree(t, "../..", 200) {
+ if !strings.HasPrefix(file.Name, "internal/") {
+ continue
+ }
+ for _, site := range decodeEOFSites(t, file.Name, file.Text) {
+ found[site] = true
+ }
+ if file.Name == "internal/browsers/ghostchrome/staticfetch/staticfetch.go" {
+ sawTokenizer = strings.Contains(file.Text, "z.Err() == io.EOF")
+ }
+ }
+
+ var stray []string
+ for site := range found {
+ if !optionalBodyOwners[site] {
+ stray = append(stray, site)
+ }
+ }
+ sort.Strings(stray)
+ for _, site := range stray {
+ t.Errorf("%s treats a JSON decode io.EOF as an empty body by hand; call httpx.DecodeOptionalJSONBody (strict) or decodeOptionalJSON (lenient, package handlers)", site)
+ }
+ for owner := range optionalBodyOwners {
+ if !found[owner] {
+ t.Errorf("%s no longer matches; the census would guard nothing there, so update the owner table", owner)
+ }
+ }
+ if !sawTokenizer {
+ t.Error("staticfetch's tokenizer io.EOF check is gone; the near-miss this census must leave alone is no longer exercised on real code")
+ }
+}
+
+func TestTheDecodeEOFCensusSeesAPlantedCopyAndNotANonDecodeRead(t *testing.T) {
+ const planted = `package p
+func strict(w http.ResponseWriter, r *http.Request) {
+ if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
+ return
+ }
+}
+func lenient(r *http.Request) {
+ decodeErr := json.NewDecoder(r.Body).Decode(&req)
+ if decodeErr != nil && decodeErr != io.EOF {
+ return
+ }
+}
+func read(r io.Reader) {
+ n, err := r.Read(buf)
+ if err == io.EOF {
+ return
+ }
+ _ = n
+}
+func tokenizer(z *html.Tokenizer) {
+ if z.Err() == io.EOF {
+ return
+ }
+}
+`
+ got := decodeEOFSites(t, "planted.go", planted)
+
+ if strings.Join(got, ",") != "planted.go::strict,planted.go::lenient" {
+ t.Fatalf("census found %v, want the two planted decode copies and neither the read nor the tokenizer", got)
+ }
+}
diff --git a/internal/httpx/optional_body_test.go b/internal/httpx/optional_body_test.go
new file mode 100644
index 00000000..31db19d1
--- /dev/null
+++ b/internal/httpx/optional_body_test.go
@@ -0,0 +1,45 @@
+package httpx
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/httpx/httpxtest"
+)
+
+func TestDecodeOptionalJSONBodyDecodesEachBodyShape(t *testing.T) {
+ type payload struct {
+ URL string `json:"url"`
+ }
+ for _, c := range httpxtest.OptionalBodyCases() {
+ t.Run(c.Name, func(t *testing.T) {
+ var got payload
+ w := httptest.NewRecorder()
+
+ err := DecodeOptionalJSONBody(w, c.Request(http.MethodPost, "/", `{"url":"https://example.com"}`), 0, &got)
+
+ switch c.Strict {
+ case httpxtest.Proceeds:
+ want := payload{}
+ if c.Name == "chunked valid payload" {
+ want.URL = "https://example.com"
+ }
+ if err != nil || got != want {
+ t.Fatalf("decoded %+v, %v; want %+v, nil", got, err, want)
+ }
+ case httpxtest.BadRequest:
+ if err == nil || StatusForJSONDecodeError(err) != http.StatusBadRequest {
+ t.Fatalf("err = %v, want a 400 decode error", err)
+ }
+ case httpxtest.TooLarge:
+ if err == nil || StatusForJSONDecodeError(err) != http.StatusRequestEntityTooLarge {
+ t.Fatalf("err = %v, want a 413 decode error", err)
+ }
+ }
+ if w.Body.Len() != 0 || w.Code != http.StatusOK {
+ t.Fatalf("the helper wrote a response (%d %q); its callers own that", w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index e5b9a1bc..de415caa 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
"net/http"
"net/url"
"strings"
@@ -55,11 +54,9 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request
Name string `json:"name,omitempty"`
}
- if r.Body != nil {
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
- return
- }
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
}
if req.Name != "" {
@@ -232,11 +229,9 @@ func (o *Orchestrator) handleLogsStreamByID(w http.ResponseWriter, r *http.Reque
func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Request) {
var req startInstanceRequest
- if r.Body != nil {
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
- return
- }
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
}
o.startInstanceWithRequest(w, r, req, "instance.started")
diff --git a/internal/orchestrator/handlers_profiles.go b/internal/orchestrator/handlers_profiles.go
index f8f2f2b7..4e42b084 100644
--- a/internal/orchestrator/handlers_profiles.go
+++ b/internal/orchestrator/handlers_profiles.go
@@ -1,9 +1,7 @@
package orchestrator
import (
- "errors"
"fmt"
- "io"
"net/http"
"github.com/pinchtab/pinchtab/internal/authn"
@@ -39,11 +37,9 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
Browser string `json:"browser,omitempty"`
FallbackTargets []string `json:"fallbackTargets,omitempty"`
}
- if httpx.MayHaveBody(r) {
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
- return
- }
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
}
if err := validateStartInstanceSecurityPolicy(req.SecurityPolicy); err != nil {
httpx.Error(w, 400, err)
diff --git a/internal/orchestrator/handlers_tabs.go b/internal/orchestrator/handlers_tabs.go
index 5550cc74..81b32cf0 100644
--- a/internal/orchestrator/handlers_tabs.go
+++ b/internal/orchestrator/handlers_tabs.go
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
- "errors"
"fmt"
"io"
"net/http"
@@ -34,11 +33,9 @@ func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Requ
var req struct {
URL string `json:"url,omitempty"`
}
- if httpx.MayHaveBody(r) {
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
- return
- }
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
}
payload, err := json.Marshal(map[string]any{
diff --git a/internal/orchestrator/optional_body_sites_test.go b/internal/orchestrator/optional_body_sites_test.go
new file mode 100644
index 00000000..522061f7
--- /dev/null
+++ b/internal/orchestrator/optional_body_sites_test.go
@@ -0,0 +1,63 @@
+package orchestrator
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/httpx/httpxtest"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+)
+
+func TestEveryOptionalBodyOrchestratorSiteDecodesTheSameWay(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+ stubPortAvailability(t, func(int) bool { return true })
+
+ withProfile := func(t *testing.T) *Orchestrator {
+ baseDir := t.TempDir()
+ o := NewOrchestratorWithRunner(baseDir, &mockRunner{portAvail: true})
+ pm := profiles.NewProfileManager(baseDir)
+ if err := pm.CreateWithMeta("work", profiles.ProfileMeta{}); err != nil {
+ t.Fatal(err)
+ }
+ o.profiles = pm
+ return o
+ }
+ sites := []struct {
+ name string
+ target string
+ payload string
+ serve func(t *testing.T, w http.ResponseWriter, r *http.Request)
+ }{
+ {"launch by name", "/instances/launch", `{"mode":"headless"}`, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
+ withProfile(t).handleLaunchByName(w, r)
+ }},
+ {"start instance", "/instances/start", `{"profileId":"work"}`, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
+ withProfile(t).handleStartInstance(w, r)
+ }},
+ {"start profile by id", "/profiles/work/start", `{"headless":true}`, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
+ r.SetPathValue("id", "work")
+ withProfile(t).handleStartByID(w, r)
+ }},
+ {"instance tab open", "/instances/" + stubInstanceID + "/tabs/open", `{"url":"https://example.com"}`, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
+ o, _ := orchestratorOverStubChild(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"tabId":"t1"}`))
+ }))
+ r.SetPathValue("id", stubInstanceID)
+ o.handleInstanceTabOpen(w, r)
+ }},
+ }
+ for _, site := range sites {
+ for _, c := range httpxtest.OptionalBodyCases() {
+ t.Run(site.name+"/"+c.Name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+
+ site.serve(t, w, c.Request(http.MethodPost, site.target, site.payload))
+
+ c.Check(t, true, w)
+ })
+ }
+ }
+}
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
index 0acb0318..76eb7d21 100644
--- a/internal/profiles/handlers.go
+++ b/internal/profiles/handlers.go
@@ -3,7 +3,6 @@ package profiles
import (
"errors"
"fmt"
- "io"
"net/http"
"path/filepath"
"strconv"
@@ -268,7 +267,7 @@ func (pm *ProfileManager) handlePruneQuarantined(w http.ResponseWriter, r *http.
// a caller sending nothing is asking for.
func decodePruneRequest(w http.ResponseWriter, r *http.Request) (pruneQuarantinedRequest, error) {
var req pruneQuarantinedRequest
- if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
return req, err
}
if req.Profile == "" {
diff --git a/internal/profiles/optional_body_site_test.go b/internal/profiles/optional_body_site_test.go
new file mode 100644
index 00000000..85731165
--- /dev/null
+++ b/internal/profiles/optional_body_site_test.go
@@ -0,0 +1,23 @@
+package profiles
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/httpx/httpxtest"
+)
+
+func TestThePruneRequestDecodesAnOptionalBodyLikeEveryOtherSite(t *testing.T) {
+ for _, c := range httpxtest.OptionalBodyCases() {
+ t.Run(c.Name, func(t *testing.T) {
+ mux := http.NewServeMux()
+ NewProfileManager(t.TempDir()).RegisterHandlers(mux)
+ w := httptest.NewRecorder()
+
+ mux.ServeHTTP(w, c.Request(http.MethodPost, "/profiles/prune", `{"confirm":false}`))
+
+ c.Check(t, true, w)
+ })
+ }
+}