High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor(handlers): fold the five tab-scoped decode-and-reconcile prologues onto the package's own helpers
Luigi Agosti16369f537371
diff --git a/internal/handlers/credentials.go b/internal/handlers/credentials.goindex 149bbf7a..32a7c664 100644--- a/internal/handlers/credentials.go+++ b/internal/handlers/credentials.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""log/slog""net/http"@@ -101,9 +100,8 @@ type credentialsRequest struct {// HandleSetCredentials sets HTTP auth credentials via the CDP Fetch domain.// POST /emulation/credentialsfunc (h *Handlers) HandleSetCredentials(w http.ResponseWriter, r *http.Request) {- var req credentialsRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[credentialsRequest](w, r)+ if !ok {return}@@ -113,20 +111,12 @@ func (h *Handlers) HandleSetCredentials(w http.ResponseWriter, r *http.Request)// HandleTabSetCredentials sets HTTP auth credentials for a specific tab.// POST /tabs/{id}/emulation/credentialsfunc (h *Handlers) HandleTabSetCredentials(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("missing tab ID"))- return- }-- var req credentialsRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[credentialsRequest](w, r)+ if !ok {return}-- if req.TabID != "" && req.TabID != tabID {- httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)+ if !ok {return}req.TabID = tabIDdiff --git a/internal/handlers/geolocation.go b/internal/handlers/geolocation.goindex a096d45d..c3366265 100644--- a/internal/handlers/geolocation.go+++ b/internal/handlers/geolocation.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""net/http""time"@@ -21,9 +20,8 @@ type geolocationRequest struct {// HandleSetGeolocation sets the browser geolocation via CDP emulation.// POST /emulation/geolocationfunc (h *Handlers) HandleSetGeolocation(w http.ResponseWriter, r *http.Request) {- var req geolocationRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[geolocationRequest](w, r)+ if !ok {return}@@ -33,20 +31,12 @@ func (h *Handlers) HandleSetGeolocation(w http.ResponseWriter, r *http.Request)// HandleTabSetGeolocation sets the browser geolocation for a specific tab.// POST /tabs/{id}/emulation/geolocationfunc (h *Handlers) HandleTabSetGeolocation(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("missing tab ID"))- return- }-- var req geolocationRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[geolocationRequest](w, r)+ if !ok {return}-- if req.TabID != "" && req.TabID != tabID {- httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)+ if !ok {return}req.TabID = tabIDdiff --git a/internal/handlers/headers.go b/internal/handlers/headers.goindex 9fee730f..8099a8db 100644--- a/internal/handlers/headers.go+++ b/internal/handlers/headers.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""net/http""time"@@ -19,9 +18,8 @@ type headersRequest struct {// HandleSetHeaders sets extra HTTP headers via CDP.// POST /emulation/headersfunc (h *Handlers) HandleSetHeaders(w http.ResponseWriter, r *http.Request) {- var req headersRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[headersRequest](w, r)+ if !ok {return}@@ -31,12 +29,10 @@ func (h *Handlers) HandleSetHeaders(w http.ResponseWriter, r *http.Request) {// HandleTabSetHeaders sets extra HTTP headers for a specific tab.// POST /tabs/{id}/emulation/headersfunc (h *Handlers) HandleTabSetHeaders(w http.ResponseWriter, r *http.Request) {- var req headersRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[headersRequest](w, r)+ if !ok {return}-tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)if !ok {returndiff --git a/internal/handlers/media.go b/internal/handlers/media.goindex 9dcb018e..24cc71b2 100644--- a/internal/handlers/media.go+++ b/internal/handlers/media.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""net/http""time"@@ -20,9 +19,8 @@ type mediaRequest struct {// HandleSetMedia emulates a CSS media feature via CDP.// POST /emulation/mediafunc (h *Handlers) HandleSetMedia(w http.ResponseWriter, r *http.Request) {- var req mediaRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[mediaRequest](w, r)+ if !ok {return}@@ -32,20 +30,12 @@ func (h *Handlers) HandleSetMedia(w http.ResponseWriter, r *http.Request) {// HandleTabSetMedia emulates a CSS media feature for a specific tab.// POST /tabs/{id}/emulation/mediafunc (h *Handlers) HandleTabSetMedia(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("missing tab ID"))- return- }-- var req mediaRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[mediaRequest](w, r)+ if !ok {return}-- if req.TabID != "" && req.TabID != tabID {- httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)+ if !ok {return}req.TabID = tabIDdiff --git a/internal/handlers/offline.go b/internal/handlers/offline.goindex 4e9de7b8..d190732d 100644--- a/internal/handlers/offline.go+++ b/internal/handlers/offline.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""net/http""time"@@ -23,9 +22,8 @@ type offlineRequest struct {// HandleSetOffline enables or disables network offline emulation via CDP.// POST /emulation/offlinefunc (h *Handlers) HandleSetOffline(w http.ResponseWriter, r *http.Request) {- var req offlineRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[offlineRequest](w, r)+ if !ok {return}@@ -35,20 +33,12 @@ func (h *Handlers) HandleSetOffline(w http.ResponseWriter, r *http.Request) {// HandleTabSetOffline enables or disables network offline emulation for a specific tab.// POST /tabs/{id}/emulation/offlinefunc (h *Handlers) HandleTabSetOffline(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("missing tab ID"))- return- }-- var req offlineRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[offlineRequest](w, r)+ if !ok {return}-- if req.TabID != "" && req.TabID != tabID {- httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)+ if !ok {return}req.TabID = tabIDdiff --git a/internal/handlers/tab_body_adapter.go b/internal/handlers/tab_body_adapter.goindex a6c62ab9..8c3d7510 100644--- a/internal/handlers/tab_body_adapter.go+++ b/internal/handlers/tab_body_adapter.go@@ -11,6 +11,19 @@ import ("github.com/pinchtab/pinchtab/internal/httpx")+// decodeJSONBody decodes the request body into T under the shared maxBodySize+// cap. ok=false means the 400 has already been written. An empty body is a+// decode error here, not an empty T — the handlers that use it all require at+// least one field.+func decodeJSONBody[T any](w http.ResponseWriter, r *http.Request) (T, bool) {+ var req T+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return req, false+ }+ return req, true+}+// requirePathTabIDMatch validates the {id} path value (required) against an// optional body-provided tabId, returning the resolved path tabID. ok=false// means an error response was already written. For typed tab handlers that calldiff --git a/internal/handlers/tab_request_test.go b/internal/handlers/tab_request_test.gonew file mode 100644index 00000000..f12a9c85--- /dev/null+++ b/internal/handlers/tab_request_test.go@@ -0,0 +1,144 @@+package handlers++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++// tabScopedFamily is every /tabs/{id}/... handler that decodes a typed body and+// reconciles it against the path id through decodeJSONBody + requirePathTabIDMatch.+// The prologue lives in one place now, so the point of walking all six is that a+// handler which stops routing through it fails here rather than drifting quietly.+var tabScopedFamily = []struct {+ name string+ handler func(*Handlers) http.HandlerFunc+ validBody string+}{+ {"emulation/viewport", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetViewport }, `{"width":800,"height":600}`},+ {"emulation/geolocation", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetGeolocation }, `{"latitude":1,"longitude":2}`},+ {"emulation/media", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetMedia }, `{"feature":"prefers-color-scheme","value":"dark"}`},+ {"emulation/offline", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetOffline }, `{"offline":true}`},+ {"emulation/credentials", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetCredentials }, `{"username":"u","password":"p"}`},+ {"emulation/headers", func(h *Handlers) http.HandlerFunc { return h.HandleTabSetHeaders }, `{"headers":{"X-Probe":"1"}}`},+}++func driveTabScoped(t *testing.T, handler http.HandlerFunc, pathID, body string) (int, string) {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/probe", strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ if pathID != "" {+ req.SetPathValue("id", pathID)+ }+ w := httptest.NewRecorder()+ handler(w, req)++ var resp struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(w.Body.Bytes(), &resp)+ return w.Code, resp.Error+}++func TestTabScopedPrologueRejections(t *testing.T) {+ oversized := `{"tabId":"` + strings.Repeat("x", maxBodySize+1) + `"}`++ cases := []struct {+ name string+ pathID string+ body func(valid string) string+ wantError string+ }{+ {+ name: "missing tab id",+ pathID: "",+ body: func(valid string) string { return valid },+ wantError: "tab id required",+ },+ {+ name: "malformed body",+ pathID: "tab_abc",+ body: func(string) string { return `{"tabId":` },+ wantError: "decode: unexpected EOF",+ },+ {+ name: "oversized body",+ pathID: "tab_abc",+ body: func(string) string { return oversized },+ wantError: "decode: http: request body too large",+ },+ {+ name: "body tabId disagrees with the path",+ pathID: "tab_abc",+ body: func(string) string { return `{"tabId":"tab_other"}` },+ wantError: "tabId in body does not match path id",+ },+ }++ for _, ep := range tabScopedFamily {+ for _, tc := range cases {+ t.Run(ep.name+"/"+tc.name, func(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ status, gotError := driveTabScoped(t, ep.handler(h), tc.pathID, tc.body(ep.validBody))++ if status != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400 (error=%q)", status, gotError)+ }+ if gotError != tc.wantError {+ t.Fatalf("error = %q, want %q", gotError, tc.wantError)+ }+ })+ }+ }++ if len(tabScopedFamily) == 0 || len(cases) == 0 {+ t.Fatal("the family or the case table is empty, so this test proves nothing")+ }+}++// TestTabScopedPrologueDecodesBeforeCheckingThePathID pins the one ordering the+// fold changed: the body is decoded first, so a request that is both malformed+// and missing its path id reports the decode error. No client can reach it —+// ServeMux redirects /tabs//... rather than matching {id} to an empty segment,+// which TestEmptyPathSegmentNeverReachesATabHandler holds — but the direct-call+// precedence is now uniform across the family instead of split two ways.+func TestTabScopedPrologueDecodesBeforeCheckingThePathID(t *testing.T) {+ for _, ep := range tabScopedFamily {+ t.Run(ep.name, func(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ status, gotError := driveTabScoped(t, ep.handler(h), "", `{"tabId":`)++ if status != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400 (error=%q)", status, gotError)+ }+ if gotError != "decode: unexpected EOF" {+ t.Fatalf("error = %q, want the decode error to win over the missing path id", gotError)+ }+ })+ }+}++// TestEmptyPathSegmentNeverReachesATabHandler is what makes the reordering above+// safe to reason about: the "missing tab id" branch is unreachable over HTTP, so+// its position in the prologue cannot change any response a client can observe.+func TestEmptyPathSegmentNeverReachesATabHandler(t *testing.T) {+ reached := false+ mux := http.NewServeMux()+ mux.HandleFunc("POST /tabs/{id}/emulation/viewport", func(w http.ResponseWriter, r *http.Request) {+ reached = true+ })++ w := httptest.NewRecorder()+ mux.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/tabs//emulation/viewport", strings.NewReader("{}")))++ if reached {+ t.Fatal("an empty {id} segment reached the handler, so the missing-tab-id branch is client-reachable after all and its ordering is observable")+ }+ if w.Code != http.StatusTemporaryRedirect {+ t.Fatalf("status = %d, want 307; ServeMux is expected to redirect the empty segment rather than match it", w.Code)+ }+}diff --git a/internal/handlers/viewport.go b/internal/handlers/viewport.goindex 4dea2c28..ac71a808 100644--- a/internal/handlers/viewport.go+++ b/internal/handlers/viewport.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "encoding/json""fmt""net/http""time"@@ -23,9 +22,8 @@ type viewportRequest struct {// HandleSetViewport sets the browser viewport dimensions via CDP emulation.// POST /emulation/viewportfunc (h *Handlers) HandleSetViewport(w http.ResponseWriter, r *http.Request) {- var req viewportRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[viewportRequest](w, r)+ if !ok {return}@@ -35,20 +33,12 @@ func (h *Handlers) HandleSetViewport(w http.ResponseWriter, r *http.Request) {// HandleTabSetViewport sets the browser viewport dimensions for a specific tab.// POST /tabs/{id}/emulation/viewportfunc (h *Handlers) HandleTabSetViewport(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("missing tab ID"))- return- }-- var req viewportRequest- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ req, ok := decodeJSONBody[viewportRequest](w, r)+ if !ok {return}-- if req.TabID != "" && req.TabID != tabID {- httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ tabID, ok := h.requirePathTabIDMatch(w, r, req.TabID)+ if !ok {return}req.TabID = tabID