High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(config): apply a sessions.agent save to the running store and flag only the enable transition (PIN-287)
Luigi Agostie6a18b8c1e53
diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 88011ce0..14c8c04e 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -280,7 +280,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {Sessions: SessionsRuntimeConfig{Agent: AgentSessionRuntimeConfig{- Enabled: true,+ Enabled: DefaultAgentSessionsEnabled,Mode: "preferred",IdleTimeout: 30 * time.Minute,MaxLifetime: 24 * time.Hour,diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex e160040d..fa2008aa 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -296,6 +296,19 @@ type SessionsFileConfig struct {Agent AgentSessionFileConfig `json:"agent,omitempty"`}+// DefaultAgentSessionsEnabled is the effective value of sessions.agent.enabled+// 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.+func (s SessionsFileConfig) AgentEnabled() bool {+ if s.Agent.Enabled == nil {+ return DefaultAgentSessionsEnabled+ }+ return *s.Agent.Enabled+}+type AgentSessionFileConfig struct {Enabled *bool `json:"enabled,omitempty"`Mode string `json:"mode,omitempty"`diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.goindex d32b61eb..6219ea00 100644--- a/internal/dashboard/agent_session_api.go+++ b/internal/dashboard/agent_session_api.go@@ -50,7 +50,21 @@ func (a *SessionAPI) registerPatterns(mux *http.ServeMux, patterns []string) {if handler == nil {panic("dashboard: no session handler bound for " + pattern)}- mux.HandleFunc(pattern, handler)+ mux.HandleFunc(pattern, a.whileEnabled(handler))+ }+}++// whileEnabled re-reads the store on every request, so a save that switches agent+// sessions off is refused by routes a boot with them on already mounted. The+// answer is the one the never-mounted state gives, from the same vocabulary.+func (a *SessionAPI) whileEnabled(next http.HandlerFunc) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ if a.store == nil || !a.store.Enabled() {+ httpx.ErrorCode(w, http.StatusNotFound, session.CodeDisabled, session.MsgDisabled, false,+ remedy.Details(session.HintDisabled, remedy.None))+ return+ }+ next(w, r)}}diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.goindex 4968d1d2..fde4afda 100644--- a/internal/dashboard/config_api.go+++ b/internal/dashboard/config_api.go@@ -15,6 +15,7 @@ import ("github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/session")type profileLister interface {@@ -30,16 +31,17 @@ type agentCounter interface {}type ConfigAPI struct {- live *config.Live- instances InstanceLister- profiles profileLister- applier runtimeConfigApplier- agents agentCounter- sessions *browsersession.Manager- version string- startedAt time.Time- boot config.FileConfig- mu sync.RWMutex+ live *config.Live+ instances InstanceLister+ profiles profileLister+ applier runtimeConfigApplier+ agents agentCounter+ sessions *browsersession.Manager+ agentSessions *session.Store+ version string+ startedAt time.Time+ boot config.FileConfig+ mu sync.RWMutex// Config-file snapshot cached by mtime so read-only health/config polls answer// from memory instead of re-reading + parsing the file every request. Guarded@@ -102,6 +104,15 @@ func (c *ConfigAPI) SetSessionManager(sessions *browsersession.Manager) {c.sessions = sessions}+// SetAgentSessionStore wires the agent session store so a save of the+// sessions.agent block reaches the running store instead of only the file.+func (c *ConfigAPI) SetAgentSessionStore(store *session.Store) {+ if c == nil {+ return+ }+ c.agentSessions = store+}+func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("GET /api/config", c.HandleGetConfig)mux.HandleFunc("PUT /api/config", c.HandlePutConfig)@@ -223,6 +234,9 @@ func (c *ConfigAPI) persistAndApply(w http.ResponseWriter, normalized *config.Fiif c.sessions != nil {c.sessions.UpdateConfig(BrowserSessionConfig(next))}+ if c.agentSessions != nil {+ c.agentSessions.UpdateConfig(AgentSessionConfig(next, c.agentSessions.PersistPath()))+ }if c.applier != nil {c.applier.ApplyRuntimeConfig(next)}diff --git a/internal/dashboard/config_changes.go b/internal/dashboard/config_changes.goindex 3158919b..0312e0af 100644--- a/internal/dashboard/config_changes.go+++ b/internal/dashboard/config_changes.go@@ -108,6 +108,15 @@ func (c *ConfigAPI) restartReasonsFor(next config.FileConfig) []string {if c.boot.InstanceDefaults.StealthLevel != next.InstanceDefaults.StealthLevel {reasons = append(reasons, "Stealth level")}+ // The sessions.agent block applies live in every direction but one: whether+ // the session API and its route family exist at all is decided at boot, so a+ // process that booted with agent sessions off cannot serve them until it+ // restarts. Turning them off needs no restart — both request-time consumers+ // read the store live — and claiming otherwise about an authentication+ // control would be the same defect one direction over.+ if !c.boot.Sessions.AgentEnabled() && next.Sessions.AgentEnabled() {+ reasons = append(reasons, "Agent sessions")+ }if !sameIntPtr(c.boot.MultiInstance.Restart.MaxRestarts, next.MultiInstance.Restart.MaxRestarts) ||!sameIntPtr(c.boot.MultiInstance.Restart.InitBackoffSec, next.MultiInstance.Restart.InitBackoffSec) ||!sameIntPtr(c.boot.MultiInstance.Restart.MaxBackoffSec, next.MultiInstance.Restart.MaxBackoffSec) ||diff --git a/internal/dashboard/session_config.go b/internal/dashboard/session_config.goindex 838b578c..ddfefc9f 100644--- a/internal/dashboard/session_config.go+++ b/internal/dashboard/session_config.go@@ -5,10 +5,13 @@ import ("github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/session")const dashboardSessionStateFile = "dashboard-auth-sessions.json"+const agentSessionStateFile = "sessions.json"+func BrowserSessionConfig(runtime *config.RuntimeConfig) browsersession.Config {if runtime == nil {return browsersession.Config{}@@ -22,3 +25,28 @@ func BrowserSessionConfig(runtime *config.RuntimeConfig) browsersession.Config {PersistElevationAcrossRestart: runtime.Sessions.Dashboard.PersistElevationAcrossRestart,}}++// AgentSessionConfig maps the runtime config onto the agent session store's+// settings. persistPath is passed in rather than rebuilt from StateDir: the+// store's config is replaced wholesale, so recomputing it would relocate live+// sessions mid-run if server.stateDir were edited.+func AgentSessionConfig(runtime *config.RuntimeConfig, persistPath string) session.Config {+ if runtime == nil {+ return session.Config{PersistPath: persistPath}+ }+ return session.Config{+ Enabled: runtime.Sessions.Agent.Enabled,+ Mode: runtime.Sessions.Agent.Mode,+ IdleTimeout: runtime.Sessions.Agent.IdleTimeout,+ MaxLifetime: runtime.Sessions.Agent.MaxLifetime,+ PersistPath: persistPath,+ }+}++// AgentSessionStatePath is where the agent session store persists at boot.+func AgentSessionStatePath(runtime *config.RuntimeConfig) string {+ if runtime == nil {+ return ""+ }+ return filepath.Join(runtime.StateDir, agentSessionStateFile)+}diff --git a/internal/server/agent_session_live_config_test.go b/internal/server/agent_session_live_config_test.gonew file mode 100644index 00000000..6e4964a6--- /dev/null+++ b/internal/server/agent_session_live_config_test.go@@ -0,0 +1,164 @@+package server++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func (f frontDoor) sessionRequest(t *testing.T, token string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(http.MethodGet, "/tabs", nil)+ req.Header.Set("Authorization", "Session "+token)+ w := httptest.NewRecorder()+ f.handler.ServeHTTP(w, req)+ return w+}++func (f frontDoor) createSessionOverHTTP(t *testing.T) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/sessions", bytes.NewReader([]byte(`{"agentId":"agent-under-test"}`)))+ req.Header.Set("Authorization", "Bearer "+frontDoorLiveToken)+ w := httptest.NewRecorder()+ f.handler.ServeHTTP(w, req)+ return w+}++func errorCode(t *testing.T, w *httptest.ResponseRecorder) string {+ t.Helper()+ var body struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode error envelope: %v (body %s)", err, w.Body.String())+ }+ return body.Code+}++func agentSessionsEnabled(fc *config.FileConfig, enabled bool) {+ fc.Sessions.Agent.Enabled = &enabled+}++// Switching an authentication mechanism off is the direction that applies: both+// consumers that decide per request — the front door's session branch and the+// session API's own handlers — read the store live, so the save must move them+// and must not claim a restart is owed.+func TestDisablingAgentSessionsTakesEffectWithoutARestart(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); this test never reached the state it is about",+ before.Code, before.Body.String())+ }+ if before := f.createSessionOverHTTP(t); before.Code != http.StatusCreated {+ t.Fatalf("POST /sessions answered %d before any save: %s", before.Code, before.Body.String())+ }++ f.save(t, func(fc *config.FileConfig) { agentSessionsEnabled(fc, false) })++ if f.agentSessions.Enabled() {+ t.Fatal("the store still reports agent sessions enabled; the save reached the file and not the running store")+ }+ after := f.sessionRequest(t, token)+ if after.Code != http.StatusUnauthorized {+ t.Fatalf("the existing session token still authenticated after the save (%d: %s)", after.Code, after.Body.String())+ }+ if got := errorCode(t, after); got != "session_auth_unavailable" {+ t.Errorf("refusal code = %q, want session_auth_unavailable naming the disabled mechanism", got)+ }+ create := f.createSessionOverHTTP(t)+ if create.Code != http.StatusNotFound {+ t.Fatalf("POST /sessions still minted a session after the save (%d: %s)", create.Code, create.Body.String())+ }+ if got := errorCode(t, create); got != CodeSessionsDisabled {+ t.Errorf("refusal code = %q, want %q", got, CodeSessionsDisabled)+ }+}++// The one direction that cannot apply: whether the family is mounted at all is+// decided at boot, so a process that booted with agent sessions off must say a+// restart is owed rather than report the save applied.+func TestEnablingAgentSessionsReportsARestartReason(t *testing.T) {+ f := newFrontDoor(t, func(fc *config.FileConfig) { agentSessionsEnabled(fc, false) })++ reasons := f.saveReportingReasons(t, func(fc *config.FileConfig) { agentSessionsEnabled(fc, true) })+ if !slices.Contains(reasons, "Agent sessions") {+ t.Fatalf("restartReasons = %v, want one naming the agent sessions block", reasons)+ }++ create := f.createSessionOverHTTP(t)+ if create.Code != http.StatusNotFound || errorCode(t, create) != CodeSessionsDisabled {+ t.Fatalf("POST /sessions answered %d (%s) after enabling; if the family were live the restart reason would be manufactured",+ create.Code, create.Body.String())+ }+}++// 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) {+ 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, 600+ fc.Sessions.Agent.IdleTimeoutSec = &idle+ fc.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)+ }+}++// The store's config is replaced wholesale, so the mapping must carry the path+// the store was built with. Both failure modes are silent: dropping the path+// stops persistence, and recomputing it from an edited stateDir splits live+// sessions across two files.+func TestASaveKeepsTheAgentSessionStoreWritingToItsOriginalPath(t *testing.T) {+ f := newFrontDoor(t, nil)++ original := f.agentSessions.PersistPath()+ if original == "" {+ t.Fatal("the store booted with no persist path; this test cannot see a path move")+ }+ moved := t.TempDir()++ f.save(t, func(fc *config.FileConfig) { fc.Server.StateDir = moved })++ if got := f.agentSessions.PersistPath(); got != original {+ t.Fatalf("persist path after the save = %q, want %q", got, original)+ }+ id, _, err := f.agentSessions.Create("agent-after-save", "", "")+ if err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(original)+ if err != nil {+ t.Fatalf("read the original session file after the save: %v", err)+ }+ if !strings.Contains(string(data), id) {+ t.Errorf("the session created after the save is not in %s; the store stopped persisting there", original)+ }+ if _, err := os.Stat(filepath.Join(moved, "sessions.json")); err == nil {+ t.Errorf("the store started writing under the edited stateDir %s, splitting live sessions across two files", moved)+ }+}diff --git a/internal/server/front_door_live_config_test.go b/internal/server/front_door_live_config_test.goindex 3ca9e8f1..62c52415 100644--- a/internal/server/front_door_live_config_test.go+++ b/internal/server/front_door_live_config_test.go@@ -15,6 +15,7 @@ import ("github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/dashboard""github.com/pinchtab/pinchtab/internal/orchestrator"+ "github.com/pinchtab/pinchtab/internal/session")const frontDoorLiveToken = "front-door-live-token"@@ -24,10 +25,11 @@ const frontDoorLiveToken = "front-door-live-token"// the save writes to. The chain is the real one — an isolated middleware already// behaved correctly, which is why nothing caught the boot pointer.type frontDoor struct {- handler http.Handler- api *dashboard.ConfigAPI- sessions *browsersession.Manager- live *config.Live+ handler http.Handler+ api *dashboard.ConfigAPI+ sessions *browsersession.Manager+ agentSessions *session.Store+ live *config.Live}func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {@@ -35,6 +37,7 @@ func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {fc := config.DefaultFileConfig()fc.Server.Token = frontDoorLiveToken+ fc.Server.StateDir = t.TempDir()if boot != nil {boot(&fc)}@@ -54,20 +57,31 @@ func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {live := orch.LiveConfig()sessions := browsersession.NewManager(dashboard.BrowserSessionConfig(cfg))+ agentSessions := session.NewStore(dashboard.AgentSessionConfig(cfg, dashboard.AgentSessionStatePath(cfg)))api := dashboard.NewConfigAPI(live, orch, nil, orch, nil, "test", time.Now())api.SetSessionManager(sessions)+ api.SetAgentSessionStore(agentSessions)mux := http.NewServeMux()mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {_, _ = w.Write([]byte(`{"status":"ok"}`))})+ mux.HandleFunc("/tabs", func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"tabs":[]}`))+ })api.RegisterHandlers(mux)+ if agentSessions.Enabled() {+ dashboard.NewSessionAPI(agentSessions, cfg.BrowsersAvailable).RegisterHandlers(mux)+ } else {+ RegisterSessionsDisabled(mux)+ }return frontDoor{- handler: FrontDoorHandler(live, nil, sessions, nil, mux),- api: api,- sessions: sessions,- live: live,+ handler: FrontDoorHandler(live, nil, sessions, agentSessions, mux),+ api: api,+ sessions: sessions,+ agentSessions: agentSessions,+ live: live,}}@@ -77,6 +91,16 @@ func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {func (f frontDoor) save(t *testing.T, mutate func(*config.FileConfig)) {t.Helper()+ if reasons := f.saveReportingReasons(t, mutate); len(reasons) > 0 {+ t.Fatalf("the save reported restartRequired=true (%v); this card must not enlarge that list", reasons)+ }+}++// saveReportingReasons drives the same real PUT and hands back the restart+// reasons the server reported, for the one transition that has any.+func (f frontDoor) saveReportingReasons(t *testing.T, mutate func(*config.FileConfig)) []string {+ t.Helper()+current, _, err := config.LoadFileConfig()if err != nil || current == nil {t.Fatalf("load current config: %v", err)@@ -102,9 +126,10 @@ func (f frontDoor) save(t *testing.T, mutate func(*config.FileConfig)) {if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {t.Fatalf("decode save envelope: %v", err)}- if env.RestartRequired {- t.Fatalf("the save reported restartRequired=true (%v); this card must not enlarge that list", env.RestartReasons)+ if env.RestartRequired && len(env.RestartReasons) == 0 {+ t.Fatal("the save reported restartRequired=true with no reason naming what is frozen")}+ return env.RestartReasons}func proxiedPreflight() *http.Request {diff --git a/internal/server/server.go b/internal/server/server.goindex 2df93555..2955bad1 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -8,7 +8,6 @@ import ("net/http""os""os/signal"- "path/filepath""sync""syscall""time"@@ -92,13 +91,8 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {configAPI.SetSessionManager(sessions)authAPI := dashboard.NewAuthAPI(live, sessions)- sessionStore := session.NewStore(session.Config{- Enabled: cfg.Sessions.Agent.Enabled,- Mode: cfg.Sessions.Agent.Mode,- IdleTimeout: cfg.Sessions.Agent.IdleTimeout,- MaxLifetime: cfg.Sessions.Agent.MaxLifetime,- PersistPath: filepath.Join(cfg.StateDir, "sessions.json"),- })+ sessionStore := session.NewStore(dashboard.AgentSessionConfig(cfg, dashboard.AgentSessionStatePath(cfg)))+ configAPI.SetAgentSessionStore(sessionStore)var sessionAPI *dashboard.SessionAPIif sessionStore.Enabled() {sessionAPI = dashboard.NewSessionAPI(sessionStore, cfg.BrowsersAvailable)diff --git a/internal/server/sessions_unavailable.go b/internal/server/sessions_unavailable.goindex 3aedfd08..9df439ce 100644--- a/internal/server/sessions_unavailable.go+++ b/internal/server/sessions_unavailable.go@@ -19,20 +19,15 @@ const (CodeSessionsUnavailableInBridgeMode = "sessions_unavailable_bridge_mode"// CodeSessionsDisabled: mounted by config and switched off, where the config remedy// this family always printed is the correct one.- CodeSessionsDisabled = "sessions_disabled"+ CodeSessionsDisabled = session.CodeDisabled)const (msgSessionsUnavailableInBridgeMode = "agent sessions are unavailable in bridge mode"hintSessionsUnavailableInBridge = "no config value mounts the session family on a bridge; the full server is what serves it."- msgSessionsDisabled = "agent sessions are not enabled on this server"- // The config editor knows sessions.dashboard.* and no sessions.agent.* field, so- // "pinchtab config set sessions.agent.enabled true" answers "unknown field" — the same- // dead end this family's remedy existed to remove, one state over. So this state has NO- // remedy: the fix is a file edit plus a restart, which is not one command, and the hint- // says so rather than a remedy naming a command that dead-ends.- hintSessionsDisabled = "set sessions.agent.enabled = true in config.json and restart the server; the config editor has no field for that path, so it cannot be changed from the command line."+ msgSessionsDisabled = session.MsgDisabled+ hintSessionsDisabled = session.HintDisabled)// Running the full server is the bridge's whole remedy. The verb it used to lead with —diff --git a/internal/session/config_access_census_test.go b/internal/session/config_access_census_test.goindex 44256b17..608a301d 100644--- a/internal/session/config_access_census_test.go+++ b/internal/session/config_access_census_test.go@@ -26,6 +26,7 @@ func TestEveryConfigReadHoldsTheStoreLock(t *testing.T) {"registerSession", // takes the lock, stamps the lifetime, installs the session"Enabled", // takes the lock for the read"Mode", // takes the lock for the read+ "PersistPath", // takes the lock for the read"isExpired", // only ever called with the lock held"loadPersisted", // runs in NewStore, before the store is reachable"snapshotLocked",diff --git a/internal/session/routes.go b/internal/session/routes.goindex e83ede57..6a507d7e 100644--- a/internal/session/routes.go+++ b/internal/session/routes.go@@ -21,3 +21,13 @@ var routePatterns = []string{func RoutePatterns() []string {return slices.Clone(routePatterns)}++// The disabled state's vocabulary lives here, beside the route list, because two+// registrars answer for it: the server package when the store booted disabled and+// never mounted the family, and the dashboard's SessionAPI when a save switched+// it off in a process that did mount it.+const (+ CodeDisabled = "sessions_disabled"+ MsgDisabled = "agent sessions are not enabled on this server"+ HintDisabled = "set sessions.agent.enabled = true and restart the server; the route family is mounted at startup, so enabling it cannot take effect in the running process."+)diff --git a/internal/session/store.go b/internal/session/store.goindex e7b08a50..d73aa2a3 100644--- a/internal/session/store.go+++ b/internal/session/store.go@@ -480,6 +480,17 @@ func (s *Store) Enabled() bool {return s.cfg.Enabled}+// PersistPath returns the file the store persists to, so a caller rebuilding+// the config from elsewhere can carry it over instead of recomputing it.+func (s *Store) PersistPath() string {+ if s == nil {+ return ""+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.cfg.PersistPath+}+// Mode returns the current auth mode.func (s *Store) Mode() string {if s == nil {