High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the capability-refusal remedy omits the required restart, so following it verbatim returns the identical 403 and an agent loops (PIN-124)
Luigi Agosti2e3d258d4899
diff --git a/cmd/pinchtab/capability_remedy_executable_test.go b/cmd/pinchtab/capability_remedy_executable_test.gonew file mode 100644index 00000000..88cdba05--- /dev/null+++ b/cmd/pinchtab/capability_remedy_executable_test.go@@ -0,0 +1,101 @@+package main++import (+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/routes"+)++// capabilitySettings are the config paths a capability refusal can name, derived+// from the route catalogue. Clipboard is appended because it gates endpoints+// without a catalogue entry, so nothing else would carry it here.+func capabilitySettings(t *testing.T) []string {+ t.Helper()++ settings := []string{"security.allowClipboard"}+ for capability := range routes.CapabilityEndpoints() {+ meta, ok := routes.Meta(capability)+ if !ok {+ t.Errorf("capability %q gates endpoints but has no metadata", capability)+ continue+ }+ settings = append(settings, meta.Setting)+ }+ if len(settings) < 2 {+ t.Fatal("no capability settings found; this test would prove nothing")+ }+ return settings+}++// A remedy an agent cannot execute is not a remedy. This resolves each command in+// the refusal against the REAL command tree — the same rootCmd the binary runs —+// rather than eyeballing the string, because the failure mode being closed is a+// remedy that reads plausibly and dead-ends when run.+func TestCapabilityRemedyCommandsResolveInTheCLI(t *testing.T) {+ for _, setting := range capabilitySettings(t) {+ remedy, _ := httpx.DisabledEndpointDetails(setting)["remedy"].(string)++ commands := strings.Split(remedy, "&&")+ if len(commands) != 2 {+ t.Fatalf("remedy for %s is not two shell-joined commands: %q", setting, remedy)+ }++ for _, command := range commands {+ fields := strings.Fields(strings.TrimSpace(command))+ if len(fields) == 0 || fields[0] != "pinchtab" {+ t.Errorf("remedy command %q does not invoke pinchtab", command)+ continue+ }+ args := fields[1:]++ found, rest, err := rootCmd.Find(args)+ if err != nil {+ t.Errorf("remedy command %q does not resolve: %v", command, err)+ continue+ }+ if !found.Runnable() {+ t.Errorf("remedy command %q resolves to %q, which is a command group and does nothing when run",+ command, found.CommandPath())+ continue+ }+ if found.Args != nil {+ if err := found.Args(found, rest); err != nil {+ t.Errorf("remedy command %q resolves to %q but its arguments %v are rejected: %v",+ command, found.CommandPath(), rest, err)+ }+ }+ }+ }+}++// The other half of executable: `config set <path> true` is only real if the+// config editor accepts that path. A setting present in the schema but missing+// from the editor's field table dead-ends every message that cites it.+func TestCapabilityRemedySettingsAreAcceptedByTheConfigEditor(t *testing.T) {+ for _, setting := range capabilitySettings(t) {+ fc := config.FileConfig{}+ if err := config.SetConfigValue(&fc, setting, "true"); err != nil {+ t.Errorf("the remedy tells the caller to run `pinchtab config set %s true`, which the editor rejects: %v", setting, err)+ }+ }+}++// The restart half must name a command that exists at that exact path. Finding it+// through the tree rather than asserting the literal means a renamed or moved+// verb reds here instead of shipping a remedy nobody can run.+func TestCapabilityRemedyRestartCommandExists(t *testing.T) {+ remedy, _ := httpx.DisabledEndpointDetails("security.allowCookies")["remedy"].(string)++ const restart = "pinchtab server restart"+ if !strings.Contains(remedy, restart) {+ t.Fatalf("remedy = %q, want it to name %q", remedy, restart)+ }+ found, _, err := rootCmd.Find([]string{"server", "restart"})+ if err != nil || found.CommandPath() != "pinchtab server restart" {+ t.Fatalf("`%s` does not resolve to itself (got %q, err %v); the remedy names a command that no longer exists",+ restart, found.CommandPath(), err)+ }+}diff --git a/cmd/pinchtab/cmd_config_actions.go b/cmd/pinchtab/cmd_config_actions.goindex b83468a5..4e537192 100644--- a/cmd/pinchtab/cmd_config_actions.go+++ b/cmd/pinchtab/cmd_config_actions.go@@ -90,7 +90,15 @@ func handleConfigPatch(jsonPatch string) error {// applyPreparedChange reviews validation warnings (gating on confirmSaveAnyway),// saves the change, prints the success message, and emits the restart hint — the// shared mutate path for `config set` and `config patch` so they cannot drift.+//+// Advisories are printed and never gated. They were gated once, when the validator had a+// single severity, and one inert key in a file then aborted every later write — off a TTY,+// where confirmSaveAnyway cannot ask, so agents could not save anything at all. Gating+// still applies to real validation errors, which is what stops an out-of-range port+// slipping through unnoticed.func applyPreparedChange(change *workflow.PreparedChange, warningNoun, abortNoun, successMessage string) error {+ printConfigAdvisories(config.FileConfigAdvisories(change.FileConfig))+if errs := change.ValidationErrors; len(errs) > 0 {fmt.Fprintf(os.Stderr, "Warning: %s causes validation error(s):\n", warningNoun)for _, err := range errs {@@ -110,6 +118,15 @@ func applyPreparedChange(change *workflow.PreparedChange, warningNoun, abortNounreturn nil}+// printConfigAdvisories reports settings the file carries that PinchTab does not act on.+// stderr, so it never lands in piped output a caller is parsing, and no exit code: an+// advisory describes something inert, and there is nothing for the reader to do about it.+func printConfigAdvisories(advisories []string) {+ for _, advisory := range advisories {+ fmt.Fprintf(os.Stderr, "Note: %s\n", advisory)+ }+}+// confirmSaveAnyway prompts on a TTY; on non-TTY (agent / pipe) it returns// false so the validation warning blocks the save by default.func confirmSaveAnyway() bool {@@ -156,12 +173,14 @@ func isSensitiveConfigPath(path string) bool {}func handleConfigValidate() {- configPath, errs, err := workflow.ValidateCurrentFile()+ configPath, errs, advisories, err := workflow.ValidateCurrentFile()if err != nil {fmt.Printf("Error: %v\n", err)os.Exit(1)}+ printConfigAdvisories(advisories)+if len(errs) > 0 {fmt.Printf("Config file has %d error(s):\n", len(errs))for _, err := range errs {diff --git a/cmd/pinchtab/config_advisory_test.go b/cmd/pinchtab/config_advisory_test.gonew file mode 100644index 00000000..49c66c7b--- /dev/null+++ b/cmd/pinchtab/config_advisory_test.go@@ -0,0 +1,117 @@+package main++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++// writeConfigCarryingTheIgnoredKey plants a config whose file holds the inert+// observability.activity.stateDir key, which is the state a user reaches by having set it+// before it was refused.+func writeConfigCarryingTheIgnoredKey(t *testing.T) string {+ t.Helper()++ path := filepath.Join(t.TempDir(), "config.json")+ fc := config.DefaultFileConfig()+ fc.Server.Port = "9867"+ fc.Observability.Activity.StateDir = "/tmp/elsewhere"+ if err := config.SaveFileConfig(&fc, path); err != nil {+ t.Fatalf("SaveFileConfig() error = %v", err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ saved, _, err := config.LoadFileConfig()+ if err != nil {+ t.Fatalf("LoadFileConfig() error = %v", err)+ }+ if saved.Observability.Activity.StateDir == "" {+ t.Fatal("the fixture lost the ignored key, so this test would prove nothing")+ }+ return path+}++// This is the agent shape and the only one that shows the bug: off a TTY confirmSaveAnyway+// cannot ask, so it answers no, and while the ignored key rode the gating list every later+// config write — to any key — was aborted. A TTY-attached run would prompt and pass.+func TestConfigSetSucceedsOffATTYWithTheIgnoredKeyInTheFile(t *testing.T) {+ if isInteractiveTerminal() {+ t.Skip("this case only exists off a TTY; the test binary is attached to one")+ }+ writeConfigCarryingTheIgnoredKey(t)++ var err error+ stderr := captureStderr(t, func() {+ _ = captureStdout(t, func() {+ err = handleConfigSet("server.port", "9999")+ })+ })+ if err != nil {+ t.Fatalf("config set error = %v, want the write to succeed; an inert key must not gate unrelated writes", err)+ }+ if !strings.Contains(stderr, config.ActivityStateDirAdvisory) {+ t.Errorf("stderr = %q, want the advisory reported rather than swallowed", stderr)+ }++ saved, _, loadErr := config.LoadFileConfig()+ if loadErr != nil {+ t.Fatalf("LoadFileConfig() error = %v", loadErr)+ }+ if saved.Server.Port != "9999" {+ t.Errorf("server.port = %q, want the value the write asked for", saved.Server.Port)+ }+ if saved.Observability.Activity.StateDir == "" {+ t.Error("the write cleared the ignored key; this fix reports it, it does not rewrite the user's file")+ }+}++// The guardrail: the fix must not turn a skipped save into a success. A genuinely invalid+// value still aborts off a TTY, non-zero, with the file untouched.+func TestConfigSetStillAbortsOffATTYOnARealValidationError(t *testing.T) {+ if isInteractiveTerminal() {+ t.Skip("this case only exists off a TTY; the test binary is attached to one")+ }+ path := writeConfigCarryingTheIgnoredKey(t)+ before, readErr := os.ReadFile(path)+ if readErr != nil {+ t.Fatal(readErr)+ }++ var err error+ _ = captureStderr(t, func() {+ _ = captureStdout(t, func() {+ err = handleConfigSet("server.port", "99999")+ })+ })+ if err == nil {+ t.Fatal("an out-of-range port saved without complaint; the gate must still hold for real errors")+ }+ if !strings.Contains(err.Error(), "aborted") {+ t.Errorf("error = %v, want the abort that makes the CLI exit non-zero", err)+ }++ after, readErr := os.ReadFile(path)+ if readErr != nil {+ t.Fatal(readErr)+ }+ if string(after) != string(before) {+ t.Error("the aborted write changed the file on disk")+ }+}++// Setting the ignored key itself is still refused on that write — the severity split is+// what keeps carrying it advisory and setting it an error.+func TestConfigSetOfTheIgnoredKeyIsStillRefused(t *testing.T) {+ writeConfigCarryingTheIgnoredKey(t)++ err := handleConfigSet("observability.activity.stateDir", "/tmp/elsewhere-again")+ if err == nil {+ t.Fatal("config set observability.activity.stateDir was accepted")+ }+ if err.Error() != config.ActivityStateDirRefusal {+ t.Errorf("refusal = %q, want %q", err, config.ActivityStateDirRefusal)+ }+}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex bcde617c..ceaa1fdf 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -51,6 +51,7 @@ type parsedConfigFile struct {UnknownFields error // non-fatal: unrecognized nested fieldsUnknownKeys []string // the dotted paths behind UnknownFieldsValidationErrs []error // non-fatal: ValidateFileConfig+ Advisories []string // non-gating: FileConfigAdvisories}func resolveConfigPath() (path, defaultPath string, envOverride bool) {@@ -103,6 +104,7 @@ func readAndParseConfigFile() parsedConfigFile {}if res.FC != nil {res.ValidationErrs = ValidateFileConfig(res.FC)+ res.Advisories = FileConfigAdvisories(res.FC)}return res}@@ -334,6 +336,11 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {for _, e := range res.ValidationErrs {diags = append(diags, LoadDiagnostic{slog.LevelWarn, "config validation error", []any{"path", res.Path, "error", e}})}+ // Reported at load like the rest, but from the non-gating list: the file says+ // something inert, which is worth knowing and is nobody's blocker.+ for _, advisory := range res.Advisories {+ diags = append(diags, LoadDiagnostic{slog.LevelWarn, "config setting has no effect", []any{"path", res.Path, "advisory", advisory}})+ }diags = append(diags, applyFileConfig(cfg, res.FC)...)diff --git a/internal/config/config_methods.go b/internal/config/config_methods.goindex 4249a91b..70079022 100644--- a/internal/config/config_methods.go+++ b/internal/config/config_methods.go@@ -57,10 +57,20 @@ func (cfg *RuntimeConfig) ActivityLogDir() string {const activityLogSubdir = "activity"-// ActivityStateDirRefusal is the one wording behind refusing observability.activity.stateDir-// at `config set` and warning about it at validation: the location is derived, so a file-// value would be accepted and then discarded. It names the derived path and why the-// derivation exists, because a user reaching for the key wants the logs elsewhere and-// deserves to learn why that is not on offer.-const ActivityStateDirRefusal = "observability.activity.stateDir is not settable: activity logs are always written to <server.stateDir>/" + activityLogSubdir +- " so two instances cannot share a log directory; set server.stateDir to move them"+// activityStateDirReason is the fact both surfaces below state, written once. A user+// reaching for observability.activity.stateDir wants the logs elsewhere and deserves to+// learn why that is not on offer, rather than being told only that the key is wrong.+const activityStateDirReason = "activity logs are always written to <server.stateDir>/" + activityLogSubdir ++ " so two instances cannot share a log directory"++// ActivityStateDirRefusal is what `config set` answers. It ends in an action because there+// is one: server.stateDir moves the logs, and `config set server.stateDir <path>` performs+// it.+const ActivityStateDirRefusal = "observability.activity.stateDir is not settable: " + activityStateDirReason ++ "; set server.stateDir to move them"++// ActivityStateDirAdvisory is what a FILE already carrying the key is told, and it+// instructs nothing on purpose. The key is inert, so there is nothing the reader must do —+// and the wording it replaces ("remove the key") named an action no shipped command+// performs, while riding a diagnostic that aborted every later config write off a TTY.+const ActivityStateDirAdvisory = "observability.activity.stateDir is ignored: " + activityStateDirReasondiff --git a/internal/config/validate.go b/internal/config/validate.goindex 429e5cba..a648cb52 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -25,7 +25,15 @@ func (e ValidationError) Error() string {return fmt.Sprintf("%s: %s", e.Field, e.Message)}-// ValidateFileConfig validates a FileConfig and returns all errors found.+// ValidateFileConfig returns the GATING problems in a FileConfig: values that are wrong,+// out of range, or no longer supported. Every caller that decides whether a write may+// proceed gates on this, so anything returned here blocks a save — off a TTY that means an+// agent's write is refused, which is correct for an invalid port and wrong for a key that+// merely does nothing.+//+// Advisories live in FileConfigAdvisories instead. Two severities rather than one is the+// whole point: a diagnostic about an inert key used to ride this list and abort every+// later config write, including writes to unrelated keys.func ValidateFileConfig(fc *FileConfig) []error {var errs []error@@ -313,9 +321,6 @@ func ValidateFileConfig(fc *FileConfig) []error {Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Observability.Activity.RetentionDays),})}- if strings.TrimSpace(fc.Observability.Activity.StateDir) != "" {- errs = append(errs, fmt.Errorf("%s; remove the key, the file value is ignored", ActivityStateDirRefusal))- }if fc.Sessions.Dashboard.IdleTimeoutSec != nil && *fc.Sessions.Dashboard.IdleTimeoutSec <= 0 {errs = append(errs, ValidationError{Field: "sessions.dashboard.idleTimeoutSec",@@ -646,3 +651,24 @@ func validateBrowsersBlock(fc FileConfig) []error {return errs}++// FileConfigAdvisories reports what a config file says that has no effect. These are+// REPORTED, never gating: nothing here means the file is unsafe to load or the next write+// is unsafe to make, so blocking a save on one would refuse work for no reason.+//+// A diagnostic belongs here only when the value is inert — PinchTab reads something else,+// or nothing — and the reader has nothing to fix. Anything the user could get wrong, and+// anything PinchTab will act on, stays in ValidateFileConfig where it gates.+//+// observability.activity.stateDir the path is derived from server.stateDir; the loader+// never reads this key, and `config set` refuses it+func FileConfigAdvisories(fc *FileConfig) []string {+ if fc == nil {+ return nil+ }+ var advisories []string+ if strings.TrimSpace(fc.Observability.Activity.StateDir) != "" {+ advisories = append(advisories, ActivityStateDirAdvisory)+ }+ return advisories+}diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex f6dbafe1..8ef974f2 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -2,6 +2,7 @@ package configimport ("context"+ "log/slog""path/filepath""strings""sync"@@ -1198,7 +1199,11 @@ func TestValidateFileConfig_DefaultSolversAreKnown(t *testing.T) {// diagnostics here — but it no longer does so in silence: the same reason the setter gives// is reported, so the operator learns the value is dead rather than discovering it never// took effect.-func TestValidateFileConfigWarnsAboutActivityStateDirWithoutBreakingTheLoad(t *testing.T) {+// A file that already carries the key keeps loading and still says so — but from the+// non-gating list. It rode the gating list once, and because every caller that decides+// whether a write may proceed gates on that list, one inert key aborted every later config+// write. Which list the diagnostic lives in IS the behaviour here.+func TestActivityStateDirIsAdvisoryRatherThanGating(t *testing.T) {root := t.TempDir()body := `{"server":{"stateDir":` + quoteJSON(root) + `},"observability":{"activity":{"stateDir":"/tmp/elsewhere"}}}`@@ -1208,24 +1213,97 @@ func TestValidateFileConfigWarnsAboutActivityStateDirWithoutBreakingTheLoad(t *tif err != nil {t.Fatalf("LoadFileConfig() error = %v; a file carrying the key must still load", err)}- found := ""+for _, e := range ValidateFileConfig(fc) {if strings.Contains(e.Error(), "observability.activity.stateDir") {- found = e.Error()+ t.Errorf("gating validation reported %q; an inert key must not gate a save", e)+ }+ }++ advisories := FileConfigAdvisories(fc)+ found := ""+ for _, advisory := range advisories {+ if strings.Contains(advisory, "observability.activity.stateDir") {+ found = advisory}}if found == "" {- t.Fatal("validation said nothing about a file carrying observability.activity.stateDir")+ t.Fatalf("advisories = %v, want one naming the ignored key: silently swallowing it is not the fix", advisories)}- if !strings.Contains(found, ActivityStateDirRefusal) {- t.Errorf("validation warning = %q, want it to carry the same reason %q", found, ActivityStateDirRefusal)+ if found != ActivityStateDirAdvisory {+ t.Errorf("advisory = %q, want %q", found, ActivityStateDirAdvisory)}- cfg, _, err := LoadConfig()+ cfg, diags, err := LoadConfig()if err != nil {- t.Fatalf("LoadConfig() error = %v; the warning must not make an existing config unloadable", err)+ t.Fatalf("LoadConfig() error = %v; the advisory must not make an existing config unloadable", err)+ }+ if !hasDiagnostic(diags, slog.LevelWarn, "config setting has no effect") {+ t.Errorf("load diagnostics = %v, want the advisory reported at load", diags)}if want := filepath.Join(root, "activity"); cfg.ActivityLogDir() != want {t.Errorf("ActivityLogDir() = %q, want the derived %q", cfg.ActivityLogDir(), want)}}++// The severity split has to hold in both directions: carrying the key in a file is an+// advisory, and SETTING it is still an error on that write.+func TestSettingTheIgnoredKeyIsStillRefusedWhileCarryingItIsNot(t *testing.T) {+ fc := DefaultFileConfig()+ if err := SetConfigValue(&fc, "observability.activity.stateDir", "/tmp/elsewhere"); err == nil {+ t.Fatal("config set observability.activity.stateDir was accepted")+ }++ carrying := DefaultFileConfig()+ carrying.Observability.Activity.StateDir = "/tmp/elsewhere"+ if errs := ValidateFileConfig(&carrying); len(errs) > 0 {+ t.Errorf("carrying the key produced gating errors %v, want none", errs)+ }+ if len(FileConfigAdvisories(&carrying)) != 1 {+ t.Errorf("advisories = %v, want exactly the ignored-key notice", FileConfigAdvisories(&carrying))+ }+}++// The guardrail on the tier: a genuinely invalid value must keep gating, or this fix trades+// a blocked agent for a config that saves nonsense.+func TestARealValidationErrorStillGates(t *testing.T) {+ fc := DefaultFileConfig()+ fc.Server.Port = "99999"+ fc.Observability.Activity.StateDir = "/tmp/elsewhere"++ errs := ValidateFileConfig(&fc)+ if len(errs) == 0 {+ t.Fatal("an out-of-range port produced no gating error")+ }+ for _, e := range errs {+ if strings.Contains(e.Error(), "observability.activity.stateDir") {+ t.Errorf("gating errors include the advisory %q", e)+ }+ }+}++// The advisory instructs nothing, which is the point of the rewording: the key is inert, so+// there is nothing to do, and the text it replaced named an action no command performs. The+// refusal DOES instruct, and what it names has to be a real, settable key.+func TestTheIgnoredKeyTextsInstructOnlyWhatTheProductCanDo(t *testing.T) {+ for _, banned := range []string{"remove", "delete", "unset"} {+ if strings.Contains(strings.ToLower(ActivityStateDirAdvisory), banned) {+ t.Errorf("advisory = %q, want no %q instruction: no shipped command does that to a key", ActivityStateDirAdvisory, banned)+ }+ }+ for _, want := range []string{"observability.activity.stateDir", "ignored", "<server.stateDir>/activity"} {+ if !strings.Contains(ActivityStateDirAdvisory, want) {+ t.Errorf("advisory = %q, want it to carry %q", ActivityStateDirAdvisory, want)+ }+ }++ if !strings.Contains(ActivityStateDirRefusal, "set server.stateDir") {+ t.Fatalf("refusal = %q, want it to name the setting that moves the logs", ActivityStateDirRefusal)+ }+ // The remedy the refusal names must be a key `config set` accepts, or the text+ // dead-ends the same way "remove the key" did.+ fc := DefaultFileConfig()+ if err := SetConfigValue(&fc, "server.stateDir", t.TempDir()); err != nil {+ t.Errorf("the refusal names server.stateDir but config set rejects it: %v", err)+ }+}diff --git a/internal/config/workflow/mutate.go b/internal/config/workflow/mutate.goindex e312b94c..958b83da 100644--- a/internal/config/workflow/mutate.go+++ b/internal/config/workflow/mutate.go@@ -49,19 +49,21 @@ func SavePreparedChange(change *PreparedChange) error {return nil}-func ValidateCurrentFile() (string, []error, error) {+// ValidateCurrentFile returns the file's gating errors and its non-gating advisories+// separately, because only the first decides whether the file is valid.+func ValidateCurrentFile() (string, []error, []string, error) {configPath := CurrentConfigPath()data, err := os.ReadFile(configPath)if err != nil {- return configPath, nil, fmt.Errorf("read config file: %w", err)+ return configPath, nil, nil, fmt.Errorf("read config file: %w", err)}fc := &config.FileConfig{}if err := json.Unmarshal(data, fc); err != nil {- return configPath, nil, fmt.Errorf("parse config: %w", err)+ return configPath, nil, nil, fmt.Errorf("parse config: %w", err)}- return configPath, config.ValidateFileConfig(fc), nil+ return configPath, config.ValidateFileConfig(fc), config.FileConfigAdvisories(fc), nil}func UpdateValue(path, value string) (*config.RuntimeConfig, bool, error) {diff --git a/internal/handlers/capability_refusal_test.go b/internal/handlers/capability_refusal_test.goindex be348fe4..af11f146 100644--- a/internal/handlers/capability_refusal_test.go+++ b/internal/handlers/capability_refusal_test.go@@ -8,16 +8,17 @@ import ("testing""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/routes")-func capabilityRefusal(t *testing.T, method, path string, call func(*Handlers, http.ResponseWriter, *http.Request)) (string, string) {+// decodeRefusal reads one recorded 403 into its message, code and details. Both+// drives below share it: the endpoint drive, which proves a real handler refuses+// this way, and the writer drive, which sweeps every catalogued capability.+func decodeRefusal(t *testing.T, subject string, w *httptest.ResponseRecorder) (string, string, map[string]any) {t.Helper()- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)- w := httptest.NewRecorder()- call(h, w, httptest.NewRequest(method, path, nil))if w.Code != http.StatusForbidden {- t.Fatalf("%s %s: status = %d, want 403: %s", method, path, w.Code, w.Body.String())+ t.Fatalf("%s: status = %d, want 403: %s", subject, w.Code, w.Body.String())}var resp struct {Error string `json:"error"`@@ -25,12 +26,27 @@ func capabilityRefusal(t *testing.T, method, path string, call func(*Handlers, hDetails map[string]any `json:"details"`}if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode: %v (body=%s)", err, w.Body.String())+ t.Fatalf("%s: decode: %v (body=%s)", subject, err, w.Body.String())}if setting, _ := resp.Details["setting"].(string); setting == "" {- t.Fatalf("%s %s: refusal dropped details.setting: %v", method, path, resp.Details)+ t.Fatalf("%s: refusal dropped details.setting: %v", subject, resp.Details)}- return resp.Error, resp.Code+ return resp.Error, resp.Code, resp.Details+}++func capabilityRefusal(t *testing.T, method, path string, call func(*Handlers, http.ResponseWriter, *http.Request)) (string, string, map[string]any) {+ t.Helper()++ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ w := httptest.NewRecorder()+ call(h, w, httptest.NewRequest(method, path, nil))+ return decodeRefusal(t, method+" "+path, w)+}++// remedyFor is the one place the expected remedy is spelled, so every assertion+// below compares against the same contract rather than its own copy.+func remedyFor(setting string) string {+ return "pinchtab config set " + setting + " true && pinchtab server restart"}// /storage is gated by the stateExport capability, so the old wording sent the@@ -68,7 +84,7 @@ func TestCapabilityRefusalNamesTheCapabilityAndKeepsTheCode(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- message, code := capabilityRefusal(t, tt.method, tt.path, tt.call)+ message, code, _ := capabilityRefusal(t, tt.method, tt.path, tt.call)if code != tt.wantCode {t.Fatalf("code = %q, want %q", code, tt.wantCode)@@ -85,3 +101,170 @@ func TestCapabilityRefusalNamesTheCapabilityAndKeepsTheCode(t *testing.T) {})}}++// The dead end this closes: the remedy stopped at the config write. Writing the+// setting is a successful no-op for the caller — the security block is read at+// boot — so the identical 403 came back, and the agent reading it has no other+// instruction to try.+//+// The scope is derived from the route catalogue rather than listed here, so a+// capability added there is covered the day it is added. Recording and clipboard+// are appended because neither goes through writeCapabilityDisabled — recording+// keeps its own error code, clipboard has no catalogue entry — and those two are+// exactly where the guidance drifted before.+func TestEveryCapabilityRefusalCarriesTheRunnableRemedy(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ type gate struct {+ name string+ setting string+ write func(w *httptest.ResponseRecorder)+ }+ var gates []gate++ caps := routes.CapabilityEndpoints()+ if len(caps) == 0 {+ t.Fatal("the route catalogue reports no capability-gated endpoints; this census would pass vacuously")+ }+ for capability := range caps {+ meta, ok := routes.Meta(capability)+ if !ok {+ t.Errorf("capability %q gates endpoints but has no metadata, so its refusal can name no setting", capability)+ continue+ }+ gates = append(gates, gate{+ name: string(capability),+ setting: meta.Setting,+ write: func(w *httptest.ResponseRecorder) { h.writeCapabilityDisabled(w, capability) },+ })+ }++ screencast, _ := routes.Meta(routes.CapScreencast)+ gates = append(gates,+ gate{+ name: "recording",+ setting: screencast.Setting,+ write: func(w *httptest.ResponseRecorder) {+ h.HandleRecordStart(w, httptest.NewRequest(http.MethodPost, "/record/start", nil))+ },+ },+ gate{+ name: "clipboard",+ setting: clipboardSetting,+ write: func(w *httptest.ResponseRecorder) { writeClipboardDisabled(w) },+ },+ )++ for _, g := range gates {+ t.Run(g.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ g.write(w)+ _, _, details := decodeRefusal(t, g.name, w)++ if got, _ := details["setting"].(string); got != g.setting {+ t.Errorf("details.setting = %q, want %q", got, g.setting)+ }+ remedy, _ := details["remedy"].(string)+ if remedy == "" {+ t.Fatalf("%s refusal carries no remedy at all, so the caller is told nothing to try: %v", g.name, details)+ }+ if remedy != remedyFor(g.setting) {+ t.Errorf("remedy = %q, want %q; a gate building its own string drifts from every other capability", remedy, remedyFor(g.setting))+ }+ })+ }+}++// Recording gates on the screencast setting but answers with its own code and+// label. Routing it through the shared builder must not have collapsed that+// distinction — a client matching recording_disabled still has to see it.+func TestRecordingKeepsItsOwnCodeWhileSharingTheRemedy(t *testing.T) {+ message, code, details := capabilityRefusal(t, http.MethodPost, "/record/start",+ func(h *Handlers, w http.ResponseWriter, r *http.Request) { h.HandleRecordStart(w, r) })++ if code != "recording_disabled" {+ t.Errorf("code = %q, want recording_disabled", code)+ }+ if !strings.Contains(message, "recording capability") {+ t.Errorf("message = %q, want it to still name the recording capability", message)+ }+ if got, _ := details["remedy"].(string); got != remedyFor("security.allowScreencast") {+ t.Errorf("remedy = %q, want the shared one", got)+ }+}++// The read and write clipboard gates were byte-identical bodies, which is how one+// of them could have been fixed alone. They now share a writer; this asserts the+// two refusals cannot diverge again.+func TestClipboardReadAndWriteRefusalsAreIdentical(t *testing.T) {+ read, readCode, readDetails := capabilityRefusal(t, http.MethodGet, "/clipboard/read",+ func(h *Handlers, w http.ResponseWriter, r *http.Request) { h.HandleClipboardRead(w, r) })+ write, writeCode, writeDetails := capabilityRefusal(t, http.MethodPost, "/clipboard/write",+ func(h *Handlers, w http.ResponseWriter, r *http.Request) { h.HandleClipboardWrite(w, r) })++ if read != write || readCode != writeCode {+ t.Errorf("clipboard read and write refuse differently:\n read: %q / %q\nwrite: %q / %q", read, readCode, write, writeCode)+ }+ for _, key := range []string{"setting", "hint", "remedy"} {+ if readDetails[key] != writeDetails[key] {+ t.Errorf("clipboard details[%q] differs: read=%v write=%v", key, readDetails[key], writeDetails[key])+ }+ }+ if got, _ := readDetails["remedy"].(string); got != remedyFor(clipboardSetting) {+ t.Errorf("clipboard remedy = %q, want %q", got, remedyFor(clipboardSetting))+ }+}++// Refuse, follow the remedy, retry. The config write and the restart are both+// modelled: SetConfigValue is what `pinchtab config set` performs, and+// ApplyFileConfigToRuntime is what a restart does with the resulting file — the+// running config is built from it at boot and never rebuilt on an edit, which is+// precisely why the remedy has to name the restart. Doing only the first half+// leaves the gate shut, which is the loop the caller was stuck in.+func TestFollowingTheRemedyClearsTheRefusal(t *testing.T) {+ cfg := &config.RuntimeConfig{}+ h := New(&mockBridge{}, cfg, nil, nil, nil)++ w := httptest.NewRecorder()+ h.HandleGetCookies(w, httptest.NewRequest(http.MethodGet, "/cookies", nil))+ _, code, details := decodeRefusal(t, "GET /cookies", w)+ if code != "cookies_disabled" {+ t.Fatalf("code = %q, want cookies_disabled", code)+ }+ setting, _ := details["setting"].(string)+ remedy, _ := details["remedy"].(string)++ fc := config.FileConfig{}+ if err := config.SetConfigValue(&fc, setting, "true"); err != nil {+ t.Fatalf("the remedy's config write fails: %v (remedy=%q)", err, remedy)+ }+ if !strings.Contains(remedy, "pinchtab server restart") {+ t.Fatalf("remedy = %q carries no restart, so the retry below would model a step the caller was never told to take", remedy)+ }+ config.ApplyFileConfigToRuntime(cfg, &fc)++ retry := httptest.NewRecorder()+ h.HandleGetCookies(retry, httptest.NewRequest(http.MethodGet, "/cookies", nil))+ if retry.Code == http.StatusForbidden && strings.Contains(retry.Body.String(), "cookies_disabled") {+ t.Fatalf("after following the remedy the identical refusal came back: %s", retry.Body.String())+ }+}++// The config write ALONE must not clear the gate. If it did, the restart in the+// remedy would be noise and this whole card would be wrong — so the negative is+// what makes the test above evidence for naming the restart rather than against.+func TestTheConfigWriteAloneDoesNotClearTheRefusal(t *testing.T) {+ cfg := &config.RuntimeConfig{}+ h := New(&mockBridge{}, cfg, nil, nil, nil)++ fc := config.FileConfig{}+ if err := config.SetConfigValue(&fc, "security.allowCookies", "true"); err != nil {+ t.Fatalf("config set: %v", err)+ }++ w := httptest.NewRecorder()+ h.HandleGetCookies(w, httptest.NewRequest(http.MethodGet, "/cookies", nil))+ if _, code, _ := decodeRefusal(t, "GET /cookies after config write only", w); code != "cookies_disabled" {+ t.Fatalf("code = %q; the running config picked the edit up without a restart, so the remedy should stop naming one", code)+ }+}diff --git a/internal/handlers/clipboard.go b/internal/handlers/clipboard.goindex 19ce2320..9afff0db 100644--- a/internal/handlers/clipboard.go+++ b/internal/handlers/clipboard.go@@ -42,6 +42,20 @@ func (h *Handlers) clipboardEnabled() bool {return h != nil && h.Config != nil && h.Config.AllowClipboard}+// clipboardSetting is the config path gating the clipboard endpoints. Clipboard+// has no entry in the route catalogue's capability table, so unlike every other+// gate its setting has no owner there and is declared here instead.+const clipboardSetting = "security.allowClipboard"++// writeClipboardDisabled emits the clipboard capability refusal. It exists so the+// read and write gates cannot drift apart, and so the clipboard carries the same+// guidance — including the restart — as every catalogued capability.+func writeClipboardDisabled(w http.ResponseWriter) {+ httpx.ErrorCode(w, 403, "clipboard_disabled",+ httpx.DisabledEndpointMessage("clipboard", clipboardSetting), false,+ httpx.DisabledEndpointDetails(clipboardSetting))+}+func rejectClipboardTabID(w http.ResponseWriter, r *http.Request) bool {if strings.TrimSpace(r.URL.Query().Get("tabId")) != "" {httpx.Error(w, http.StatusBadRequest, fmt.Errorf("tabId is not supported for shared clipboard operations"))@@ -53,9 +67,7 @@ func rejectClipboardTabID(w http.ResponseWriter, r *http.Request) bool {// HandleClipboardRead reads text from the clipboard.func (h *Handlers) HandleClipboardRead(w http.ResponseWriter, r *http.Request) {if !h.clipboardEnabled() {- httpx.ErrorCode(w, 403, "clipboard_disabled", httpx.DisabledEndpointMessage("clipboard", "security.allowClipboard"), false, map[string]any{- "setting": "security.allowClipboard",- })+ writeClipboardDisabled(w)return}if rejectClipboardTabID(w, r) {@@ -79,9 +91,7 @@ func (h *Handlers) HandleClipboardRead(w http.ResponseWriter, r *http.Request) {// HandleClipboardWrite writes text to the clipboard.func (h *Handlers) HandleClipboardWrite(w http.ResponseWriter, r *http.Request) {if !h.clipboardEnabled() {- httpx.ErrorCode(w, 403, "clipboard_disabled", httpx.DisabledEndpointMessage("clipboard", "security.allowClipboard"), false, map[string]any{- "setting": "security.allowClipboard",- })+ writeClipboardDisabled(w)return}if rejectClipboardTabID(w, r) {diff --git a/internal/handlers/record_handlers.go b/internal/handlers/record_handlers.goindex 992d6678..8052d730 100644--- a/internal/handlers/record_handlers.go+++ b/internal/handlers/record_handlers.go@@ -12,19 +12,20 @@ import ("github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/fileout""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/routes""github.com/pinchtab/pinchtab/internal/session")// HandleRecordStart starts a recording session for a tab.func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {if !h.Config.AllowScreencast {+ // Recording keeps its own label and error code — the caller asked to+ // record, not to screencast — but the setting and the guidance come from+ // the shared owners, so it cannot drift from every other capability gate.+ meta, _ := routes.Meta(routes.CapScreencast)httpx.ErrorCode(w, 403, "recording_disabled",- httpx.DisabledEndpointMessage("recording", "security.allowScreencast"), false,- map[string]any{- "setting": "security.allowScreencast",- "hint": "Recording requires screen capture to be enabled.",- "remedy": "pinchtab config set security.allowScreencast true",- })+ httpx.DisabledEndpointMessage("recording", meta.Setting), false,+ httpx.DisabledEndpointDetails(meta.Setting))return}diff --git a/internal/handlers/security.go b/internal/handlers/security.goindex 3800ec0a..3930a131 100644--- a/internal/handlers/security.go+++ b/internal/handlers/security.go@@ -21,7 +21,7 @@ func (h *Handlers) writeCapabilityDisabled(w http.ResponseWriter, cap routes.Capmeta, _ := routes.Meta(cap)httpx.ErrorCode(w, http.StatusForbidden, meta.DisabledCode,httpx.DisabledEndpointMessage(meta.Label, meta.Setting), false,- map[string]any{"setting": meta.Setting})+ httpx.DisabledEndpointDetails(meta.Setting))}// capState builds the /security projection for a capability-gated endpoint@@ -77,8 +77,8 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {// clipboard has no capability gate in the route catalog, so its metadata stays local."clipboard": {Enabled: h.clipboardEnabled(),- Setting: "security.allowClipboard",- Message: httpx.DisabledEndpointMessage("clipboard", "security.allowClipboard"),+ Setting: clipboardSetting,+ Message: httpx.DisabledEndpointMessage("clipboard", clipboardSetting),Paths: []string{"GET /clipboard/read", "POST /clipboard/write", "POST /clipboard/copy", "GET /clipboard/paste"},},"stateExport": capState(routes.CapStateExport, h.stateExportEnabled(),diff --git a/internal/httpx/endpointlock.go b/internal/httpx/endpointlock.goindex 7e1a97c4..1cd666c2 100644--- a/internal/httpx/endpointlock.go+++ b/internal/httpx/endpointlock.go@@ -13,13 +13,29 @@ func DisabledEndpointMessage(capability, setting string) string {return fmt.Sprintf("this endpoint requires the %s capability; enable %s in config to use it", capability, setting)}+// DisabledEndpointDetails builds the error details every capability refusal+// carries, so the guidance is written once rather than restated at each gate.+//+// The remedy names the restart because writing the config is not enough: the+// security block is snapshotted at boot and is not rebuilt on a config edit, so+// enabling a capability never takes effect until the server restarts. Without+// the restart a caller who follows the remedy verbatim gets the identical 403+// back, and an agent — which reads this refusal, not the config command's+// stdout — has no exit from that loop. The two commands are joined with && so+// the remedy is one line a shell accepts, not prose to be interpreted.+func DisabledEndpointDetails(setting string) map[string]any {+ return map[string]any{+ "setting": setting,+ "hint": fmt.Sprintf("Enable %s to use this feature.", setting),+ "remedy": fmt.Sprintf("pinchtab config set %s true && pinchtab server restart", setting),+ }+}+// DisabledEndpointHandler returns a handler that reports a capability gate lock.func DisabledEndpointHandler(capability, setting, code string) http.HandlerFunc {return func(w http.ResponseWriter, _ *http.Request) {- ErrorCode(w, http.StatusForbidden, code, DisabledEndpointMessage(capability, setting), false, map[string]any{- "setting": setting,- "hint": fmt.Sprintf("Enable %s to use this feature.", setting),- "remedy": fmt.Sprintf("pinchtab config set %s true", setting),- })+ ErrorCode(w, http.StatusForbidden, code,+ DisabledEndpointMessage(capability, setting), false,+ DisabledEndpointDetails(setting))}}diff --git a/internal/httpx/endpointlock_test.go b/internal/httpx/endpointlock_test.goindex 242f979d..737bdc7b 100644--- a/internal/httpx/endpointlock_test.go+++ b/internal/httpx/endpointlock_test.go@@ -41,8 +41,8 @@ func TestDisabledEndpointHandlerIncludesHintAndRemedy(t *testing.T) {if remedy == "" {t.Fatal("expected non-empty remedy in details")}- if remedy != "pinchtab config set security.allowScreencast true" {- t.Fatalf("remedy = %q, want config set command", remedy)+ if remedy != "pinchtab config set security.allowScreencast true && pinchtab server restart" {+ t.Fatalf("remedy = %q, want the config set AND the restart that applies it", remedy)}}@@ -100,10 +100,46 @@ func TestDisabledEndpointHandlerKeepsSettingHintAndRemedy(t *testing.T) {for key, want := range map[string]string{"setting": "security.allowStateExport","hint": "Enable security.allowStateExport to use this feature.",- "remedy": "pinchtab config set security.allowStateExport true",+ "remedy": "pinchtab config set security.allowStateExport true && pinchtab server restart",} {if got, _ := resp.Details[key].(string); got != want {t.Fatalf("details[%q] = %q, want %q", key, got, want)}}}++// The defect this pins: the remedy used to stop at the config write. Writing the+// setting is a successful no-op for the caller — the security block is read at+// boot, so the very same 403 comes back — and the caller reading this refusal is+// an agent that has no other instruction to try. The properties, not the+// sentence: both commands present, the config write FIRST, joined so a shell can+// run the string verbatim, and no prose asking the reader to interpret anything.+func TestDisabledEndpointRemedyIsOneRunnableLineEndingInTheRestart(t *testing.T) {+ for _, setting := range []string{"security.allowCookies", "security.allowStateExport", "security.allowClipboard"} {+ remedy, _ := DisabledEndpointDetails(setting)["remedy"].(string)++ configCmd := "pinchtab config set " + setting + " true"+ restartCmd := "pinchtab server restart"++ if strings.Contains(remedy, "\n") {+ t.Errorf("remedy for %s spans lines, so it cannot be run verbatim: %q", setting, remedy)+ }+ if !strings.Contains(remedy, configCmd) {+ t.Errorf("remedy for %s does not enable the setting: %q", setting, remedy)+ }+ if !strings.Contains(remedy, restartCmd) {+ t.Errorf("remedy for %s omits the restart, so following it verbatim returns the identical 403: %q", setting, remedy)+ }+ if strings.Index(remedy, configCmd) > strings.Index(remedy, restartCmd) {+ t.Errorf("remedy for %s restarts before writing the setting, so the restart applies nothing: %q", setting, remedy)+ }+ if !strings.Contains(remedy, "&&") {+ t.Errorf("remedy for %s joins its two commands with prose rather than a shell operator: %q", setting, remedy)+ }+ for _, prose := range []string{" then", "then:", "after that", "first ", "next "} {+ if strings.Contains(remedy, prose) {+ t.Errorf("remedy for %s contains prose %q an agent would have to interpret: %q", setting, prose, remedy)+ }+ }+ }+}