High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(config): serve only the modes the validator accepts, folding case, and stop the load on one it cannot interpret (PIN-298)
Luigi Agosti372cde3d175d
diff --git a/docs/reference/sessions.md b/docs/reference/sessions.mdindex 31dfc296..fd589e1f 100644--- a/docs/reference/sessions.md+++ b/docs/reference/sessions.md@@ -34,6 +34,18 @@ In `config.json`:| `preferred` | Both bearer and session auth accepted (default) || `required` | **Not implemented — refused at config load.** It would mean only session auth is accepted for agents, but the bearer token and the dashboard cookie still authenticate, so the value is refused rather than accepted and ignored |+Mode values are case-insensitive and surrounding space is ignored: `"Off"`, `"OFF"`+and `" off "` all mean off. A capitalisation slip in this switch turns agent sessions+off, as written, rather than being read as anything else.++**A mode the server cannot interpret stops it.** `"required"`, a typo, or any other+value outside the table is refused at load: the process reports the field and exits+instead of starting with a posture chosen on your behalf — the failure a warning-only+load would hide is agent sessions left serving. The daemon unit and auto-start run a+bare `pinchtab server`, so the config file is the whole input and the exit is where you+see it. `pinchtab config set sessions.agent.mode off` still works on a config the+server refuses to load, so the repair does not need a hand edit.+## Lifecycle1. **Create** — `pinchtab session create --agent-id <id>` (or `POST /sessions` directly)diff --git a/internal/config/config_apply_census_test.go b/internal/config/config_apply_census_test.goindex 75fd9c3c..829236bd 100644--- a/internal/config/config_apply_census_test.go+++ b/internal/config/config_apply_census_test.go@@ -8,6 +8,7 @@ import ("testing""github.com/pinchtab/pinchtab/internal/browsers"+ "github.com/pinchtab/pinchtab/internal/session")// refusedKey records a key the product deliberately does not carry: patch writes the@@ -58,6 +59,7 @@ var censusValueFor = map[string]string{"security.trustedProxyCIDRs": "10.0.0.0/8","security.trustedResolveCIDRs": "10.0.0.0/8","autoSolver.solvers": "semantic",+ "sessions.agent.mode": session.ModeOff,}// censusCandidates are tried in order for every other key: the first one the setter takesdiff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 14c8c04e..7432fd38 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -2,6 +2,7 @@ package configimport ("encoding/json"+ "errors""fmt""log/slog""os"@@ -335,6 +336,9 @@ 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}})}+ if err := fatalValidationError(res.ValidationErrs); err != nil {+ return cfg, diags, err+ }// 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 {@@ -350,6 +354,20 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {return cfg, diags, nil}+// fatalValidationError returns the first validation error that must stop the load.+// The class is declared by the error itself (ValidationError.FatalAtLoad), never+// inferred here from a field name or a message, so adding a member is a decision+// taken where the rule is written.+func fatalValidationError(errs []error) error {+ for _, e := range errs {+ var ve ValidationError+ if errors.As(e, &ve) && ve.FatalAtLoad {+ return fmt.Errorf("config cannot be loaded: %w", e)+ }+ }+ return nil+}+// ConfigFileStatus reports on-disk config state without invoking Load (used by `pinchtab doctor`).type ConfigFileStatus struct {Path stringdiff --git a/internal/config/validate.go b/internal/config/validate.goindex ca446c06..06c3039c 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -25,18 +25,20 @@ import (// operator-visible and small-radius (the default is preferred, so only an explicit// setter is hit) and it replaces a silent security misapprehension with a loud one.func validateAgentSessionMode(mode string) []error {- switch mode {+ switch session.NormalizeMode(mode) {case "", session.ModeOff, session.ModePreferred:return nilcase session.ModeRequired:return []error{ValidationError{- Field: "sessions.agent.mode",- Message: fmt.Sprintf("%q is not implemented: the server bearer token and the dashboard cookie still authenticate, so this value cannot deliver the session-only auth it names (must be off or preferred)", session.ModeRequired),+ Field: "sessions.agent.mode",+ Message: fmt.Sprintf("%q is not implemented: the server bearer token and the dashboard cookie still authenticate, so this value cannot deliver the session-only auth it names (must be off or preferred)", session.ModeRequired),+ FatalAtLoad: true,}}default:return []error{ValidationError{- Field: "sessions.agent.mode",- Message: fmt.Sprintf("invalid value %q (must be off or preferred)", mode),+ Field: "sessions.agent.mode",+ Message: fmt.Sprintf("invalid value %q (must be off or preferred)", mode),+ FatalAtLoad: true,}}}}@@ -44,6 +46,19 @@ func validateAgentSessionMode(mode string) []error {type ValidationError struct {Field stringMessage string++ // FatalAtLoad stops the process at load instead of warning past the problem.+ // Membership is an explicit opt-in with a reason per field, so the class stays+ // readable in the type rather than being re-decided from a message:+ //+ // sessions.agent.mode — an auth posture. A value the server cannot interpret+ // would otherwise be read as the default and leave agent sessions serving,+ // which is the misapprehension refusing it exists to end. Choosing a posture+ // on the operator's behalf is what a load must not do.+ //+ // It is the only member. Every other validation error warns at load and gates+ // only the write paths, which is what keeps an inert key from aborting a server.+ FatalAtLoad bool}func (e ValidationError) Error() string {diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex b471fa0d..3108e29f 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -1,7 +1,10 @@package configimport (+ "errors"+ "fmt""log/slog"+ "os""path/filepath""strings""sync"@@ -13,6 +16,7 @@ import (_ "github.com/pinchtab/pinchtab/internal/browsers/chrome"_ "github.com/pinchtab/pinchtab/internal/browsers/cloak"_ "github.com/pinchtab/pinchtab/internal/browsers/ghostchrome"+ "github.com/pinchtab/pinchtab/internal/session")func TestValidateFileConfig_Valid(t *testing.T) {@@ -1320,7 +1324,14 @@ func TestValidateFileConfig_AgentSessionMode(t *testing.T) {{"preferred", false, ""},{"required", true, "not implemented"},{"nonsense", true, "invalid value"},- {"Off", true, "invalid value"},+ {"prefered", true, "invalid value"},+ // Case and surrounding space are read the way every other enum in this+ // file is read, so a capitalisation slip in an auth switch means what the+ // operator wrote instead of being refused as a typo.+ {"Off", false, ""},+ {"OFF", false, ""},+ {" off ", false, ""},+ {" Preferred ", false, ""},} {fc := &FileConfig{Sessions: SessionsFileConfig{Agent: AgentSessionFileConfig{Mode: tt.mode}}}errs := ValidateFileConfig(fc)@@ -1339,6 +1350,109 @@ func TestValidateFileConfig_AgentSessionMode(t *testing.T) {if !strings.Contains(message, tt.wantSays) {t.Errorf("mode=%q: refusal %q does not say %q", tt.mode, message, tt.wantSays)}+ var ve ValidationError+ if !errors.As(errs[0], &ve) || !ve.FatalAtLoad {+ t.Errorf("mode=%q: the refusal does not declare itself fatal at load, so a server would warn and then pick a posture on the operator's behalf", tt.mode)+ }+ }+}++// The two readers of ModeServes answer at different points — the live store and the+// raw file value the restart-reason comparison comes from — so they are asserted+// together. A fold applied at only one of them would disagree for "Off", and the+// disagreement is invisible from either side alone.+func TestBothModeConsumersAgreeOnEveryValue(t *testing.T) {+ enabled := true+ for _, tt := range []struct {+ mode string+ want bool+ }{+ {"", true},+ {"preferred", true},+ {" Preferred ", true},+ {"off", false},+ {"Off", false},+ {"OFF", false},+ {" off ", false},+ {"required", false},+ {"prefered", false},+ } {+ fromFile := SessionsFileConfig{Agent: AgentSessionFileConfig{Enabled: &enabled, Mode: tt.mode}}.AgentEnabled()+ fromStore := session.NewStore(session.Config{Enabled: true, Mode: tt.mode}).Enabled()+ if fromFile != tt.want || fromStore != tt.want {+ t.Errorf("mode=%q: file config says %v, the live store says %v, want %v — one predicate, two readers, and a value the validator refuses must never serve",+ tt.mode, fromFile, fromStore, tt.want)+ }+ }+}++// The claim the previous card published to operators and the load path did not keep:+// a config the server cannot interpret stops it, rather than warning and then reading+// the value as the default. Driven through a real file and a real load, because the+// validator's return value was already correct while the outcome was not.+func TestAModeTheServerCannotInterpretStopsTheLoad(t *testing.T) {+ for _, tt := range []struct {+ mode string+ wantFatal bool+ }{+ {"required", true},+ {"nonsense", true},+ {"Off", false},+ {"preferred", false},+ } {+ path := filepath.Join(t.TempDir(), "config.json")+ body := fmt.Sprintf(`{"server":{"port":"9867"},"sessions":{"agent":{"mode":%q}}}`, tt.mode)+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ cfg, _, err := LoadConfig()+ if !tt.wantFatal {+ if err != nil {+ t.Errorf("mode=%q refused the load: %v", tt.mode, err)+ }+ continue+ }+ if err == nil {+ t.Errorf("mode=%q loaded and the server would run with agent sessions %v; a posture it cannot interpret must not be chosen on the operator's behalf",+ tt.mode, cfg.Sessions.Agent.Enabled)+ continue+ }+ if !strings.Contains(err.Error(), "sessions.agent.mode") {+ t.Errorf("mode=%q: the fatal error %q does not name the field to fix", tt.mode, err)+ }+ }+}++// A fatal load must not lock the operator out of the command that repairs it. The+// editor reads and writes the file directly and never builds a RuntimeConfig, so+// `config set sessions.agent.mode off` works on a config the server refuses to+// start on — pinned here because routing the editor through the runtime load would+// be an invisible change that leaves a hand edit as the only way out.+func TestTheEditorStillRepairsAConfigTheLoadRefuses(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"9867"},"sessions":{"agent":{"mode":"required"}}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)++ if _, _, err := LoadConfig(); err == nil {+ t.Fatal("the load accepted the unusable mode, so this test is not standing on the state it is about")+ }++ fc, loadedPath, err := LoadFileConfig()+ if err != nil {+ t.Fatalf("the editor cannot even read the file it must repair: %v", err)+ }+ if err := SetConfigValue(fc, "sessions.agent.mode", session.ModeOff); err != nil {+ t.Fatalf("the editor refused the repair: %v", err)+ }+ if err := SaveFileConfig(fc, loadedPath); err != nil {+ t.Fatalf("the editor could not save the repair: %v", err)+ }+ if _, _, err := LoadConfig(); err != nil {+ t.Fatalf("the repaired config still refuses to load: %v", err)}}diff --git a/internal/server/agent_session_live_config_test.go b/internal/server/agent_session_live_config_test.goindex 05f83a41..5dec2bcd 100644--- a/internal/server/agent_session_live_config_test.go+++ b/internal/server/agent_session_live_config_test.go@@ -148,6 +148,11 @@ func TestModeOffDisablesAgentSessionsExactlyAsEnabledFalseDoes(t *testing.T) {[]string{"sessions.agent.mode"}, "sessions.agent.enabled"},{"both off", func(fc *config.FileConfig) { agentSessionsEnabled(fc, false); fc.Sessions.Agent.Mode = "off" },[]string{"sessions.agent.enabled", "sessions.agent.mode"}, ""},+ // A capitalisation slip in an auth switch means what the operator wrote: the+ // save is accepted rather than refused, and the family goes off. Refusing it+ // as a typo would leave agent sessions serving on a warning.+ {"mode Off", func(fc *config.FileConfig) { fc.Sessions.Agent.Mode = "Off" },+ []string{"sessions.agent.mode"}, "sessions.agent.enabled"},} {t.Run(tc.name, func(t *testing.T) {f := newFrontDoor(t, nil)diff --git a/internal/session/store_test.go b/internal/session/store_test.goindex d63f4351..732d6ee8 100644--- a/internal/session/store_test.go+++ b/internal/session/store_test.go@@ -399,9 +399,44 @@ func TestEnabledFoldsModeAndEnabled(t *testing.T) {{"enabled, off", Config{Enabled: true, Mode: ModeOff}, false},{"disabled, preferred", Config{Enabled: false, Mode: ModePreferred}, false},{"disabled, off", Config{Enabled: false, Mode: ModeOff}, false},+ // Every value the validator refuses, and the case variants it accepts as+ // off. The table used to cover only the two canonical spellings, so a+ // predicate that served everything but exact "off" looked correct here.+ {"enabled, required", Config{Enabled: true, Mode: ModeRequired}, false},+ {"enabled, a typo", Config{Enabled: true, Mode: "prefered"}, false},+ {"enabled, off capitalised", Config{Enabled: true, Mode: "Off"}, false},+ {"enabled, off shouted", Config{Enabled: true, Mode: "OFF"}, false},+ {"enabled, off with space", Config{Enabled: true, Mode: " off "}, false},+ {"enabled, preferred capitalised", Config{Enabled: true, Mode: " Preferred "}, true},} {if got := NewStore(tt.cfg).Enabled(); got != tt.want {t.Errorf("%s: Enabled() = %v, want %v", tt.name, got, tt.want)}}}++// ModeServes is an allowlist over the normalized value, not "anything but off".+// A denylist reads every unvalidated value — a typo, a posture the server does not+// implement — as the default and leaves an auth mechanism serving, which is the+// state refusing those values exists to end.+func TestModeServesOnlyTheValuesTheValidatorAccepts(t *testing.T) {+ for _, tt := range []struct {+ mode string+ want bool+ }{+ {"", true},+ {ModePreferred, true},+ {" Preferred ", true},+ {ModeOff, false},+ {"Off", false},+ {"OFF", false},+ {" off ", false},+ {ModeRequired, false},+ {"prefered", false},+ } {+ if got := ModeServes(tt.mode); got != tt.want {+ t.Errorf("ModeServes(%q) = %v, want %v — a value the validator does not accept must never serve, and a case variant of off must mean off",+ tt.mode, got, tt.want)+ }+ }+}