Skip to content

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

fix: a dashboard config PUT that touches only the port is diffed as a security change, so every edit demands elevation (PIN-071)

Luigi Agosti9c5dafcebf73
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index b866d503..7e3d42b4 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -259,14 +259,8 @@ func TestHandlePutConfigPreservesExistingToken(t *testing.T) {
}
func TestHandlePutConfigPreservesWriteOnlySecretsFromRedactedGetPayload(t *testing.T) {
- fc := config.DefaultFileConfig()
- fc.Server.Token = "secret-token"
stateKey := "state-secret"
- fc.Security.StateEncryptionKey = &stateKey
- fc.AutoSolver.External.CapsolverKey = "capsolver-secret"
- fc.AutoSolver.External.TwoCaptchaKey = "twocaptcha-secret"
-
- api := newConfigAPITestAPI(t, fc)
+ api := newConfigAPIOverFile(t, []byte(minimalUserConfigJSON))
sessions := browsersession.NewManager(browsersession.Config{ElevationWindow: time.Minute})
sessionID, err := sessions.Create("secret-token")
if err != nil {
@@ -281,13 +275,7 @@ func TestHandlePutConfigPreservesWriteOnlySecretsFromRedactedGetPayload(t *testi
t.Fatalf("HandleGetConfig() status = %d, want %d", getRes.Code, http.StatusOK)
}
- env := decodeConfigEnvelope(t, getRes)
- env.Config.Server.Port = "9898"
-
- body, err := json.Marshal(env.Config)
- if err != nil {
- t.Fatalf("Marshal() error = %v", err)
- }
+ body := putBodyFromGetPayloadWithPort(t, getRes, "9898")
putReq := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
putReq.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
@@ -588,10 +576,24 @@ func TestHandleHealthSecurityVisibilityByAuthMethod(t *testing.T) {
func newConfigAPITestAPI(t *testing.T, fc config.FileConfig) *ConfigAPI {
t.Helper()
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ t.Fatalf("MarshalIndent() error = %v", err)
+ }
+ return newConfigAPIOverFile(t, data)
+}
+
+// newConfigAPIOverFile builds the API over the exact bytes given, so a test can
+// exercise the shape a real config file has: keys the user never set are absent,
+// which loads them as nil rather than as the empty slices a materialised file
+// carries.
+func newConfigAPIOverFile(t *testing.T, data []byte) *ConfigAPI {
+ t.Helper()
+
configPath := filepath.Join(t.TempDir(), "config.json")
t.Setenv("PINCHTAB_CONFIG", configPath)
- if err := config.SaveFileConfig(&fc, configPath); err != nil {
- t.Fatalf("SaveFileConfig() error = %v", err)
+ if err := os.WriteFile(configPath, data, 0o600); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
}
return NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
@@ -755,3 +757,63 @@ func TestHandleHealthCountsQuarantinedProfilesSeparately(t *testing.T) {
t.Errorf("health quarantinedProfiles = %d, want 2", health.QuarantinedProfiles)
}
}
+
+func TestHandlePutConfigDoesNotDemandElevationForANonSensitiveEdit(t *testing.T) {
+ api := newConfigAPIOverFile(t, []byte(minimalUserConfigJSON))
+
+ getRes := httptest.NewRecorder()
+ api.HandleGetConfig(getRes, httptest.NewRequest(http.MethodGet, "/api/config", nil))
+ if getRes.Code != http.StatusOK {
+ t.Fatalf("HandleGetConfig() status = %d, want %d", getRes.Code, http.StatusOK)
+ }
+ body := putBodyFromGetPayloadWithPort(t, getRes, "9898")
+
+ putReq := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ putReq.AddCookie(&http.Cookie{Name: authn.CookieName, Value: "dashboard-session"})
+ putRes := httptest.NewRecorder()
+ api.HandlePutConfig(putRes, putReq)
+ if putRes.Code != http.StatusOK {
+ t.Fatalf("HandlePutConfig() status = %d, want %d: %s", putRes.Code, http.StatusOK, putRes.Body.String())
+ }
+}
+
+// putBodyFromGetPayloadWithPort edits the GET payload the way a dashboard client
+// does: the received JSON is sent back verbatim apart from the one field the user
+// touched. Re-marshalling through config.FileConfig instead would drop every empty
+// array the payload carries, which is exactly the difference this exercises.
+const minimalUserConfigJSON = `{
+ "server": {
+ "port": "9913",
+ "token": "secret-token"
+ },
+ "security": {
+ "stateEncryptionKey": "state-secret"
+ },
+ "autoSolver": {
+ "external": {
+ "capsolverKey": "capsolver-secret",
+ "twoCaptchaKey": "twocaptcha-secret"
+ }
+ }
+}`
+
+func putBodyFromGetPayloadWithPort(t *testing.T, getRes *httptest.ResponseRecorder, port string) []byte {
+ t.Helper()
+
+ var envelope struct {
+ Config map[string]any `json:"config"`
+ }
+ if err := json.Unmarshal(getRes.Body.Bytes(), &envelope); err != nil {
+ t.Fatalf("Unmarshal GET payload: %v", err)
+ }
+ server, ok := envelope.Config["server"].(map[string]any)
+ if !ok {
+ t.Fatalf("GET payload has no server section: %v", envelope.Config)
+ }
+ server["port"] = port
+ body, err := json.Marshal(envelope.Config)
+ if err != nil {
+ t.Fatalf("Marshal PUT body: %v", err)
+ }
+ return body
+}
diff --git a/internal/dashboard/config_changes.go b/internal/dashboard/config_changes.go
index 2d6c8de3..3158919b 100644
--- a/internal/dashboard/config_changes.go
+++ b/internal/dashboard/config_changes.go
@@ -1,11 +1,20 @@
package dashboard
import (
- "reflect"
+ "encoding/json"
"github.com/pinchtab/pinchtab/internal/config"
)
+func sameConfigSection(a, b any) bool {
+ left, errLeft := json.Marshal(a)
+ right, errRight := json.Marshal(b)
+ if errLeft != nil || errRight != nil {
+ return false
+ }
+ return string(left) == string(right)
+}
+
type sensitiveConfigChangeSet struct {
requiresElevation bool
proxyChanged bool
@@ -24,11 +33,11 @@ func sensitiveConfigChanges(current, next *config.FileConfig) sensitiveConfigCha
if current == nil || next == nil {
return out
}
- if !reflect.DeepEqual(current.Security, next.Security) {
+ if !sameConfigSection(current.Security, next.Security) {
out.requiresElevation = true
out.names = append(out.names, "security")
}
- if !reflect.DeepEqual(current.Browser.Proxy, next.Browser.Proxy) {
+ if !sameConfigSection(current.Browser.Proxy, next.Browser.Proxy) {
out.requiresElevation = true
out.proxyChanged = true
out.names = append(out.names, "browser.proxy")
@@ -69,7 +78,7 @@ func changedTargetProxyNames(current, next config.BrowserTargetsConfig) []string
}
var changed []string
for _, name := range names {
- if !reflect.DeepEqual(current[name].Proxy, next[name].Proxy) {
+ if !sameConfigSection(current[name].Proxy, next[name].Proxy) {
changed = append(changed, name)
}
}
@@ -84,7 +93,7 @@ func (c *ConfigAPI) restartReasonsFor(next config.FileConfig) []string {
// edit, so any change to the security block only takes effect after a restart.
// Surfacing it here is what lets `pinchtab security`/`health` warn that the
// running server is enforcing stale policy instead of silently diverging.
- if !reflect.DeepEqual(c.boot.Security, next.Security) {
+ if !sameConfigSection(c.boot.Security, next.Security) {
reasons = append(reasons, "Security policy")
}
if c.boot.Server.Port != next.Server.Port || c.boot.Server.Bind != next.Server.Bind {
diff --git a/internal/dashboard/config_changes_test.go b/internal/dashboard/config_changes_test.go
new file mode 100644
index 00000000..b17985de
--- /dev/null
+++ b/internal/dashboard/config_changes_test.go
@@ -0,0 +1,131 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// The fields are derived by reflection rather than named, so a slice added to
+// SecurityConfig later inherits the check.
+func TestSensitiveConfigChangesIgnoresAbsentVersusEmptyContainers(t *testing.T) {
+ current := config.DefaultFileConfig()
+ next := current
+
+ emptied := emptyContainerFields(t, reflect.ValueOf(&next.Security).Elem(), "security")
+ emptied = append(emptied, emptyContainerFields(t, reflect.ValueOf(&next.Browser).Elem(), "browser")...)
+ if len(emptied) == 0 {
+ t.Fatal("no slice or map field found under the sections that gate elevation, so this guard checked nothing")
+ }
+ t.Logf("emptied %d container fields: %v", len(emptied), emptied)
+
+ changes := sensitiveConfigChanges(&current, &next)
+ if changes.requiresElevation {
+ t.Errorf("sensitiveConfigChanges() demands elevation for %v, but only absent-versus-empty containers differ: %v", changes.names, emptied)
+ }
+}
+
+func TestSensitiveConfigChangesStillReportsARealSecurityEdit(t *testing.T) {
+ current := config.DefaultFileConfig()
+ next := current
+ next.Security.AllowedDomains = append(append([]string(nil), current.Security.AllowedDomains...), "example.com")
+
+ changes := sensitiveConfigChanges(&current, &next)
+ if !changes.requiresElevation {
+ t.Fatal("sensitiveConfigChanges() allows an allowlist edit without elevation")
+ }
+ if len(changes.names) != 1 || changes.names[0] != "security" {
+ t.Fatalf("changes.names = %v, want [security]", changes.names)
+ }
+}
+
+func TestSameConfigSectionTreatsUnmarshalableValuesAsChanged(t *testing.T) {
+ if sameConfigSection(func() {}, func() {}) {
+ t.Error("sameConfigSection() reports two unmarshalable values as equal; a section it cannot read must reach the elevation gate")
+ }
+}
+
+func TestRestartReasonsIgnoreAbsentVersusEmptyContainers(t *testing.T) {
+ boot := config.DefaultFileConfig()
+ api := NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ api.boot = boot
+
+ next := boot
+ if len(emptyContainerFields(t, reflect.ValueOf(&next.Security).Elem(), "security")) == 0 {
+ t.Fatal("no slice or map field found under SecurityConfig, so this guard checked nothing")
+ }
+
+ for _, reason := range api.restartReasonsFor(next) {
+ if reason == "Security policy" {
+ t.Error("restartReasonsFor() demands a restart for Security policy, but only absent-versus-empty containers differ")
+ }
+ }
+}
+
+func emptyContainerFields(t *testing.T, v reflect.Value, path string) []string {
+ t.Helper()
+
+ var touched []string
+ switch v.Kind() {
+ case reflect.Slice:
+ if v.IsNil() && v.CanSet() {
+ v.Set(reflect.MakeSlice(v.Type(), 0, 0))
+ touched = append(touched, path)
+ }
+ case reflect.Map:
+ if v.IsNil() && v.CanSet() {
+ v.Set(reflect.MakeMap(v.Type()))
+ touched = append(touched, path)
+ }
+ case reflect.Struct:
+ for i := range v.NumField() {
+ field := v.Type().Field(i)
+ if !field.IsExported() {
+ continue
+ }
+ touched = append(touched, emptyContainerFields(t, v.Field(i), path+"."+jsonFieldName(field))...)
+ }
+ case reflect.Ptr:
+ if !v.IsNil() {
+ touched = append(touched, emptyContainerFields(t, v.Elem(), path)...)
+ }
+ }
+ return touched
+}
+
+func jsonFieldName(field reflect.StructField) string {
+ tag := field.Tag.Get("json")
+ for i := range len(tag) {
+ if tag[i] == ',' {
+ tag = tag[:i]
+ break
+ }
+ }
+ if tag == "" || tag == "-" {
+ return field.Name
+ }
+ return tag
+}
+
+func TestEmptyContainerFieldsKeepsTheJSONDocumentIdentical(t *testing.T) {
+ before := config.DefaultFileConfig()
+ after := before
+ if len(emptyContainerFields(t, reflect.ValueOf(&after.Security).Elem(), "security")) == 0 {
+ t.Fatal("no container field emptied, so the other guards in this file check nothing")
+ }
+
+ left, err := json.Marshal(before.Security)
+ if err != nil {
+ t.Fatalf("Marshal(before): %v", err)
+ }
+ right, err := json.Marshal(after.Security)
+ if err != nil {
+ t.Fatalf("Marshal(after): %v", err)
+ }
+ if string(left) != string(right) {
+ t.Fatalf("emptying nil containers changed the JSON document, so these fixtures differ in settings and not only in representation:\n%s\n%s", left, right)
+ }
+}