High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: starting the server silently rewrites the user config, freezing every default (PIN-071)
Luigi Agosti9afcfaa13b53
diff --git a/cmd/pinchtab/cmd_server_test.go b/cmd/pinchtab/cmd_server_test.goindex dac857c2..bdb5da21 100644--- a/cmd/pinchtab/cmd_server_test.go+++ b/cmd/pinchtab/cmd_server_test.go@@ -565,3 +565,40 @@ func TestDeferredDiagnosticsAreEmittedBeforeAnyExit(t *testing.T) {t.Fatalf("inspected %d %s call sites; the census matched almost nothing and would pass vacuously", sites, load)}}++// Only `pinchtab server` ever wrote the config, and the write it performed was the+// defect this card removed. These two load the same file and must stay non-writing —+// the regression guard is at the source, because driving `bridge` needs a browser and+// `security` is interactive.+func TestOnlyTheStartupWizardPathWritesTheConfig(t *testing.T) {+ writers := map[string][]string{}+ for _, path := range commandSourceFiles(t) {+ body, err := os.ReadFile(path) // #nosec G304 -- files listed from this package's own directory.+ if err != nil {+ t.Fatal(err)+ }+ for _, line := range strings.Split(string(body), "\n") {+ if strings.Contains(line, "config.SaveFileConfig(") {+ writers[filepath.Base(path)] = append(writers[filepath.Base(path)], strings.TrimSpace(line))+ }+ }+ }+ if len(writers) == 0 {+ t.Fatal("no config writer found in the command package; this census would pass vacuously")+ }++ // cmd_wizard.go owns every config write in this package: the startup stamp goes+ // through recordConfigVersion, and the interactive wizard writes what the user+ // just chose. cmd_bridge.go and cmd_server.go must not appear.+ allowed := map[string]bool{"cmd_wizard.go": true, "config_load.go": true}+ for file, lines := range writers {+ if !allowed[file] {+ t.Errorf("%s writes the config (%v); only the wizard path may, and bridge/server must stay non-writing", file, lines)+ }+ }+ for _, forbidden := range []string{"cmd_bridge.go", "cmd_server.go", "cmd_security.go"} {+ if lines, found := writers[forbidden]; found {+ t.Errorf("%s gained a config write: %v", forbidden, lines)+ }+ }+}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex a5079219..74b6fad8 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -296,7 +296,14 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {AutoSolver: defaultAutoSolverConfig(),}- finalizeProfileConfig(cfg)++ // Deferred, not called here, because the profile paths are DERIVED from+ // server.stateDir and the file that carries stateDir has not been read yet.+ // Finalizing eagerly filled ProfilesBaseDir from the default state dir, and the+ // second call after applyFileConfig then found it non-empty and left it alone — so+ // server.stateDir could never relocate profiles. A defer is the one shape that+ // cannot miss one of this function's several early returns.+ defer finalizeProfileConfig(cfg)var diags []LoadDiagnosticres := readAndParseConfigFile()@@ -328,7 +335,6 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {}diags = append(diags, applyFileConfig(cfg, res.FC)...)- finalizeProfileConfig(cfg)if cfg.Port == "" {return cfg, diags, fmt.Errorf("server port is not configured — set server.port in config.json")diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 32d78813..6310f768 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -3,6 +3,7 @@ package configimport ("bytes""encoding/json"+ "fmt""log/slog""os""path/filepath"@@ -1450,3 +1451,59 @@ func TestFileConfigFromRuntimeCarriesTheLogLevel(t *testing.T) {t.Fatalf("Server.LogLevel = %q, want error", fc.Server.LogLevel)}}++// server.stateDir must actually relocate profiles. finalizeProfileConfig's+// filepath.Join(StateDir, "profiles") fallback was unreachable because+// DefaultFileConfig pre-filled Profiles.BaseDir with an absolute userConfigDir() path —+// the same pre-filling that baked a host home directory into every written config. With+// it empty, this fallback is the live path, so a throwaway state dir stops writing+// profiles and quarantine directories into the real profile set.+func TestStateDirAloneRelocatesTheProfilesBaseDir(t *testing.T) {+ clearConfigEnvVars(t)+ stateDir := filepath.Join(t.TempDir(), "state")+ cfgPath := filepath.Join(t.TempDir(), "config.json")+ body := fmt.Sprintf(`{"server":{"port":"9867","token":"tok","stateDir":%q}}`, stateDir)+ if err := os.WriteFile(cfgPath, []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", cfgPath)++ cfg := Load()++ wantBase := filepath.Join(stateDir, "profiles")+ if cfg.ProfilesBaseDir != wantBase {+ t.Errorf("ProfilesBaseDir = %q, want %q — the stateDir fallback is unreachable again", cfg.ProfilesBaseDir, wantBase)+ }+ if cfg.ProfileDir != filepath.Join(wantBase, "default") {+ t.Errorf("ProfileDir = %q, want it under the relocated base", cfg.ProfileDir)+ }+ if home, err := os.UserHomeDir(); err == nil && home != "" && strings.HasPrefix(cfg.ProfilesBaseDir, filepath.Join(home, ".pinchtab")) {+ t.Errorf("ProfilesBaseDir still resolves into the real profile set: %q", cfg.ProfilesBaseDir)+ }+}++// The fallback is only reachable while nothing pre-fills BaseDir. This pins the shipped+// FileConfig default as empty, so restoring the pre-fill reds here by name rather than+// silently making the test above depend on a value nobody sets.+func TestTheShippedProfilesBaseDirIsEmptySoTheFallbackStaysLive(t *testing.T) {+ if got := DefaultFileConfig().Profiles.BaseDir; got != "" {+ t.Errorf("DefaultFileConfig().Profiles.BaseDir = %q, want empty: a pre-filled absolute path makes finalizeProfileConfig's stateDir fallback dead code and bakes a host path into every written config", got)+ }+}++// An explicit profiles.baseDir still wins: the fallback must not override what the user+// set.+func TestAnExplicitProfilesBaseDirStillWins(t *testing.T) {+ clearConfigEnvVars(t)+ explicit := filepath.Join(t.TempDir(), "chosen-profiles")+ cfgPath := filepath.Join(t.TempDir(), "config.json")+ body := fmt.Sprintf(`{"server":{"port":"9867","token":"tok","stateDir":%q},"profiles":{"baseDir":%q}}`, filepath.Join(t.TempDir(), "state"), explicit)+ if err := os.WriteFile(cfgPath, []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", cfgPath)++ if got := Load().ProfilesBaseDir; got != explicit {+ t.Errorf("ProfilesBaseDir = %q, want the explicitly configured %q", got, explicit)+ }+}diff --git a/internal/config/fileio.go b/internal/config/fileio.goindex 3cf6ed00..d29e15f6 100644--- a/internal/config/fileio.go+++ b/internal/config/fileio.go@@ -134,11 +134,30 @@ func SaveFileConfig(fc *FileConfig, path string) error {return fmt.Errorf("failed to read config file before writing: %w", err)}- data, err := renderMinimalConfig(fc, existing)- if err != nil {+ // Creating a config and updating one are different acts. With nothing on disk there+ // is no user shape to respect and the caller is `init` or the daemon's ensure-config,+ // whose whole job is to lay down a complete starter file — schema URL, bind, the+ // works. Only an UPDATE has a file whose shape is authoritative, and that is where+ // materialising defaults did the damage.+ var data []byte+ if len(existing) == 0 {+ if data, err = json.MarshalIndent(fc, "", " "); err != nil {+ return fmt.Errorf("failed to serialize config: %w", err)+ }+ data = append(data, '\n')+ } else if data, err = renderMinimalConfig(fc, existing); err != nil {return err}+ // A save that changes nothing does not touch the file. This is what makes a+ // no-op write byte-identical by construction rather than by matching the user's+ // formatting: an inline array or a hand-wrapped section is only ever re-rendered+ // when something in it actually changed. It also means a read-only config raises+ // no error for a write that had nothing to say.+ if len(existing) > 0 && sameJSONDocument(existing, data) {+ return nil+ }+if err := os.WriteFile(path, data, 0600); err != nil {return fmt.Errorf("failed to write config file: %w", err)}diff --git a/internal/config/fileio_minimal.go b/internal/config/fileio_minimal.goindex b67d56b0..7cf3732a 100644--- a/internal/config/fileio_minimal.go+++ b/internal/config/fileio_minimal.go@@ -94,7 +94,7 @@ func patchConfigObject(onDisk []jsonMember, full, shipped map[string]any) []jsonif len(members) == 0 {continue}- out = append(out, jsonMember{key: key, value: encodeJSONObject(members, 0)})+ out = append(out, jsonMember{key: key, value: encodeJSONObject(members)})continue}if sameJSONValue(value, shipped[key]) {@@ -121,13 +121,12 @@ func patchedValue(onDisk json.RawMessage, full, shipped any) json.RawMessage {return raw}shippedObj, _ := shipped.(map[string]any)- return encodeJSONObject(patchConfigObject(parseJSONObject(onDisk), fullObj, shippedObj), 0)+ return encodeJSONObject(patchConfigObject(parseJSONObject(onDisk), fullObj, shippedObj))}-// encodeJSONObject serialises members in order. Nested values are re-indented by-// indentJSONValue at write time, so depth is handled once at the top rather than-// threaded through every recursion.-func encodeJSONObject(members []jsonMember, depth int) json.RawMessage {+// encodeJSONObject serialises members in order, compactly. renderMinimalConfig indents+// the whole document once at the end, so no depth has to be threaded through here.+func encodeJSONObject(members []jsonMember) json.RawMessage {if len(members) == 0 {return json.RawMessage("{}")}@@ -162,7 +161,7 @@ func renderMinimalConfig(fc *FileConfig, existing []byte) ([]byte, error) {}members := patchConfigObject(parseJSONObject(existing), full, shipped)- compact := encodeJSONObject(members, 0)+ compact := encodeJSONObject(members)var out bytes.Bufferif err := json.Indent(&out, compact, "", " "); err != nil {@@ -171,3 +170,16 @@ func renderMinimalConfig(fc *FileConfig, existing []byte) ([]byte, error) {body := strings.TrimRight(out.String(), "\n")return []byte(body + "\n"), nil}++// sameJSONDocument reports whether two byte slices encode the same JSON value,+// ignoring key order and whitespace. Used to decide that a write would be a no-op.+func sameJSONDocument(a, b []byte) bool {+ var left, right any+ if err := json.Unmarshal(a, &left); err != nil {+ return false+ }+ if err := json.Unmarshal(b, &right); err != nil {+ return false+ }+ return sameJSONValue(left, right)+}diff --git a/internal/config/fileio_minimal_test.go b/internal/config/fileio_minimal_test.gonew file mode 100644index 00000000..22de3a59--- /dev/null+++ b/internal/config/fileio_minimal_test.go@@ -0,0 +1,323 @@+package config++import (+ "encoding/json"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++// A save must not materialise defaults. LoadFileConfig unmarshals the user's file on+// top of the shipped defaults, so the in-memory struct is always fully populated; a+// wholesale marshal turned a 50-byte config into a 3.8kB snapshot of one build's+// defaults, and every untouched setting became explicitly set — which silently cut that+// install off from every future default change.+func TestSavingAConfigDoesNotMaterialiseDefaults(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ original := "{\n \"server\": {\n \"port\": \"9913\",\n \"token\": \"tok3\"\n }\n}\n"+ if err := os.WriteFile(path, []byte(original), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }++ after, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(after) != original {+ t.Errorf("a load-then-save round trip rewrote the file:\n before %q\n after %q", original, string(after))+ }++ // Named individually rather than by size, so the failure says which section+ // leaked back in.+ for _, key := range []string{"$schema", "configVersion", "timeouts", "scheduler", "observability", "sessions", "autoSolver", "browsers", "profiles", "security", "instanceDefaults", "multiInstance"} {+ if strings.Contains(string(after), "\""+key+"\"") {+ t.Errorf("save added %q, which the user never set — that key now stops tracking the shipped default", key)+ }+ }+}++// The absent key must still resolve to the shipped value: suppressing the write is only+// safe because the loader treats absence as "use the default".+func TestAnAbsentSectionStillResolvesToTheShippedDefault(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ shipped := DefaultFileConfig()+ if fc.Timeouts != shipped.Timeouts {+ t.Errorf("timeouts resolved to %+v, want the shipped %+v", fc.Timeouts, shipped.Timeouts)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }+ if body, err := os.ReadFile(path); err != nil {+ t.Fatal(err)+ } else if strings.Contains(string(body), "timeouts") {+ t.Errorf("timeouts was written into a config that never set it: %s", body)+ }+}++// A key the file already carries is rewritten unconditionally, so an edit back to the+// shipped default still lands. A pure difference-from-defaults render would drop it from+// the patch and leave the old value standing — the one way writing less loses data.+func TestAnEditBackToTheDefaultValueIsStillWritten(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"},"browser":{"version":"1.2.3.4"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ shipped := DefaultFileConfig()+ fc.Browser.BrowserVersion = shipped.Browser.BrowserVersion+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }++ body, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(body), "1.2.3.4") {+ t.Errorf("the stale value survived a write that set it back to the default: %s", body)+ }+ if !strings.Contains(string(body), shipped.Browser.BrowserVersion) {+ t.Errorf("the key the user had set was dropped instead of updated: %s", body)+ }+}++// Member order is part of the file the user authored. Rendering through a map would sort+// every key, so a write the user asked for would arrive with an unexplained whole-file+// diff — the same harm as materialising defaults, wearing different clothes.+func TestSavingPreservesTheFilesKeyOrder(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ original := "{\n \"server\": {\n \"token\": \"tok3\",\n \"port\": \"9913\",\n \"bind\": \"127.0.0.1\"\n },\n \"browser\": {\n \"version\": \"1.2.3.4\"\n }\n}\n"+ if err := os.WriteFile(path, []byte(original), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }++ body, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(body) != original {+ t.Errorf("save reordered or reformatted an unchanged file:\n before %q\n after %q", original, string(body))+ }+ if got := strings.Index(string(body), "token"); got > strings.Index(string(body), "port") {+ t.Error("server.token moved after server.port; the file's own order was not preserved")+ }+}++// A key the struct does not model must survive a save. Dropping it would delete+// something the writer merely failed to parse.+func TestSavingKeepsAKeyTheStructDoesNotModel(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"},"somethingNobodyModels":{"keep":true}}`), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }+ body, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(body), "somethingNobodyModels") {+ t.Errorf("an unmodelled key was deleted by a save: %s", body)+ }+}++// The e2e fixture is the realistic case: a hand-authored, richly-populated config that a+// developer points PINCHTAB_CONFIG at when reproducing a failure. A load-then-save must+// leave it byte-identical, including its inline arrays.+func TestSavingTheE2EFixtureLeavesItByteIdentical(t *testing.T) {+ source := filepath.Join("..", "..", "tests", "e2e", "config", "pinchtab.json")+ original, err := os.ReadFile(source)+ if err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, original, 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }++ after, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(after) != string(original) {+ t.Errorf("a load-then-save changed the e2e fixture; first divergence at byte %d", firstDiff(string(original), string(after)))+ }+ for _, forbidden := range []string{"$schema", "configVersion", userConfigDir()} {+ if forbidden != "" && strings.Contains(string(after), forbidden) {+ t.Errorf("save added %q to the fixture", forbidden)+ }+ }+}++func firstDiff(a, b string) int {+ for i := 0; i < len(a) && i < len(b); i++ {+ if a[i] != b[i] {+ return i+ }+ }+ return min(len(a), len(b))+}++// No absolute host path may reach a config the user did not put one in: such a file gets+// copied into containers, committed, and shared.+func TestSavingWritesNoAbsoluteHostPath(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ fc.ConfigVersion = CurrentConfigVersion+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }+ body, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ for _, key := range []string{"baseDir", "extensionPaths"} {+ if strings.Contains(string(body), key) {+ t.Errorf("save wrote %q into a config that never set it: %s", key, body)+ }+ }+ if home, err := os.UserHomeDir(); err == nil && home != "" && strings.Contains(string(body), home) {+ t.Errorf("save baked a host home directory into the config: %s", body)+ }+ // The write the wizard needs still lands.+ var written map[string]any+ if err := json.Unmarshal(body, &written); err != nil {+ t.Fatal(err)+ }+ if written["configVersion"] != CurrentConfigVersion {+ t.Errorf("configVersion = %v, want %q — the one key the startup write exists to add", written["configVersion"], CurrentConfigVersion)+ }+}++// Loading must not unprotect a config the user marked read-only: restoring the owner+// write bit on the read path is what let a later write replace it silently.+func TestLoadingLeavesAReadOnlyConfigsModeAlone(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("unix-only file mode semantics")+ }+ dir := t.TempDir()+ path := filepath.Join(dir, "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(path, 0444); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatalf("LoadFileConfig() error = %v", err)+ }+ fi, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if got := fi.Mode().Perm(); got != 0444 {+ t.Errorf("mode after load = %o, want 0444 — reading a config must not make it writable again", got)+ }++ // And the write that used to succeed because of that chmod now fails loudly+ // instead of replacing a protected file. The change has to be real: a save with+ // nothing to say is skipped entirely, which is its own form of leaving the file+ // alone.+ fc.ConfigVersion = CurrentConfigVersion+ if err := SaveFileConfig(fc, path); err == nil {+ t.Error("SaveFileConfig succeeded against a 0444 config; a protected file must not be replaced silently")+ }+ if fi, err := os.Stat(path); err != nil {+ t.Fatal(err)+ } else if got := fi.Mode().Perm(); got != 0444 {+ t.Errorf("mode after a refused save = %o, want 0444", got)+ }+}++// security.idpi.allowedDomains is the one alias the loader normalises into+// security.allowedDomains. A patch-based save writes the canonical key while the alias+// stays on disk, so the round trip is what matters: the value the user set must survive,+// and the loader must keep preferring the canonical spelling.+func TestSavingAConfigThatUsesTheIDPIAllowedDomainsAliasKeepsTheValue(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9913","token":"tok3"},"security":{"idpi":{"allowedDomains":["example.test"]}}}`), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ fc, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if got := strings.Join(fc.Security.AllowedDomains, ","); got != "example.test" {+ t.Fatalf("precondition: the alias must load into Security.AllowedDomains, got %q", got)+ }+ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatal(err)+ }++ reloaded, _, err := LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if got := strings.Join(reloaded.Security.AllowedDomains, ","); got != "example.test" {+ body, _ := os.ReadFile(path)+ t.Errorf("the aliased value did not survive a save: got %q, file is now %s", got, body)+ }+}