High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the explicit-config token guard is unreachable on the server path, so a secret is written into an operator-authored config that bridge refuses to touch (PIN-201)
Luigi Agostiffec48e9d31c
diff --git a/cmd/pinchtab/cmd_config_actions.go b/cmd/pinchtab/cmd_config_actions.goindex 4e537192..9b125cdc 100644--- a/cmd/pinchtab/cmd_config_actions.go+++ b/cmd/pinchtab/cmd_config_actions.go@@ -54,6 +54,7 @@ func handleConfigInit() {}fmt.Printf("Config file created at %s\n", configPath)+ fmt.Fprintf(os.Stderr, "pinchtab: generated server.token in %s\n", configPath)}func handleConfigPath() {diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.goindex a380b62c..93a24a4c 100644--- a/cmd/pinchtab/cmd_wizard.go+++ b/cmd/pinchtab/cmd_wizard.go@@ -1,6 +1,7 @@package mainimport (+ "errors""fmt""os""strings"@@ -14,8 +15,10 @@ import (// Returns true if the user completed setup, false if they cancelled.func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bool {interactive := isInteractiveTerminal()- tokenGenerated, err := config.EnsureFileToken(cfg)- if err != nil {+ tokenGenerated, err := config.ProvisionFileToken(cfg, configPath)+ if errors.Is(err, config.ErrOperatorConfigToken) {+ tokenGenerated = false+ } else if err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to generate auth token: %v", err)))return false}@@ -25,9 +28,9 @@ func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bo}if isNew {- return runFullWizard(cfg, configPath)+ return runFullWizard(cfg, configPath, tokenGenerated)}- return runUpgradeNotice(cfg, configPath)+ return runUpgradeNotice(cfg, configPath, tokenGenerated)}// A non-interactive start writes the config ONLY when a token had to be generated.@@ -57,10 +60,10 @@ func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew, tofmt.Println()}- return recordConfigVersion(cfg, configPath, true)+ return recordConfigVersion(cfg, configPath, true, tokenGenerated)}-func runFullWizard(cfg *config.FileConfig, configPath string) bool {+func runFullWizard(cfg *config.FileConfig, configPath string, tokenGenerated bool) bool {fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "🛡️ Know your config"))fmt.Println()@@ -111,6 +114,9 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {fmt.Println()cfg.ConfigVersion = config.CurrentConfigVersion+ if tokenGenerated {+ fmt.Fprintf(os.Stderr, "pinchtab: generated server.token in %s\n", configPath)+ }if err := config.SaveFileConfig(cfg, configPath); err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to save config: %v", err)))return false@@ -122,7 +128,7 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {return true}-func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {+func runUpgradeNotice(cfg *config.FileConfig, configPath string, tokenGenerated bool) bool {fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "🛡️ Config update (v"+config.CurrentConfigVersion+")"))fmt.Println()@@ -137,7 +143,7 @@ func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")fmt.Println()- return recordConfigVersion(cfg, configPath, false)+ return recordConfigVersion(cfg, configPath, false, tokenGenerated)}// securityPosture is the single source of truth for a wizard security choice:@@ -252,7 +258,7 @@ func orDefault(val, fallback string) string {}// recordConfigVersion is the only write a plain `pinchtab server` start performs. It-// exists to stamp configVersion (plus any token EnsureFileToken generated), and it used+// exists to stamp configVersion (plus any token ProvisionFileToken generated), and it used// to be silent and to marshal the whole defaults-populated struct — which is how a// 50-byte config became a 3.8kB frozen snapshot of one build's defaults. SaveFileConfig// now writes only changed keys; announce says it out loud on the startup path, where@@ -260,10 +266,15 @@ func orDefault(val, fallback string) string {//// The error is reported rather than discarded either way: a config the user marked// read-only must not be replaced, and swallowing EACCES here is what made that silent.-func recordConfigVersion(cfg *config.FileConfig, configPath string, announce bool) bool {+func recordConfigVersion(cfg *config.FileConfig, configPath string, announce, tokenGenerated bool) bool {cfg.ConfigVersion = config.CurrentConfigVersion- if announce {+ switch {+ case announce && tokenGenerated:+ fmt.Fprintf(os.Stderr, "pinchtab: recording configVersion %s and a generated server.token in %s\n", config.CurrentConfigVersion, configPath)+ case announce:fmt.Fprintf(os.Stderr, "pinchtab: recording configVersion %s in %s\n", config.CurrentConfigVersion, configPath)+ case tokenGenerated:+ fmt.Fprintf(os.Stderr, "pinchtab: generated server.token in %s\n", configPath)}if err := config.SaveFileConfig(cfg, configPath); err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("pinchtab: could not record configVersion in %s: %v", configPath, err)))diff --git a/cmd/pinchtab/cmd_wizard_test.go b/cmd/pinchtab/cmd_wizard_test.goindex eadf96b7..c0ea5558 100644--- a/cmd/pinchtab/cmd_wizard_test.go+++ b/cmd/pinchtab/cmd_wizard_test.go@@ -39,7 +39,7 @@ func TestRunUpgradeNoticeDoesNotPrintToken(t *testing.T) {cfg.Server.Token = "very-secret-token-value"output := captureStdout(t, func() {- if !runUpgradeNotice(&cfg, configPath) {+ if !runUpgradeNotice(&cfg, configPath, false) {t.Fatal("runUpgradeNotice() = false")}})@@ -159,7 +159,7 @@ func TestRecordConfigVersionAnnouncesItselfAndReportsAFailedWrite(t *testing.T)}announced := captureStderr(t, func() {- if !recordConfigVersion(cfg, path, true) {+ if !recordConfigVersion(cfg, path, true, false) {t.Error("recordConfigVersion() = false for a writable config")}})@@ -184,7 +184,7 @@ func TestRecordConfigVersionAnnouncesItselfAndReportsAFailedWrite(t *testing.T)t.Fatal(err)}reported := captureStderr(t, func() {- if recordConfigVersion(lockedCfg, locked, false) {+ if recordConfigVersion(lockedCfg, locked, false, false) {t.Error("recordConfigVersion() = true against a read-only config; the failure must not be swallowed")}})diff --git a/cmd/pinchtab/config_load.go b/cmd/pinchtab/config_load.goindex 6ae25cb1..ce7d4b46 100644--- a/cmd/pinchtab/config_load.go+++ b/cmd/pinchtab/config_load.go@@ -56,17 +56,9 @@ func ensureMandatoryToken() error {return nil}- if strings.TrimSpace(os.Getenv("PINCHTAB_CONFIG")) != "" {- if _, statErr := os.Stat(configPath); statErr == nil {- return fmt.Errorf("server token is required in %s when PINCHTAB_CONFIG is set; add server.token or set PINCHTAB_TOKEN", configPath)- } else if !os.IsNotExist(statErr) {- return fmt.Errorf("stat config file: %w", statErr)- }- }-- changed, err := config.EnsureFileToken(fc)+ changed, err := config.ProvisionFileToken(fc, configPath)if err != nil {- return fmt.Errorf("ensure server token: %w", err)+ return err}if !changed {return nil@@ -75,5 +67,6 @@ func ensureMandatoryToken() error {if err := config.SaveFileConfig(fc, configPath); err != nil {return fmt.Errorf("save config file: %w", err)}+ fmt.Fprintf(os.Stderr, "pinchtab: generated server.token in %s\n", configPath)return nil}diff --git a/cmd/pinchtab/token_guard_test.go b/cmd/pinchtab/token_guard_test.gonew file mode 100644index 00000000..44c5b674--- /dev/null+++ b/cmd/pinchtab/token_guard_test.go@@ -0,0 +1,143 @@+package main++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func modeConfigPhases() map[string]func() {+ return map[string]func(){+ "server": maybeRunWizard,+ "bridge": func() {},+ }+}++func writeOperatorConfig(t *testing.T) string {+ t.Helper()+ configPath := filepath.Join(t.TempDir(), "cfg.json")+ if err := os.WriteFile(configPath, []byte(`{"server":{"port":"18274"},"instanceDefaults":{"mode":"headless"}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ return configPath+}++func TestBothModesRefuseToProvisionATokenIntoAnOperatorConfig(t *testing.T) {+ for mode, configPhase := range modeConfigPhases() {+ t.Run(mode, func(t *testing.T) {+ configPath := writeOperatorConfig(t)+ t.Setenv("PINCHTAB_CONFIG", configPath)+ t.Setenv("PINCHTAB_TOKEN", "")+ before, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }++ configPhase()+ refusal := ensureMandatoryToken()++ if !errors.Is(refusal, config.ErrOperatorConfigToken) {+ t.Fatalf("%s mode: err = %v, want the operator-config refusal; a mode whose config phase provisions first makes the guard unreachable", mode, refusal)+ }+ if !strings.Contains(refusal.Error(), "add server.token or set PINCHTAB_TOKEN") {+ t.Errorf("%s mode: refusal %q lost its remedies", mode, refusal)+ }+ after, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(before, after) {+ t.Errorf("%s mode: the operator's config changed on a refused start:\nbefore: %s\nafter: %s", mode, before, after)+ }+ })+ }+}++func TestAnEnvTokenStartsBothModesWithoutTouchingTheOperatorConfig(t *testing.T) {+ for mode, configPhase := range modeConfigPhases() {+ t.Run(mode, func(t *testing.T) {+ configPath := writeOperatorConfig(t)+ t.Setenv("PINCHTAB_CONFIG", configPath)+ t.Setenv("PINCHTAB_TOKEN", "env-token")+ before, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }++ configPhase()+ if err := ensureMandatoryToken(); err != nil {+ t.Fatalf("%s mode: PINCHTAB_TOKEN must satisfy the token requirement, got %v", mode, err)+ }++ after, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(before, after) {+ t.Errorf("%s mode: the operator's config changed under an env token:\nbefore: %s\nafter: %s", mode, before, after)+ }+ })+ }+}++func TestTheDefaultPathStillSelfProvisionsAndSaysSo(t *testing.T) {+ tmpHome := t.TempDir()+ t.Setenv("HOME", tmpHome)+ t.Setenv("PINCHTAB_CONFIG", "")+ t.Setenv("PINCHTAB_TOKEN", "")++ stderr := captureStderr(t, func() {+ if err := ensureMandatoryToken(); err != nil {+ t.Fatalf("a first run on the default path must self-provision, got %v", err)+ }+ })++ fc, configPath, err := config.LoadFileConfig()+ if err != nil {+ t.Fatal(err)+ }+ if fc == nil || strings.TrimSpace(fc.Server.Token) == "" {+ t.Fatalf("no token persisted at %s", configPath)+ }+ if !strings.Contains(stderr, "server.token") {+ t.Errorf("stderr %q does not name the generated server.token; a silent credential write is what this card removed", stderr)+ }+}++func TestRecordConfigVersionNamesAGeneratedToken(t *testing.T) {+ for _, tc := range []struct {+ name string+ announce bool+ tokenGenerated bool+ wantSays []string+ wantSilent bool+ }{+ {name: "version and token", announce: true, tokenGenerated: true, wantSays: []string{"configVersion", "server.token"}},+ {name: "version only", announce: true, tokenGenerated: false, wantSays: []string{"configVersion"}},+ {name: "token without version announcement", announce: false, tokenGenerated: true, wantSays: []string{"server.token"}},+ {name: "quiet when nothing was generated", announce: false, tokenGenerated: false, wantSilent: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ configPath := filepath.Join(t.TempDir(), "cfg.json")+ cfg := &config.FileConfig{}+ stderr := captureStderr(t, func() {+ if !recordConfigVersion(cfg, configPath, tc.announce, tc.tokenGenerated) {+ t.Fatalf("recordConfigVersion failed")+ }+ })+ if tc.wantSilent && stderr != "" {+ t.Fatalf("stderr = %q, want silence", stderr)+ }+ for _, says := range tc.wantSays {+ if !strings.Contains(stderr, says) {+ t.Errorf("stderr = %q, want it to name %q; the line telling the operator their file was touched must not omit the secret half of the write", stderr, says)+ }+ }+ })+ }+}diff --git a/internal/cli/report/security_test.go b/internal/cli/report/security_test.goindex d98c73a6..5e3b0f01 100644--- a/internal/cli/report/security_test.go+++ b/internal/cli/report/security_test.go@@ -1,6 +1,8 @@package reportimport (+ "bytes"+ "errors""os""path/filepath""testing"@@ -269,13 +271,13 @@ func TestApplyRecommendedSecurityDefaults(t *testing.T) {}}-func TestApplyRecommendedSecurityDefaults_GeneratesTokenWhenMissing(t *testing.T) {+func TestApplyRecommendedSecurityDefaults_LeavesAMissingTokenAlone(t *testing.T) {fc := &config.FileConfig{}applyRecommendedSecurityDefaults(fc)- if fc.Server.Token == "" {- t.Fatalf("expected generated token, got empty")+ if fc.Server.Token != "" {+ t.Fatalf("applying security defaults generated a token %q; whether one may be added to an existing config is ProvisionFileToken's decision, and generating here bypasses the operator-config refusal", fc.Server.Token)}}@@ -343,11 +345,44 @@ func TestRestoreSecurityDefaults(t *testing.T) {}}-func TestRestoreSecurityDefaults_TokenOnlyChangeIsSaved(t *testing.T) {+func TestRestoreSecurityDefaults_RefusesToProvisionIntoAnOperatorConfig(t *testing.T) {tmpDir := t.TempDir()configPath := filepath.Join(tmpDir, "config.json")t.Setenv("PINCHTAB_CONFIG", configPath)+ fc := config.DefaultFileConfig()+ fc.Server.Token = ""+ if err := config.SaveFileConfig(&fc, configPath); err != nil {+ t.Fatalf("SaveFileConfig() error = %v", err)+ }+ before, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }++ _, _, err = restoreSecurityDefaults()+ if !errors.Is(err, config.ErrOperatorConfigToken) {+ t.Fatalf("restoreSecurityDefaults() error = %v, want the operator-config refusal; this path used to generate a credential into the operator's file and discard the error", err)+ }++ after, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(before, after) {+ t.Fatalf("the operator's config changed on a refused restore:\nbefore: %s\nafter: %s", before, after)+ }+}++func TestRestoreSecurityDefaults_TokenOnlyChangeOnTheDefaultPathIsSaved(t *testing.T) {+ tmpHome := t.TempDir()+ t.Setenv("HOME", tmpHome)+ t.Setenv("PINCHTAB_CONFIG", "")+ configPath := filepath.Join(tmpHome, ".pinchtab", "config.json")+ if err := os.MkdirAll(filepath.Dir(configPath), 0o700); err != nil {+ t.Fatal(err)+ }+fc := config.DefaultFileConfig()fc.Server.Token = ""if err := config.SaveFileConfig(&fc, configPath); err != nil {@@ -367,6 +402,6 @@ func TestRestoreSecurityDefaults_TokenOnlyChangeIsSaved(t *testing.T) {t.Fatalf("LoadFileConfig() error = %v", err)}if loaded.Server.Token == "" {- t.Fatalf("expected generated token to be persisted")+ t.Fatalf("expected generated token to be persisted on the default path")}}diff --git a/internal/config/config_utils.go b/internal/config/config_utils.goindex c6abb6c7..cb124409 100644--- a/internal/config/config_utils.go+++ b/internal/config/config_utils.go@@ -3,6 +3,7 @@ package configimport ("crypto/rand""encoding/hex"+ "errors""fmt""os""path/filepath"@@ -63,6 +64,29 @@ func GenerateAuthToken() (string, error) {return hex.EncodeToString(buf), nil}+// ErrOperatorConfigToken marks the refusal to write a generated credential into+// a config file the operator supplied via PINCHTAB_CONFIG.+var ErrOperatorConfigToken = errors.New("server token is required")++// ProvisionFileToken is the one decision point for adding a token to an+// EXISTING config: it refuses when the operator supplied the file explicitly+// (PINCHTAB_CONFIG set and the file present), and otherwise generates one via+// EnsureFileToken. Only config init may call EnsureFileToken directly — a fresh+// default file has no operator-authored content to protect.+func ProvisionFileToken(fc *FileConfig, configPath string) (bool, error) {+ if fc != nil && strings.TrimSpace(fc.Server.Token) != "" {+ return false, nil+ }+ if strings.TrimSpace(os.Getenv("PINCHTAB_CONFIG")) != "" {+ if _, statErr := os.Stat(configPath); statErr == nil {+ return false, fmt.Errorf("%w in %s when PINCHTAB_CONFIG is set; add server.token or set PINCHTAB_TOKEN", ErrOperatorConfigToken, configPath)+ } else if !os.IsNotExist(statErr) {+ return false, fmt.Errorf("stat config file: %w", statErr)+ }+ }+ return EnsureFileToken(fc)+}+// EnsureFileToken guarantees that a persisted config carries a non-empty// server token. It returns true when a new token was generated.func EnsureFileToken(fc *FileConfig) (bool, error) {diff --git a/internal/config/config_utils_test.go b/internal/config/config_utils_test.goindex fde78805..3211e398 100644--- a/internal/config/config_utils_test.go+++ b/internal/config/config_utils_test.go@@ -1,9 +1,11 @@package configimport (+ "errors""os""path/filepath""runtime"+ "strings""testing")@@ -122,3 +124,61 @@ func TestUserConfigDirWindowsUsesUserConfigDir(t *testing.T) {t.Fatalf("userConfigDir() = %q, want Windows default path %q", got, want)}}++func TestProvisionFileTokenRefusesAnOperatorSuppliedConfig(t *testing.T) {+ dir := t.TempDir()+ configPath := filepath.Join(dir, "cfg.json")+ if err := os.WriteFile(configPath, []byte(`{"server":{"port":"1"}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", configPath)++ fc := &FileConfig{}+ changed, err := ProvisionFileToken(fc, configPath)+ if !errors.Is(err, ErrOperatorConfigToken) {+ t.Fatalf("err = %v, want ErrOperatorConfigToken; a generated credential must not be written into a file the operator supplied", err)+ }+ if changed || fc.Server.Token != "" {+ t.Fatalf("changed = %v, token = %q; the refusal must not provision anyway", changed, fc.Server.Token)+ }+}++func TestProvisionFileTokenProvisionsWhenTheConfigIsNotOperatorSupplied(t *testing.T) {+ for _, tc := range []struct {+ name string+ envVal func(dir string) string+ }{+ {"no PINCHTAB_CONFIG", func(string) string { return "" }},+ {"PINCHTAB_CONFIG names an absent file", func(dir string) string { return filepath.Join(dir, "cfg.json") }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ dir := t.TempDir()+ configPath := filepath.Join(dir, "cfg.json")+ t.Setenv("PINCHTAB_CONFIG", tc.envVal(dir))++ fc := &FileConfig{}+ changed, err := ProvisionFileToken(fc, configPath)+ if err != nil {+ t.Fatal(err)+ }+ if !changed || strings.TrimSpace(fc.Server.Token) == "" {+ t.Fatalf("changed = %v, token = %q; a config the operator did not author still self-provisions", changed, fc.Server.Token)+ }+ })+ }+}++func TestProvisionFileTokenKeepsAnExistingToken(t *testing.T) {+ dir := t.TempDir()+ configPath := filepath.Join(dir, "cfg.json")+ if err := os.WriteFile(configPath, []byte(`{}`), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", configPath)++ fc := &FileConfig{Server: ServerConfig{Token: "tok"}}+ changed, err := ProvisionFileToken(fc, configPath)+ if err != nil || changed {+ t.Fatalf("changed = %v, err = %v; a present token needs no decision at all", changed, err)+ }+}diff --git a/internal/config/workflow/mutate.go b/internal/config/workflow/mutate.goindex 958b83da..97a7ae49 100644--- a/internal/config/workflow/mutate.go+++ b/internal/config/workflow/mutate.go@@ -86,6 +86,9 @@ func InitDefaultConfig(path string) error {}fc := config.DefaultFileConfig()+ // EnsureFileToken directly, not ProvisionFileToken: config init materialises a+ // FRESH default file, so there is no operator-authored content to protect and+ // generating a token is the whole point. This is the one recorded exemption.if _, err := config.EnsureFileToken(&fc); err != nil {return fmt.Errorf("generate auth token: %w", err)}diff --git a/internal/config/workflow/security.go b/internal/config/workflow/security.goindex 4eca2197..57cbd44d 100644--- a/internal/config/workflow/security.go+++ b/internal/config/workflow/security.go@@ -3,6 +3,7 @@ package workflowimport ("encoding/json""fmt"+ "os""reflect""slices""strings"@@ -17,7 +18,6 @@ func ApplyRecommendedSecurityDefaults(fc *config.FileConfig) {}fc.Server.Bind = defaults.Server.Bindfc.Security = defaults.Security- _, _ = config.EnsureFileToken(fc)}func RestoreSecurityDefaults() (string, bool, error) {@@ -27,6 +27,10 @@ func RestoreSecurityDefaults() (string, bool, error) {}before := securityDefaultsSnapshot(fc)ApplyRecommendedSecurityDefaults(fc)+ tokenGenerated, err := config.ProvisionFileToken(fc, configPath)+ if err != nil {+ return "", false, err+ }after := securityDefaultsSnapshot(fc)if reflect.DeepEqual(before, after) {return configPath, false, nil@@ -34,6 +38,9 @@ func RestoreSecurityDefaults() (string, bool, error) {if err := config.SaveFileConfig(fc, configPath); err != nil {return "", false, err}+ if tokenGenerated {+ fmt.Fprintf(os.Stderr, "pinchtab: generated server.token in %s\n", configPath)+ }return configPath, true, nil}