High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(config): make sessions.agent.mode decide, refusing "required" as unimplemented (PIN-290)
Luigi Agostif25f76a47e80
diff --git a/docs/guides/agent-identity.md b/docs/guides/agent-identity.mdindex a1698d65..0cf4226b 100644--- a/docs/guides/agent-identity.md+++ b/docs/guides/agent-identity.md@@ -141,7 +141,7 @@ curl -X POST http://localhost:9867/sessions/ses_e6ac8132fe7e7016/revoke \| Setting | Default | Description ||---------|---------|-------------|| `sessions.agent.enabled` | `true` | Enable agent sessions |-| `sessions.agent.mode` | `preferred` | Auth mode: `off`, `preferred`, `required` |+| `sessions.agent.mode` | `preferred` | Auth mode. `preferred` serves agent sessions alongside the server token; `off` disables them exactly as `enabled: false` does. `required` is **not implemented** and is refused at config load — the bearer token and the dashboard cookie still authenticate, so the value cannot deliver the session-only auth it names || `sessions.agent.idleTimeoutSec` | `1800` (30m) | Session expires after this many seconds of inactivity || `sessions.agent.maxLifetimeSec` | `86400` (24h) | Hard session expiry |diff --git a/docs/reference/sessions.md b/docs/reference/sessions.mdindex 8050e862..31dfc296 100644--- a/docs/reference/sessions.md+++ b/docs/reference/sessions.md@@ -30,9 +30,9 @@ In `config.json`:| Mode | Behavior ||------|----------|-| `off` | Agent sessions disabled |+| `off` | Agent sessions disabled, exactly as `enabled: false` || `preferred` | Both bearer and session auth accepted (default) |-| `required` | Only session auth accepted for agents |+| `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 |## Lifecycle@@ -52,7 +52,9 @@ In `config.json`:>> The session management API (`/sessions`) still has admin-style authority for create, list, and inspect operations. Any caller authenticated with the server bearer token or a valid dashboard cookie can manage sessions for any agent. Session-authenticated callers are blocked from dashboard/admin endpoint families, but a session without explicit grants can still access the normal non-admin automation surface by default.>-> In untrusted or shared environments where agent sessions are not needed, disable them entirely by setting `"enabled": false` or `"mode": "off"` in your config to reduce the auth surface.+> In untrusted or shared environments where agent sessions are not needed, disable them entirely by setting `"enabled": false` or `"mode": "off"` in your config to reduce the auth surface. The two are one switch: either refuses an existing session token at the front door and answers the whole `/sessions` family with `sessions_disabled`.+>+> `"mode": "required"` is not implemented and is refused at config load rather than accepted and ignored: the server bearer token and the dashboard cookie still authenticate, so setting it would leave you believing session auth is the only way in.### Session Grantsdiff --git a/internal/config/config_types.go b/internal/config/config_types.goindex fa2008aa..008099fe 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -1,6 +1,10 @@package config-import "time"+import (+ "time"++ "github.com/pinchtab/pinchtab/internal/session"+)const defaultPort = "9867"@@ -300,9 +304,16 @@ type SessionsFileConfig struct {// when the file leaves the key out.const DefaultAgentSessionsEnabled = true-// AgentEnabled resolves sessions.agent.enabled against that default, so a-// comparison of two file configs never reads an absent key as disabled.+// AgentEnabled is the file-config twin of session.Store.Enabled: whether this+// config leaves agent sessions serving. It resolves an absent enabled key against+// the default, so a comparison of two file configs never reads absence as+// disabled, and it honours mode — mode "off" disables the family exactly as+// enabled false does, so a restart-reason comparison built on this cannot miss+// the transition through the other field.func (s SessionsFileConfig) AgentEnabled() bool {+ if !session.ModeServes(s.Agent.Mode) {+ return false+ }if s.Agent.Enabled == nil {return DefaultAgentSessionsEnabled}diff --git a/internal/config/validate.go b/internal/config/validate.goindex dedc1c03..ca446c06 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -14,8 +14,33 @@ import ("github.com/pinchtab/pinchtab/internal/browsers""github.com/pinchtab/pinchtab/internal/config/geo""github.com/pinchtab/pinchtab/internal/safelog"+ "github.com/pinchtab/pinchtab/internal/session")+// validateAgentSessionMode gates sessions.agent.mode. "required" is refused+// rather than accepted-and-ignored: it names a real posture — the session+// credential as the only accepted agent credential — that this server does not+// enforce, and an operator who sets it believes they have session-only auth while+// the bearer token and the dashboard cookie still authenticate. Refusing is+// 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 {+ case "", session.ModeOff, session.ModePreferred:+ return nil+ case 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),+ }}+ default:+ return []error{ValidationError{+ Field: "sessions.agent.mode",+ Message: fmt.Sprintf("invalid value %q (must be off or preferred)", mode),+ }}+ }+}+type ValidationError struct {Field stringMessage string@@ -321,6 +346,7 @@ func ValidateFileConfig(fc *FileConfig) []error {Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Observability.Activity.RetentionDays),})}+ errs = append(errs, validateAgentSessionMode(fc.Sessions.Agent.Mode)...)if fc.Sessions.Dashboard.IdleTimeoutSec != nil && *fc.Sessions.Dashboard.IdleTimeoutSec <= 0 {errs = append(errs, ValidationError{Field: "sessions.dashboard.idleTimeoutSec",diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex 0706992a..b471fa0d 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -1303,3 +1303,64 @@ func TestTheIgnoredKeyTextsInstructOnlyWhatTheProductCanDo(t *testing.T) {t.Errorf("the refusal names server.stateDir but config set rejects it: %v", err)}}++// mode used to be accepted whatever it said and read by nothing, so+// `config set sessions.agent.mode nonsense` succeeded and changed nothing.+// "required" is refused separately from a typo because it is not a typo: it names+// a posture this server does not enforce, and accepting it leaves an operator+// believing they have session-only auth.+func TestValidateFileConfig_AgentSessionMode(t *testing.T) {+ for _, tt := range []struct {+ mode string+ wantErr bool+ wantSays string+ }{+ {"", false, ""},+ {"off", false, ""},+ {"preferred", false, ""},+ {"required", true, "not implemented"},+ {"nonsense", true, "invalid value"},+ {"Off", true, "invalid value"},+ } {+ fc := &FileConfig{Sessions: SessionsFileConfig{Agent: AgentSessionFileConfig{Mode: tt.mode}}}+ errs := ValidateFileConfig(fc)++ if hasErr := len(errs) > 0; hasErr != tt.wantErr {+ t.Errorf("mode=%q: got error=%v (%v), want error=%v", tt.mode, hasErr, errs, tt.wantErr)+ continue+ }+ if !tt.wantErr {+ continue+ }+ message := errs[0].Error()+ if !strings.Contains(message, "sessions.agent.mode") {+ t.Errorf("mode=%q: refusal %q does not name the field", tt.mode, message)+ }+ if !strings.Contains(message, tt.wantSays) {+ t.Errorf("mode=%q: refusal %q does not say %q", tt.mode, message, tt.wantSays)+ }+ }+}++// The predicate the whole card turns on, at the file-config layer: mode off and+// enabled false must answer the same, or the restart-reason comparison built on+// this misses the transition through the other field.+func TestAgentEnabledFoldsBothFields(t *testing.T) {+ enabled, disabled := true, false+ for _, tt := range []struct {+ name string+ fc SessionsFileConfig+ want bool+ }{+ {"absent keys", SessionsFileConfig{}, true},+ {"enabled true", SessionsFileConfig{Agent: AgentSessionFileConfig{Enabled: &enabled}}, true},+ {"enabled false", SessionsFileConfig{Agent: AgentSessionFileConfig{Enabled: &disabled}}, false},+ {"mode off", SessionsFileConfig{Agent: AgentSessionFileConfig{Mode: "off"}}, false},+ {"enabled true, mode off", SessionsFileConfig{Agent: AgentSessionFileConfig{Enabled: &enabled, Mode: "off"}}, false},+ {"mode preferred", SessionsFileConfig{Agent: AgentSessionFileConfig{Mode: "preferred"}}, true},+ } {+ if got := tt.fc.AgentEnabled(); got != tt.want {+ t.Errorf("%s: AgentEnabled() = %v, want %v", tt.name, got, tt.want)+ }+ }+}diff --git a/internal/server/agent_session_live_config_test.go b/internal/server/agent_session_live_config_test.goindex 4ed01db8..60c71881 100644--- a/internal/server/agent_session_live_config_test.go+++ b/internal/server/agent_session_live_config_test.go@@ -105,27 +105,69 @@ func TestEnablingAgentSessionsReportsARestartReason(t *testing.T) {}}+// mode "off" is the other half of one question, and the docs promise it reduces+// the auth surface. It must reach exactly the state enabled false reaches — the+// same refusals, through the same assertions — or the two fields drift again.// mode and the two timeouts have no boot-time consumer, so they apply live in-// both directions and must never produce a restart reason.-func TestAgentSessionModeAppliesLiveInBothDirections(t *testing.T) {+// both directions and never produce a restart reason.+func TestModeOffDisablesAgentSessionsExactlyAsEnabledFalseDoes(t *testing.T) {+ for _, tc := range []struct {+ name string+ disable func(*config.FileConfig)+ restore func(*config.FileConfig)+ }{+ {"enabled false", func(fc *config.FileConfig) { agentSessionsEnabled(fc, false) }, func(fc *config.FileConfig) { agentSessionsEnabled(fc, true) }},+ {"mode off", func(fc *config.FileConfig) { fc.Sessions.Agent.Mode = "off" }, func(fc *config.FileConfig) { fc.Sessions.Agent.Mode = "preferred" }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ f := newFrontDoor(t, nil)++ _, token, err := f.agentSessions.Create("agent-under-test", "", "")+ if err != nil {+ t.Fatal(err)+ }+ if before := f.sessionRequest(t, token); before.Code != http.StatusOK {+ t.Fatalf("the session token was refused before any save (%d: %s)", before.Code, before.Body.String())+ }++ f.save(t, tc.disable)++ if f.agentSessions.Enabled() {+ t.Fatal("the store still reports agent sessions enabled; Enabled() is not the one predicate both fields feed")+ }+ after := f.sessionRequest(t, token)+ if after.Code != http.StatusUnauthorized || errorCode(t, after) != "session_auth_unavailable" {+ t.Fatalf("the existing session token still authenticated (%d: %s)", after.Code, after.Body.String())+ }+ create := f.createSessionOverHTTP(t)+ if create.Code != http.StatusNotFound || errorCode(t, create) != CodeSessionsDisabled {+ t.Fatalf("POST /sessions answered %d (%s), want the disabled refusal", create.Code, create.Body.String())+ }++ // Back again, live: the family was mounted at boot, so nothing here is frozen.+ f.save(t, tc.restore)+ if !f.agentSessions.Enabled() {+ t.Fatal("the store did not come back; the restoring save reported applied and moved nothing")+ }+ if back := f.createSessionOverHTTP(t); back.Code != http.StatusCreated {+ t.Fatalf("POST /sessions answered %d (%s) after restoring", back.Code, back.Body.String())+ }+ })+ }+}++// The timeouts have no boot-time consumer either: they reach the store and never+// produce a restart reason. f.save asserts the second half.+func TestAgentSessionTimeoutsApplyLive(t *testing.T) {f := newFrontDoor(t, nil)- if got := f.agentSessions.Mode(); got != "preferred" {- t.Fatalf("boot mode = %q, want preferred", got)- }f.save(t, func(fc *config.FileConfig) {- fc.Sessions.Agent.Mode = "required"idle, life := 60, 600fc.Sessions.Agent.IdleTimeoutSec = &idlefc.Sessions.Agent.MaxLifetimeSec = &life})- if got := f.agentSessions.Mode(); got != "required" {- t.Fatalf("mode after the save = %q, want required", got)- }-- f.save(t, func(fc *config.FileConfig) { fc.Sessions.Agent.Mode = "preferred" })- if got := f.agentSessions.Mode(); got != "preferred" {- t.Fatalf("mode after the second save = %q, want preferred", got)+ if !f.agentSessions.Enabled() {+ t.Fatal("a timeout save disabled the store")}}diff --git a/internal/session/config_access_census_test.go b/internal/session/config_access_census_test.goindex 608a301d..9a6ba144 100644--- a/internal/session/config_access_census_test.go+++ b/internal/session/config_access_census_test.go@@ -24,8 +24,7 @@ func TestEveryConfigReadHoldsTheStoreLock(t *testing.T) {owners := []string{"applyConfig", // called under the lock by UpdateConfig, and from NewStore before sharing"registerSession", // takes the lock, stamps the lifetime, installs the session- "Enabled", // takes the lock for the read- "Mode", // takes the lock for the read+ "Enabled", // takes the lock for the read of both fields the predicate folds"PersistPath", // takes the lock for the read"isExpired", // only ever called with the lock held"loadPersisted", // runs in NewStore, before the store is reachablediff --git a/internal/session/store.go b/internal/session/store.goindex d73aa2a3..ce9bef24 100644--- a/internal/session/store.go+++ b/internal/session/store.go@@ -33,10 +33,25 @@ type Session struct {Grants []string `json:"grants,omitempty"`}+// The auth modes sessions.agent.mode may name. ModeRequired is vocabulary, not+// behaviour: it is refused by config validation, because accepting it would+// promise session-only auth that the bearer token and the dashboard cookie still+// bypass. This package owns the set so the validator and the predicate cannot+// hold two copies of it.+const (+ ModeOff = "off"+ ModePreferred = "preferred"+ ModeRequired = "required"+)++// ModeServes reports whether a mode value leaves agent sessions serving. An+// empty value is the default, ModePreferred.+func ModeServes(mode string) bool { return mode != ModeOff }+// Config controls store behavior.type Config struct {Enabled bool- Mode string // "off", "preferred", "required"+ Mode stringIdleTimeout time.DurationMaxLifetime time.DurationPersistPath string@@ -160,7 +175,7 @@ func (s *Store) applyConfig(cfg Config) {cfg.MaxLifetime = DefaultMaxLifetime}if cfg.Mode == "" {- cfg.Mode = "preferred"+ cfg.Mode = ModePreferred}s.cfg = cfg}@@ -470,14 +485,17 @@ func (s *Store) RunMaintenance(ctx context.Context) {}}-// Enabled reports whether session auth is enabled.+// Enabled is the ONE predicate every consumer of agent sessions asks — the front+// door's session branch, the session API's handlers and their registration. enabled+// and mode were a two-field encoding of one question, and the halves drifted: mode+// was documented as reducing the auth surface while nothing read it.func (s *Store) Enabled() bool {if s == nil {return false}s.mu.Lock()defer s.mu.Unlock()- return s.cfg.Enabled+ return s.cfg.Enabled && ModeServes(s.cfg.Mode)}// PersistPath returns the file the store persists to, so a caller rebuilding@@ -491,16 +509,6 @@ func (s *Store) PersistPath() string {return s.cfg.PersistPath}-// Mode returns the current auth mode.-func (s *Store) Mode() string {- if s == nil {- return "off"- }- s.mu.Lock()- defer s.mu.Unlock()- return s.cfg.Mode-}-func (s *Store) isExpired(sess *Session, now time.Time) bool {if !sess.ExpiresAt.IsZero() && now.After(sess.ExpiresAt) {return truediff --git a/internal/session/store_race_test.go b/internal/session/store_race_test.goindex 0c866263..afc22d6b 100644--- a/internal/session/store_race_test.go+++ b/internal/session/store_race_test.go@@ -38,8 +38,8 @@ func TestAuthenticateReturnsDefensiveCopy(t *testing.T) {wg.Wait()}-// Enabled/Mode are read on every authenticated request; UpdateConfig replaces-// the whole config struct, so unsynchronized reads race.+// Enabled is read on every authenticated request and reads two config fields;+// UpdateConfig replaces the whole config struct, so unsynchronized reads race.func TestConfigAccessorsAreSynchronized(t *testing.T) {s := NewStore(Config{Enabled: true, Mode: "preferred"})@@ -48,14 +48,13 @@ func TestConfigAccessorsAreSynchronized(t *testing.T) {go func() {defer wg.Done()for i := 0; i < 500; i++ {- s.UpdateConfig(Config{Enabled: i%2 == 0, Mode: "required"})+ s.UpdateConfig(Config{Enabled: i%2 == 0, Mode: ModeOff})}}()go func() {defer wg.Done()for i := 0; i < 500; i++ {_ = s.Enabled()- _ = s.Mode()}}()wg.Wait()diff --git a/internal/session/store_test.go b/internal/session/store_test.goindex f75d4d26..d63f4351 100644--- a/internal/session/store_test.go+++ b/internal/session/store_test.go@@ -384,3 +384,24 @@ func TestNilStore(t *testing.T) {t.Fatal("nil store should return nil list")}}++// enabled and mode were a two-field encoding of one question and the halves+// drifted: mode was documented as reducing the auth surface and read by nothing.+// Enabled() is now the one predicate, so every consumer follows both fields.+func TestEnabledFoldsModeAndEnabled(t *testing.T) {+ for _, tt := range []struct {+ name string+ cfg Config+ want bool+ }{+ {"enabled, mode unset", Config{Enabled: true}, true},+ {"enabled, preferred", Config{Enabled: true, Mode: ModePreferred}, true},+ {"enabled, off", Config{Enabled: true, Mode: ModeOff}, false},+ {"disabled, preferred", Config{Enabled: false, Mode: ModePreferred}, false},+ {"disabled, off", Config{Enabled: false, Mode: ModeOff}, false},+ } {+ if got := NewStore(tt.cfg).Enabled(); got != tt.want {+ t.Errorf("%s: Enabled() = %v, want %v", tt.name, got, tt.want)+ }+ }+}