Skip to content

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

security: gate storage mutations and harden state delete path

Yash Jadhave203c32bee5e
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 00c52dbd..0971d273 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -73,16 +73,24 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
"x-pinchtab-enabled": security["screencast"].Enabled,
}},
"/storage": map[string]any{
- "post": map[string]any{"summary": "Set a storage item"},
- "delete": map[string]any{"summary": "Delete storage items or clear storage"},
+ "get": map[string]any{
+ "summary": "Get localStorage/sessionStorage items (current origin only)",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
+ "post": map[string]any{
+ "summary": "Set a storage item",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
+ "delete": map[string]any{
+ "summary": "Delete storage items or clear storage",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
},
"/state/list": map[string]any{"get": map[string]any{"summary": "List saved state files"}},
// CapStateExport-gated endpoints
- "/storage (GET)": map[string]any{"get": map[string]any{
- "summary": "Get localStorage/sessionStorage items (current origin only)",
- "description": security["stateExport"].Message,
- "x-pinchtab-enabled": security["stateExport"].Enabled,
- }},
"/state/show": map[string]any{"get": map[string]any{
"summary": "Show state file details",
"description": security["stateExport"].Message,
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index a439d205..7bb7ebde 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -68,7 +68,8 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
Setting: "security.allowStateExport",
Message: httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"),
Paths: []string{
- "GET /storage", "GET /tabs/{id}/storage",
+ "GET /storage", "POST /storage", "DELETE /storage",
+ "GET /tabs/{id}/storage", "POST /tabs/{id}/storage", "DELETE /tabs/{id}/storage",
"GET /state/show", "POST /state/save",
"POST /state/load", "DELETE /state", "POST /state/clean",
},
diff --git a/internal/handlers/storage.go b/internal/handlers/storage.go
index 421c061b..d74a17ff 100644
--- a/internal/handlers/storage.go
+++ b/internal/handlers/storage.go
@@ -31,6 +31,16 @@ func (h *Handlers) HandleStorage(w http.ResponseWriter, r *http.Request) {
}
}
+func (h *Handlers) ensureStateExportEnabled(w http.ResponseWriter) bool {
+ if h.stateExportEnabled() {
+ return true
+ }
+ httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{
+ "setting": "security.allowStateExport",
+ })
+ return false
+}
+
// handleStorageGet retrieves localStorage and/or sessionStorage items.
// Gated behind CapStateExport: storage can contain auth tokens and session data.
//
@@ -38,10 +48,7 @@ func (h *Handlers) HandleStorage(w http.ResponseWriter, r *http.Request) {
// - type: "local", "session", or "" (both)
// - key: optional specific key to retrieve
func (h *Handlers) handleStorageGet(w http.ResponseWriter, r *http.Request) {
- if !h.stateExportEnabled() {
- httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{
- "setting": "security.allowStateExport",
- })
+ if !h.ensureStateExportEnabled(w) {
return
}
tabID := r.URL.Query().Get("tabId")
@@ -93,6 +100,10 @@ type storageSetRequest struct {
// handleStorageSet sets a single storage item.
func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
var req storageSetRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
@@ -166,6 +177,10 @@ func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {
// handleStorageDelete removes a storage item or clears storage.
// Supports type=local, type=session, or type=all (clears both).
func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
var req struct {
TabID string `json:"tabId"`
Key string `json:"key"`
diff --git a/internal/handlers/storage_test.go b/internal/handlers/storage_test.go
index 7681bb49..ac022e78 100644
--- a/internal/handlers/storage_test.go
+++ b/internal/handlers/storage_test.go
@@ -3,58 +3,144 @@ package handlers
import (
"bytes"
"context"
-
- "github.com/pinchtab/pinchtab/internal/config"
+ "encoding/json"
+ "net/http"
"net/http/httptest"
+ "strings"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
-func TestHandleStorageDelete_EmptyBody(t *testing.T) {
- // Setup handlers with a mock bridge
- m := &mockBridge{}
- h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
- h.evalJS = func(ctx context.Context, expr string, out *string) error {
- *out = `{"success":true,"origin":"http://example.com"}`
- return nil
+func TestHandleStorage_StateExportGateDisabled(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: false}, nil, nil, nil)
+
+ tests := []struct {
+ name string
+ method string
+ body string
+ }{
+ {name: "get blocked", method: http.MethodGet},
+ {name: "post blocked", method: http.MethodPost, body: `{"key":"k","value":"v","type":"local"}`},
+ {name: "delete blocked", method: http.MethodDelete, body: `{"type":"all"}`},
}
- // Create a DELETE request with NO body
- req := httptest.NewRequest("DELETE", "/storage", nil)
- w := httptest.NewRecorder()
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var req *httptest.ResponseRecorder
+ if tc.body != "" {
+ r := httptest.NewRequest(tc.method, "/storage", bytes.NewReader([]byte(tc.body)))
+ w := httptest.NewRecorder()
+ h.HandleStorage(w, r)
+ req = w
+ } else {
+ r := httptest.NewRequest(tc.method, "/storage", nil)
+ w := httptest.NewRecorder()
+ h.HandleStorage(w, r)
+ req = w
+ }
- // Direct call to handleStorageDelete (which is unexported but in same package)
- h.handleStorageDelete(w, req)
+ if req.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d: %s", req.Code, req.Body.String())
+ }
+ })
+ }
+}
- // It should NOT return 400 (EOF)
- // It might return 404 if the tab isn't found in the mock, but we want to see it pass the decode stage.
- if w.Code == 400 {
- t.Fatalf("expected handleStorageDelete to handle empty body, got 400: %s", w.Body.String())
+func TestHandleStorage_StateExportGateEnabled(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: true}, nil, nil, nil)
+ h.evalJS = func(ctx context.Context, expr string, out *string) error {
+ switch {
+ case bytes.Contains([]byte(expr), []byte("setItem")):
+ *out = `{"success":true,"origin":"http://example.com"}`
+ case bytes.Contains([]byte(expr), []byte("clear")) || bytes.Contains([]byte(expr), []byte("removeItem")):
+ *out = `{"success":true,"origin":"http://example.com"}`
+ default:
+ *out = `{"local":[],"session":[],"origin":"http://example.com"}`
+ }
+ return nil
}
- // If it got past decode, it should try to find a tab.
- // Our mockBridge return a context for any tabID, so it should proceed to domain check.
- // We expect 200 if the mock allows it.
- if w.Code != 200 {
- t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
+ tests := []struct {
+ name string
+ method string
+ body string
+ }{
+ {name: "get allowed", method: http.MethodGet},
+ {name: "post allowed", method: http.MethodPost, body: `{"key":"k","value":"v","type":"local"}`},
+ {name: "delete allowed", method: http.MethodDelete, body: `{"type":"all"}`},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var r *http.Request
+ if tc.body != "" {
+ r = httptest.NewRequest(tc.method, "/storage", bytes.NewReader([]byte(tc.body)))
+ } else {
+ r = httptest.NewRequest(tc.method, "/storage", nil)
+ }
+ w := httptest.NewRecorder()
+ h.HandleStorage(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ })
}
}
-func TestHandleStorageDelete_WithBody(t *testing.T) {
- m := &mockBridge{}
- h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
- h.evalJS = func(ctx context.Context, expr string, out *string) error {
- *out = `{"success":true,"origin":"http://example.com"}`
- return nil
+func TestEndpointSecurityState_IncludesStorageMutations(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: false}, nil, nil, nil)
+ state := h.endpointSecurityStates()["stateExport"]
+
+ want := []string{"GET /storage", "POST /storage", "DELETE /storage"}
+ for _, p := range want {
+ found := false
+ for _, have := range state.Paths {
+ if have == p {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected %q in stateExport paths, got %v", p, state.Paths)
+ }
}
+}
- // Valid body
- body := `{"type": "local", "key": "test"}`
- req := httptest.NewRequest("DELETE", "/storage", bytes.NewReader([]byte(body)))
+func TestOpenAPI_StorageModeledOnceWithMethodMetadata(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: false}, nil, nil, nil)
w := httptest.NewRecorder()
+ r := httptest.NewRequest(http.MethodGet, "/openapi.json", nil)
- h.handleStorageDelete(w, req)
+ h.HandleOpenAPI(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+
+ if strings.Contains(w.Body.String(), "/storage (GET)") {
+ t.Fatalf("openapi should not expose synthetic /storage (GET) path")
+ }
- if w.Code != 200 {
- t.Fatalf("expected handleStorageDelete to handle valid body and return 200, got %d: %s", w.Code, w.Body.String())
+ var doc map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
+ t.Fatalf("unmarshal openapi: %v", err)
+ }
+ paths, ok := doc["paths"].(map[string]any)
+ if !ok {
+ t.Fatalf("paths missing or invalid")
+ }
+ storagePath, ok := paths["/storage"].(map[string]any)
+ if !ok {
+ t.Fatalf("/storage path missing")
+ }
+ for _, method := range []string{"get", "post", "delete"} {
+ meta, ok := storagePath[method].(map[string]any)
+ if !ok {
+ t.Fatalf("/storage.%s missing", method)
+ }
+ if _, ok := meta["x-pinchtab-enabled"]; !ok {
+ t.Fatalf("/storage.%s missing x-pinchtab-enabled", method)
+ }
}
}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 1bb21afa..b41d5e64 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -109,10 +109,9 @@ var coreEndpoints = []Endpoint{
{"POST", "/cache/clear", "Clear browser cache", CapNone, false},
{"GET", "/cache/status", "Cache status", CapNone, false},
- // Storage — GET reads sensitive client-side state and is gated alongside state export.
- // POST/DELETE mutate state and are gated to prevent unauthorized writes.
- {"POST", "/storage", "Set storage item", CapNone, true},
- {"DELETE", "/storage", "Delete storage items", CapNone, true},
+ // Storage operations are gated under stateExport because they access/mutate sensitive client-side state.
+ {"POST", "/storage", "Set storage item", CapStateExport, true},
+ {"DELETE", "/storage", "Delete storage items", CapStateExport, true},
// State management — list is read-only summary, ungated.
{"GET", "/state/list", "List saved states", CapNone, false},
diff --git a/internal/state/state.go b/internal/state/state.go
index d6df6b2f..63dd6158 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -238,9 +238,13 @@ func FindByPrefix(stateDir, prefix string) ([]StateEntry, error) {
func Delete(stateDir, name string) error {
dir := SessionsDir(stateDir)
base := sanitizeFilename(name)
+ cleanDir := filepath.Clean(dir) + string(os.PathSeparator)
// Try encrypted extension first.
for _, ext := range []string{".json.enc", ".json"} {
- path := filepath.Join(dir, base+ext)
+ path := filepath.Clean(filepath.Join(dir, base+ext))
+ if !strings.HasPrefix(path, cleanDir) {
+ return fmt.Errorf("resolved path escapes sessions dir")
+ }
if err := os.Remove(path); err == nil {
return nil
} else if !os.IsNotExist(err) {