Skip to content

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

fix(security): derive the sensitive-endpoint reporter from the routes capability table so allowStateExport is reported, and withhold cookie values from GET /state and /state/show without allowCookies, answering the count instead (PIN-299)

Luigi Agosti59e5d2839834
diff --git a/internal/cli/report/security_state_export_test.go b/internal/cli/report/security_state_export_test.go
new file mode 100644
index 00000000..90715f0f
--- /dev/null
+++ b/internal/cli/report/security_state_export_test.go
@@ -0,0 +1,34 @@
+package report
+
+import (
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func sensitiveEndpointsCheck(t *testing.T, cfg *config.RuntimeConfig) SecurityPostureCheck {
+ t.Helper()
+ for _, check := range AssessSecurityPosture(cfg).Checks {
+ if check.ID == "sensitive_endpoints_disabled" {
+ return check
+ }
+ }
+ t.Fatal("no sensitive_endpoints_disabled check in the posture")
+ return SecurityPostureCheck{}
+}
+
+// Two servers identical but for one flag: allowStateExport alone used to pass the
+// sensitive-endpoints check and print "disabled" while ten state routes were live.
+func TestAllowStateExportAloneFailsTheSensitiveEndpointsCheckLikeAllowCookiesDoes(t *testing.T) {
+ cookies := sensitiveEndpointsCheck(t, &config.RuntimeConfig{AllowCookies: true})
+ stateExport := sensitiveEndpointsCheck(t, &config.RuntimeConfig{AllowStateExport: true})
+ if cookies.Passed || cookies.Detail != "cookies" {
+ t.Errorf("allowCookies alone: passed=%v detail=%q", cookies.Passed, cookies.Detail)
+ }
+ if stateExport.Passed || stateExport.Detail != "stateExport" {
+ t.Errorf("allowStateExport alone: passed=%v detail=%q, want the check failed naming stateExport", stateExport.Passed, stateExport.Detail)
+ }
+ if quiet := sensitiveEndpointsCheck(t, &config.RuntimeConfig{}); !quiet.Passed || quiet.Detail != "disabled" {
+ t.Errorf("nothing enabled: passed=%v detail=%q", quiet.Passed, quiet.Detail)
+ }
+}
diff --git a/internal/config/config_methods.go b/internal/config/config_methods.go
index fdfede9a..41099af5 100644
--- a/internal/config/config_methods.go
+++ b/internal/config/config_methods.go
@@ -2,7 +2,10 @@ package config
import (
"fmt"
+ "github.com/pinchtab/pinchtab/internal/routes"
"path/filepath"
+ "reflect"
+ "strings"
)
// EnabledSensitiveEndpoints returns the names of sensitive endpoint families
@@ -11,32 +14,33 @@ func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
if cfg == nil {
return nil
}
-
- enabled := make([]string, 0, 7)
- if cfg.AllowEvaluate {
- enabled = append(enabled, "evaluate")
- }
- if cfg.AllowMacro {
- enabled = append(enabled, "macro")
- }
- if cfg.AllowScreencast {
- enabled = append(enabled, "screencast")
- }
- if cfg.AllowDownload {
- enabled = append(enabled, "download")
- }
- if cfg.AllowCookies {
- enabled = append(enabled, "cookies")
- }
- if cfg.AllowUpload {
- enabled = append(enabled, "upload")
- }
- if cfg.AllowNetworkIntercept {
- enabled = append(enabled, "networkIntercept")
+ caps := routes.Capabilities()
+ enabled := make([]string, 0, len(caps))
+ for _, cap := range caps {
+ if cfg.CapabilityEnabled(cap) {
+ meta, _ := routes.Meta(cap)
+ enabled = append(enabled, meta.Label)
+ }
}
return enabled
}
+// CapabilityEnabled reads the flag a capability's declared setting names, so the
+// routes table is the only place a capability is listed.
+func (cfg *RuntimeConfig) CapabilityEnabled(cap routes.Capability) bool {
+ meta, ok := routes.Meta(cap)
+ if !ok || cfg == nil {
+ return false
+ }
+ field := reflect.ValueOf(cfg).Elem().FieldByName(capabilityFlagField(meta.Setting))
+ return field.IsValid() && field.Kind() == reflect.Bool && field.Bool()
+}
+
+func capabilityFlagField(setting string) string {
+ name := strings.TrimPrefix(setting, "security.")
+ return strings.ToUpper(name[:1]) + name[1:]
+}
+
// ActivityStateDir returns the directory root used for activity log storage.
// When unset, activity logs live under the main server state directory.
func (cfg *RuntimeConfig) ActivityStateDir() string {
diff --git a/internal/config/enabled_sensitive_endpoints_test.go b/internal/config/enabled_sensitive_endpoints_test.go
new file mode 100644
index 00000000..82f61dc5
--- /dev/null
+++ b/internal/config/enabled_sensitive_endpoints_test.go
@@ -0,0 +1,70 @@
+package config
+
+import (
+ "os"
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/routes"
+)
+
+func withCapability(t *testing.T, cap routes.Capability) *RuntimeConfig {
+ t.Helper()
+ meta, ok := routes.Meta(cap)
+ if !ok {
+ t.Fatalf("no metadata for %q", cap)
+ }
+ cfg := &RuntimeConfig{}
+ field := reflect.ValueOf(cfg).Elem().FieldByName(capabilityFlagField(meta.Setting))
+ if !field.IsValid() || field.Kind() != reflect.Bool {
+ t.Fatalf("%s names no bool flag on RuntimeConfig; the reporter cannot see %q", meta.Setting, cap)
+ }
+ field.SetBool(true)
+ return cfg
+}
+
+// The reporter used to be an if-chain over seven flags while the table held eight,
+// so the eighth family reported as disabled while ten of its routes were live. Driven
+// from the table: a capability added there reaches the reporter or this reds.
+func TestEveryCapabilityInTheTableIsReportedWhenItsFlagIsOn(t *testing.T) {
+ caps := routes.Capabilities()
+ if len(caps) < 8 {
+ t.Fatalf("table lists %d capabilities; the reporter guarded eight and this walk would prove less", len(caps))
+ }
+ for _, cap := range caps {
+ meta, _ := routes.Meta(cap)
+ got := withCapability(t, cap).EnabledSensitiveEndpoints()
+ if len(got) != 1 || got[0] != meta.Label {
+ t.Errorf("%s on reports %v, want exactly [%s]", meta.Setting, got, meta.Label)
+ }
+ }
+ if got := (&RuntimeConfig{}).EnabledSensitiveEndpoints(); len(got) != 0 {
+ t.Errorf("all flags off reports %v, want nothing", got)
+ }
+}
+
+func TestAllowStateExportAloneIsNotReportedAsSensitiveEndpointsDisabled(t *testing.T) {
+ cookiesOnly := (&RuntimeConfig{AllowCookies: true}).EnabledSensitiveEndpoints()
+ stateOnly := (&RuntimeConfig{AllowStateExport: true}).EnabledSensitiveEndpoints()
+ if len(cookiesOnly) != 1 || cookiesOnly[0] != "cookies" {
+ t.Errorf("allowCookies alone reports %v", cookiesOnly)
+ }
+ if len(stateOnly) != 1 || stateOnly[0] != "stateExport" {
+ t.Errorf("allowStateExport alone reports %v, want [stateExport]: ten live routes read as disabled", stateOnly)
+ }
+}
+
+func TestTheReporterRestatesNoCapabilityCount(t *testing.T) {
+ src, err := os.ReadFile("config_methods.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m := regexp.MustCompile(`make\(\[\]string, 0, \d+\)`).Find(src); m != nil {
+ t.Errorf("config_methods.go restates the capability count: %s", m)
+ }
+ if strings.Count(string(src), "cfg.Allow") > 0 {
+ t.Errorf("config_methods.go reads a capability flag by name; the routes table is the only list")
+ }
+}
diff --git a/internal/handlers/state.go b/internal/handlers/state.go
index b8696a04..59793e76 100644
--- a/internal/handlers/state.go
+++ b/internal/handlers/state.go
@@ -54,7 +54,7 @@ func (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 500, fmt.Errorf("load state: %w", err))
return
}
- httpx.JSON(w, 200, sf)
+ httpx.JSON(w, 200, h.stateFileInScope(sf))
}
// stateEncryptionKey resolves the key the state files are encrypted with. The
diff --git a/internal/handlers/state_capture.go b/internal/handlers/state_capture.go
index 99c9b197..40712c87 100644
--- a/internal/handlers/state_capture.go
+++ b/internal/handlers/state_capture.go
@@ -19,7 +19,7 @@ type currentBrowserStateResponse struct {
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Origins []string `json:"origins"`
- Cookies []state.Cookie `json:"cookies"`
+ Cookies any `json:"cookies"`
Storage map[string]state.OriginStorage `json:"storage"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
@@ -54,12 +54,38 @@ func (h *Handlers) HandleStateCurrent(w http.ResponseWriter, r *http.Request) {
URL: captured.url,
Title: captured.title,
Origins: captured.file.Origins,
- Cookies: captured.file.Cookies,
+ Cookies: h.cookiesInScope(captured.file.Cookies),
Storage: captured.file.Storage,
Metadata: captured.file.Metadata,
})
}
+// cookiesInScope is the one place cookie VALUES leave a state response: they need
+// the cookies capability whatever route asked, and without it the count stands in,
+// the same vocabulary /state/save answers with.
+func (h *Handlers) cookiesInScope(cookies []state.Cookie) any {
+ if h.Config != nil && h.Config.AllowCookies {
+ return cookies
+ }
+ return len(cookies)
+}
+
+func (h *Handlers) stateFileInScope(sf *state.StateFile) any {
+ if h.Config != nil && h.Config.AllowCookies {
+ return sf
+ }
+ raw, err := json.Marshal(sf)
+ if err != nil {
+ return sf
+ }
+ var withheld map[string]any
+ if err := json.Unmarshal(raw, &withheld); err != nil {
+ return sf
+ }
+ withheld["cookies"] = len(sf.Cookies)
+ return withheld
+}
+
// HandleStateLoad reads a state file and restores cookies and storage.
func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
if !h.ensureStateExportEnabled(w) {
diff --git a/internal/handlers/state_cookie_scope_test.go b/internal/handlers/state_cookie_scope_test.go
new file mode 100644
index 00000000..f2568eae
--- /dev/null
+++ b/internal/handlers/state_cookie_scope_test.go
@@ -0,0 +1,121 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/state"
+)
+
+const secretCookieValue = "SUPERSECRET-SESSION-TOKEN"
+
+type secretJarBridge struct{ mockBridge }
+
+func newSecretJarBridge() *secretJarBridge {
+ b := &secretJarBridge{}
+ b.evaluateFn = func(_ string, result any) error {
+ if p, ok := result.(*string); ok {
+ *p = "{}"
+ }
+ return nil
+ }
+ return b
+}
+
+func (secretJarBridge) GetRawCookies(context.Context) ([]bridge.RawCookie, error) {
+ return []bridge.RawCookie{{Name: "session", Value: secretCookieValue, Domain: "localhost", Path: "/"}}, nil
+}
+
+func stateResponse(t *testing.T, h *Handlers, serve func(*Handlers, *httptest.ResponseRecorder)) (string, map[string]any) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ serve(h, w)
+ if w.Code != 200 {
+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ return w.Body.String(), body
+}
+
+func serveStateCurrent(h *Handlers, w *httptest.ResponseRecorder) {
+ h.HandleStateCurrent(w, httptest.NewRequest("GET", "/state?tabId=tab1", nil))
+}
+
+func serveStateShow(h *Handlers, w *httptest.ResponseRecorder) {
+ h.HandleStateShow(w, httptest.NewRequest("GET", "/state/show?name=saved", nil))
+}
+
+func savedStateDir(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ if _, err := state.Save(dir, &state.StateFile{
+ Name: "saved",
+ Cookies: []state.Cookie{{Name: "session", Value: secretCookieValue, Domain: "localhost", Path: "/"}},
+ }, ""); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+// allowStateExport alone used to hand back the full cookie jar that allowCookies
+// refuses one route over. Cookie VALUES need the cookies capability whatever route
+// answers; without it the count stands in and the route still answers 200.
+func TestStateReadBackWithholdsCookieValuesWithoutTheCookiesCapability(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ serve func(*Handlers, *httptest.ResponseRecorder)
+ }{
+ {"GET /state", serveStateCurrent},
+ {"GET /state/show", serveStateShow},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := savedStateDir(t)
+ withheld := New(newSecretJarBridge(), &config.RuntimeConfig{AllowStateExport: true, StateDir: dir}, nil, nil, nil)
+ raw, body := stateResponse(t, withheld, tc.serve)
+ if strings.Contains(raw, secretCookieValue) {
+ t.Errorf("the secret cookie value reached an allowStateExport-only caller: %s", raw)
+ }
+ if body["cookies"] != float64(1) {
+ t.Errorf("cookies = %v, want the count 1 standing in for the values", body["cookies"])
+ }
+
+ full := New(newSecretJarBridge(), &config.RuntimeConfig{AllowStateExport: true, AllowCookies: true, StateDir: dir}, nil, nil, nil)
+ raw, body = stateResponse(t, full, tc.serve)
+ jar, ok := body["cookies"].([]any)
+ if !ok || len(jar) != 1 || !strings.Contains(raw, secretCookieValue) {
+ t.Errorf("with both capabilities cookies = %v, want the full values", body["cookies"])
+ }
+ })
+ }
+}
+
+func TestSaveAndLoadRoundTripWithoutTheCookiesCapability(t *testing.T) {
+ dir := t.TempDir()
+ h := New(newSecretJarBridge(), &config.RuntimeConfig{AllowStateExport: true, StateDir: dir}, nil, nil, nil)
+
+ raw, saved := stateResponse(t, h, func(h *Handlers, w *httptest.ResponseRecorder) {
+ h.HandleStateSave(w, httptest.NewRequest("POST", "/state/save", strings.NewReader(`{"name":"trip","tabId":"tab1"}`)))
+ })
+ if saved["cookies"] != float64(1) || strings.Contains(raw, secretCookieValue) {
+ t.Fatalf("save answered %s, want a count and no value", raw)
+ }
+ sf, err := state.Load(state.ResolvePath(dir, "trip"), "")
+ if err != nil || len(sf.Cookies) != 1 || sf.Cookies[0].Value != secretCookieValue {
+ t.Fatalf("the saved file does not hold the cookie server-side: %+v %v", sf, err)
+ }
+
+ raw, loaded := stateResponse(t, h, func(h *Handlers, w *httptest.ResponseRecorder) {
+ h.HandleStateLoad(w, httptest.NewRequest("POST", "/state/load", strings.NewReader(`{"name":"trip","tabId":"tab1"}`)))
+ })
+ if loaded["cookiesRestored"] != float64(1) || strings.Contains(raw, secretCookieValue) {
+ t.Fatalf("load answered %s, want one cookie restored and no value", raw)
+ }
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index b3f79710..0054a12f 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -4,6 +4,8 @@
// the generated /openapi.json response.
package routes
+import "sort"
+
import "fmt"
// Capability gates an endpoint behind a security config flag.
@@ -45,6 +47,17 @@ var capabilityMeta = map[Capability]CapabilityMeta{
CapNetworkIntercept: {CapNetworkIntercept, "networkIntercept", "security.allowNetworkIntercept", "network_intercept_disabled"},
}
+// Capabilities lists every gated capability, ordered by label so a reporter
+// derived from the table answers deterministically.
+func Capabilities() []Capability {
+ caps := make([]Capability, 0, len(capabilityMeta))
+ for cap := range capabilityMeta {
+ caps = append(caps, cap)
+ }
+ sort.Slice(caps, func(i, j int) bool { return capabilityMeta[caps[i]].Label < capabilityMeta[caps[j]].Label })
+ return caps
+}
+
// Meta returns the gate metadata for a capability. The second result is false
// for CapNone or any capability without registered metadata.
func Meta(cap Capability) (CapabilityMeta, bool) {