Skip to content

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

refactor(handlers): one owner for the /tabs/{id} path-id prelude (PIN-365)

Luigi Agostia1d5a5a1b142
diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.go
index 3c78293e..79b8f89b 100644
--- a/internal/handlers/cookies.go
+++ b/internal/handlers/cookies.go
@@ -146,9 +146,8 @@ func (h *Handlers) HandleClearCookies(w http.ResponseWriter, r *http.Request) {
//
// @Endpoint DELETE /tabs/{id}/cookies
func (h *Handlers) HandleTabClearCookies(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index 6de05d03..b1caddae 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -269,23 +269,13 @@ func (h *Handlers) writeDownloadResponse(w http.ResponseWriter, body []byte, mim
// @Endpoint GET /tabs/{id}/download
func (h *Handlers) HandleTabDownload(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
if _, _, err := h.tabContext(r, tabID); err != nil {
WriteTabContextError(w, err, 404)
return
}
-
- q := r.URL.Query()
- q.Set("tabId", tabID)
-
- req := r.Clone(r.Context())
- u := *r.URL
- u.RawQuery = q.Encode()
- req.URL = &u
-
- h.HandleDownload(w, req)
+ h.HandleDownload(w, cloneWithTabIDQuery(r, tabID))
}
diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.go
index 4cc2ed7b..8114e8de 100644
--- a/internal/handlers/handoff.go
+++ b/internal/handlers/handoff.go
@@ -128,9 +128,8 @@ func (h *Handlers) pauseTabForHandoff(tabID, reason, source string, timeout time
}
func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {
- tabID := strings.TrimSpace(r.PathValue("id"))
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
@@ -188,9 +187,8 @@ func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabResume(w http.ResponseWriter, r *http.Request) {
- tabID := strings.TrimSpace(r.PathValue("id"))
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
@@ -249,9 +247,8 @@ func (h *Handlers) HandleTabResume(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabHandoffStatus(w http.ResponseWriter, r *http.Request) {
- tabID := strings.TrimSpace(r.PathValue("id"))
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index 832c3989..d60f08b0 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -112,9 +112,8 @@ func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabMetrics(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("missing tab id"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
diff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.go
index 605f4882..c074d262 100644
--- a/internal/handlers/inspect.go
+++ b/internal/handlers/inspect.go
@@ -46,7 +46,7 @@ func (h *Handlers) HandleTitle(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabTitle(w http.ResponseWriter, r *http.Request) {
- h.forwardInspectTabRoute(w, r, h.HandleTitle)
+ h.withPathTabID(w, r, h.HandleTitle)
}
func (h *Handlers) HandleURL(w http.ResponseWriter, r *http.Request) {
@@ -54,7 +54,7 @@ func (h *Handlers) HandleURL(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabURL(w http.ResponseWriter, r *http.Request) {
- h.forwardInspectTabRoute(w, r, h.HandleURL)
+ h.withPathTabID(w, r, h.HandleURL)
}
func (h *Handlers) HandleHTML(w http.ResponseWriter, r *http.Request) {
@@ -62,7 +62,7 @@ func (h *Handlers) HandleHTML(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabHTML(w http.ResponseWriter, r *http.Request) {
- h.forwardInspectTabRoute(w, r, h.HandleHTML)
+ h.withPathTabID(w, r, h.HandleHTML)
}
func (h *Handlers) HandleStyles(w http.ResponseWriter, r *http.Request) {
@@ -70,7 +70,7 @@ func (h *Handlers) HandleStyles(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) HandleTabStyles(w http.ResponseWriter, r *http.Request) {
- h.forwardInspectTabRoute(w, r, h.HandleStyles)
+ h.withPathTabID(w, r, h.HandleStyles)
}
func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind inspectKind) {
@@ -297,18 +297,3 @@ func sortCSSMap(css map[string]any) map[string]any {
}
return out
}
-
-func (h *Handlers) forwardInspectTabRoute(w http.ResponseWriter, r *http.Request, next func(http.ResponseWriter, *http.Request)) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
- q := r.URL.Query()
- q.Set("tabId", tabID)
- req := r.Clone(r.Context())
- u := *r.URL
- u.RawQuery = q.Encode()
- req.URL = &u
- next(w, req)
-}
diff --git a/internal/handlers/inspect_lifecycle.go b/internal/handlers/inspect_lifecycle.go
index 573e2ba3..b937f6c5 100644
--- a/internal/handlers/inspect_lifecycle.go
+++ b/internal/handlers/inspect_lifecycle.go
@@ -8,21 +8,22 @@ import (
"github.com/pinchtab/pinchtab/internal/httpx"
)
-// withPathTabID maps the {id} path value into the tabId query param and calls
-// root with a cloned request; writes 400 when the path id is empty.
func (h *Handlers) withPathTabID(w http.ResponseWriter, r *http.Request, root http.HandlerFunc) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
+ root(w, cloneWithTabIDQuery(r, tabID))
+}
+
+func cloneWithTabIDQuery(r *http.Request, tabID string) *http.Request {
q := r.URL.Query()
q.Set("tabId", tabID)
req := r.Clone(r.Context())
u := *r.URL
u.RawQuery = q.Encode()
req.URL = &u
- root(w, req)
+ return req
}
// callOnResolvedElement resolves sel to a DOM node on tabID and runs jsFn on it,
diff --git a/internal/handlers/network.go b/internal/handlers/network.go
index e898da03..7c59c553 100644
--- a/internal/handlers/network.go
+++ b/internal/handlers/network.go
@@ -488,19 +488,14 @@ func (h *Handlers) HandleTabNetwork(w http.ResponseWriter, r *http.Request) {
//
// @Endpoint GET /tabs/{id}/network/{requestId}
func (h *Handlers) HandleTabNetworkByID(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- requestID := r.PathValue("requestId")
- if tabID == "" || requestID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id and request id required"))
+ if _, ok := requirePathTabID(w, r); !ok {
+ return
+ }
+ if r.PathValue("requestId") == "" {
+ httpx.Error(w, 400, fmt.Errorf("request id required"))
return
}
- q := r.URL.Query()
- q.Set("tabId", tabID)
- req := r.Clone(r.Context())
- u := *r.URL
- u.RawQuery = q.Encode()
- req.URL = &u
- h.HandleNetworkByID(w, req)
+ h.withPathTabID(w, r, h.HandleNetworkByID)
}
// HandleTabNetworkStream streams network entries for a tab identified by path ID.
diff --git a/internal/handlers/network_route.go b/internal/handlers/network_route.go
index c5af128e..32a66caa 100644
--- a/internal/handlers/network_route.go
+++ b/internal/handlers/network_route.go
@@ -64,9 +64,8 @@ func (h *Handlers) HandleNetworkRouteList(w http.ResponseWriter, r *http.Request
//
// @Endpoint POST /tabs/{id}/network/route
func (h *Handlers) HandleTabNetworkRoute(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
h.handleNetworkRouteFor(w, r, tabID)
@@ -76,9 +75,8 @@ func (h *Handlers) HandleTabNetworkRoute(w http.ResponseWriter, r *http.Request)
//
// @Endpoint DELETE /tabs/{id}/network/route
func (h *Handlers) HandleTabNetworkUnroute(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
h.handleNetworkUnrouteFor(w, r, tabID)
@@ -88,9 +86,8 @@ func (h *Handlers) HandleTabNetworkUnroute(w http.ResponseWriter, r *http.Reques
//
// @Endpoint GET /tabs/{id}/network/route
func (h *Handlers) HandleTabNetworkRouteList(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
return
}
h.handleNetworkRouteListFor(w, r, tabID)
diff --git a/internal/handlers/path_tab_id_test.go b/internal/handlers/path_tab_id_test.go
new file mode 100644
index 00000000..7eae59d3
--- /dev/null
+++ b/internal/handlers/path_tab_id_test.go
@@ -0,0 +1,132 @@
+package handlers
+
+import (
+ "bytes"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+func pathTabHandlers(t *testing.T) *Handlers {
+ t.Helper()
+ return New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: time.Second, AllowNetworkIntercept: true, AllowDownload: true, AllowCookies: true}, nil, nil, nil)
+}
+
+var pathTabRoutes = []struct {
+ name string
+ method string
+ call func(h *Handlers, w http.ResponseWriter, r *http.Request)
+}{
+ {"network route list", http.MethodGet, (*Handlers).HandleTabNetworkRouteList},
+ {"network route add", http.MethodPost, (*Handlers).HandleTabNetworkRoute},
+ {"network unroute", http.MethodDelete, (*Handlers).HandleTabNetworkUnroute},
+ {"network by id", http.MethodGet, (*Handlers).HandleTabNetworkByID},
+ {"handoff", http.MethodPost, (*Handlers).HandleTabHandoff},
+ {"resume", http.MethodPost, (*Handlers).HandleTabResume},
+ {"handoff status", http.MethodGet, (*Handlers).HandleTabHandoffStatus},
+ {"title", http.MethodGet, (*Handlers).HandleTabTitle},
+ {"url", http.MethodGet, (*Handlers).HandleTabURL},
+ {"html", http.MethodGet, (*Handlers).HandleTabHTML},
+ {"styles", http.MethodGet, (*Handlers).HandleTabStyles},
+ {"metrics", http.MethodGet, (*Handlers).HandleTabMetrics},
+ {"download", http.MethodGet, (*Handlers).HandleTabDownload},
+ {"pdf", http.MethodGet, (*Handlers).HandleTabPDF},
+ {"clear cookies", http.MethodDelete, (*Handlers).HandleTabClearCookies},
+ {"close", http.MethodPost, (*Handlers).HandleTabClose},
+}
+
+func TestEveryTabPathRouteRefusesAnEmptyOrBlankIDTheSameWay(t *testing.T) {
+ for _, route := range pathTabRoutes {
+ for _, id := range []string{"", " ", "\t"} {
+ t.Run(route.name+"/"+strings.TrimSpace(id)+"blank", func(t *testing.T) {
+ h := pathTabHandlers(t)
+ req := httptest.NewRequest(route.method, "/tabs/x/anything", nil)
+ req.SetPathValue("id", id)
+ req.SetPathValue("requestId", "req1")
+ w := httptest.NewRecorder()
+ route.call(h, w, req)
+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "tab id required") {
+ t.Fatalf("id %q: %d %s, want 400 tab id required", id, w.Code, w.Body.String())
+ }
+ })
+ }
+ }
+}
+
+func TestTabPDFRefusesABodyTabIDThatDisagreesWithThePath(t *testing.T) {
+ h := pathTabHandlers(t)
+ for _, tc := range []struct{ body, want string }{
+ {`{"tabId":"B"}`, "does not match path id"},
+ {`{"tabId":""}`, "invalid tabId"},
+ {`{"tabId":7}`, "invalid tabId"},
+ } {
+ req := httptest.NewRequest(http.MethodPost, "/tabs/A/pdf", bytes.NewReader([]byte(tc.body)))
+ req.SetPathValue("id", "A")
+ w := httptest.NewRecorder()
+ h.HandleTabPDF(w, req)
+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), tc.want) {
+ t.Fatalf("body %s: %d %s, want 400 %s", tc.body, w.Code, w.Body.String(), tc.want)
+ }
+ }
+}
+
+func TestThePathTabIDPreludeHasOneOwner(t *testing.T) {
+ fset := token.NewFileSet()
+ literalSites := map[string]int{}
+ pathValueSites := map[string]int{}
+ missingWording := 0
+ for _, name := range srccensus.Load(t, ".", handlersSourceFileFloor).Files() {
+ f, err := parser.ParseFile(fset, filepath.Join(".", name), nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.BasicLit:
+ if x.Kind == token.STRING && x.Value == `"tab id required"` {
+ literalSites[name]++
+ }
+ if x.Kind == token.STRING && strings.Contains(x.Value, "missing tab id") && name == "health_tabs.go" {
+ missingWording++
+ }
+ case *ast.CallExpr:
+ if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "PathValue" && len(x.Args) == 1 {
+ if lit, ok := x.Args[0].(*ast.BasicLit); ok && lit.Value == `"id"` {
+ pathValueSites[name]++
+ }
+ }
+ }
+ return true
+ })
+ }
+ total := 0
+ for _, n := range literalSites {
+ total += n
+ }
+ if total != 1 || literalSites["tab_body_adapter.go"] != 1 {
+ t.Errorf("\"tab id required\" is spelled at %v, want once in tab_body_adapter.go", literalSites)
+ }
+ allowed := map[string]bool{"tab_body_adapter.go": true, "find.go": true, "state_tab.go": true}
+ for file := range pathValueSites {
+ if !allowed[file] {
+ t.Errorf("%s reads r.PathValue(\"id\") itself; route it through requirePathTabID", file)
+ }
+ }
+ for _, file := range []string{"tab_body_adapter.go", "find.go", "state_tab.go"} {
+ if pathValueSites[file] == 0 {
+ t.Errorf("%s no longer reads the path id; update the census exclusions", file)
+ }
+ }
+ if missingWording != 0 {
+ t.Errorf("health_tabs.go still spells the drifted 'missing tab id' wording")
+ }
+}
diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.go
index d77003ea..9ba03761 100644
--- a/internal/handlers/pdf.go
+++ b/internal/handlers/pdf.go
@@ -237,13 +237,8 @@ func validatePDFTemplate(template string) error {
// @Endpoint GET /tabs/{id}/pdf
// @Endpoint POST /tabs/{id}/pdf
func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
q := r.URL.Query()
+ provided := ""
if r.Method == http.MethodPost {
var body map[string]any
if r.ContentLength > 0 {
@@ -251,6 +246,11 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
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
@@ -269,6 +269,10 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
}
}
}
+ tabID, ok := h.requirePathTabIDMatch(w, r, provided)
+ if !ok {
+ return
+ }
q.Set("tabId", tabID)
req := r.Clone(r.Context())
diff --git a/internal/handlers/tab_body_adapter.go b/internal/handlers/tab_body_adapter.go
index 8c3d7510..cc1d5872 100644
--- a/internal/handlers/tab_body_adapter.go
+++ b/internal/handlers/tab_body_adapter.go
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
+ "strings"
"github.com/pinchtab/pinchtab/internal/httpx"
)
@@ -29,12 +30,32 @@ func decodeJSONBody[T any](w http.ResponseWriter, r *http.Request) (T, bool) {
// means an error response was already written. For typed tab handlers that call
// an internal func directly (no JSON re-marshal) — the typed sibling of
// withPathTabIDBody.
-func (h *Handlers) requirePathTabIDMatch(w http.ResponseWriter, r *http.Request, bodyTabID string) (string, bool) {
- tabID := r.PathValue("id")
+func requirePathTabID(w http.ResponseWriter, r *http.Request) (string, bool) {
+ tabID := strings.TrimSpace(r.PathValue("id"))
if tabID == "" {
httpx.Error(w, 400, fmt.Errorf("tab id required"))
return "", false
}
+ return tabID, true
+}
+
+func bodyTabID(body map[string]any) (string, error) {
+ raw, present := body["tabId"]
+ if !present {
+ return "", nil
+ }
+ provided, ok := raw.(string)
+ if !ok || provided == "" {
+ return "", fmt.Errorf("invalid tabId")
+ }
+ return provided, nil
+}
+
+func (h *Handlers) requirePathTabIDMatch(w http.ResponseWriter, r *http.Request, bodyTabID string) (string, bool) {
+ tabID, ok := requirePathTabID(w, r)
+ if !ok {
+ return "", false
+ }
if bodyTabID != "" && bodyTabID != tabID {
httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
return "", false
@@ -58,27 +79,20 @@ func (h *Handlers) withPathTabIDBody(w http.ResponseWriter, r *http.Request, roo
// forwarded body (e.g. POST /tabs/{id}/navigate forcing newTab=false). A nil
// 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) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
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))
return
}
-
- if rawTabID, ok := body["tabId"]; ok {
- if provided, ok := rawTabID.(string); !ok || provided == "" {
- httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
- return
- } else if provided != tabID {
- httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
- return
- }
+ provided, err := bodyTabID(body)
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ tabID, ok := h.requirePathTabIDMatch(w, r, provided)
+ if !ok {
+ return
}
body["tabId"] = tabID
if mutate != nil {
diff --git a/internal/handlers/tab_lifecycle.go b/internal/handlers/tab_lifecycle.go
index cac2f3c3..536487f0 100644
--- a/internal/handlers/tab_lifecycle.go
+++ b/internal/handlers/tab_lifecycle.go
@@ -128,24 +128,18 @@ func (h *Handlers) createBlankTab(w http.ResponseWriter, r *http.Request, browse
// equivalent of POST /close and exists so orchestrator dashboard commands can
// use the common /tabs/{id}/... proxy path.
func (h *Handlers) HandleTabClose(w http.ResponseWriter, r *http.Request) {
- tabID := strings.TrimSpace(r.PathValue("id"))
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
- return
+ var req struct {
+ TabID string `json:"tabId"`
}
-
if r.Body != nil && r.Body != http.NoBody && r.ContentLength != 0 {
- 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))
return
}
- if req.TabID != "" && req.TabID != tabID {
- httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
- return
- }
+ }
+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)
+ if !ok {
+ return
}
h.closeTab(w, r, tabID)