High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor(session): drop the per-session idle timeout nothing read and lock the config it hid
Luigi Agosti08a31110f888
diff --git a/internal/session/config_access_census_test.go b/internal/session/config_access_census_test.gonew file mode 100644index 00000000..44256b17--- /dev/null+++ b/internal/session/config_access_census_test.go@@ -0,0 +1,67 @@+package session++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// cfg is written by UpdateConfig under s.mu, so every reader must hold s.mu too.+// One did not: Create built the session's expiry from s.cfg.MaxLifetime before it+// took the lock, which is a data race by the memory model and reads a value a+// concurrent save may be part-way through replacing.+//+// The rule cannot be checked by a unit test — an unlocked read returns the right+// answer almost always, and the race detector only reports it under an+// interleaving no test can force — so the guard is a source census over the+// functions allowed to touch the field.+func TestEveryConfigReadHoldsTheStoreLock(t *testing.T) {+ pkg := srccensus.Load(t, ".", 4)++ // Each entry is a function that touches s.cfg while holding s.mu, or that runs+ // before the store is shared. Checked in both directions: a function that stops+ // touching cfg fails too, so the list cannot drift from the real one.+ 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+ "isExpired", // only ever called with the lock held+ "loadPersisted", // runs in NewStore, before the store is reachable+ "snapshotLocked",+ }++ spans := make(map[string]srccensus.Func, len(owners))+ for _, name := range owners {+ fn, ok := pkg.Func(name)+ if !ok {+ t.Fatalf("owner %s of s.cfg no longer exists in %s; re-point this census at whatever replaced it rather than deleting it", name, pkg.Dir())+ }+ spans[name] = fn+ }++ sites := pkg.FieldReferences("cfg")+ if len(sites) < len(owners) {+ t.Fatalf("only %d reference(s) to s.cfg for %d owner(s); the census is matching almost nothing and would pass vacuously", len(sites), len(owners))+ }++ covered := map[string]bool{}+ for _, site := range sites {+ owner := ""+ for name, span := range spans {+ if pkg.Contains(span, site) {+ owner = name+ break+ }+ }+ covered[owner] = true+ if owner == "" {+ t.Errorf("%s touches s.cfg outside a function that holds s.mu; take the lock there, or add it here with the reason it is safe", site)+ }+ }+ for _, name := range owners {+ if !covered[name] {+ t.Errorf("%s no longer touches s.cfg, so this census is guarding one site fewer than it claims; drop it from the list", name)+ }+ }+}diff --git a/internal/session/store.go b/internal/session/store.goindex 27e00301..e7b08a50 100644--- a/internal/session/store.go+++ b/internal/session/store.go@@ -21,17 +21,16 @@ import (// Session represents a durable, revocable authenticated session.type Session struct {- ID string `json:"id"`- AgentID string `json:"agentId"`- Label string `json:"label,omitempty"`- Browser string `json:"browser,omitempty"`- TokenHash [32]byte `json:"-"`- CreatedAt time.Time `json:"createdAt"`- LastSeenAt time.Time `json:"lastSeenAt"`- ExpiresAt time.Time `json:"expiresAt,omitempty"`- IdleTimeout time.Duration `json:"-"`- Status string `json:"status"`- Grants []string `json:"grants,omitempty"`+ ID string `json:"id"`+ AgentID string `json:"agentId"`+ Label string `json:"label,omitempty"`+ Browser string `json:"browser,omitempty"`+ TokenHash [32]byte `json:"-"`+ CreatedAt time.Time `json:"createdAt"`+ LastSeenAt time.Time `json:"lastSeenAt"`+ ExpiresAt time.Time `json:"expiresAt,omitempty"`+ Status string `json:"status"`+ Grants []string `json:"grants,omitempty"`}// Config controls store behavior.@@ -184,23 +183,17 @@ func (s *Store) Create(agentID, label, browser string) (sessionID, sessionTokennow := s.now()session := &Session{- ID: id,- AgentID: strings.TrimSpace(agentID),- Label: strings.TrimSpace(label),- Browser: strings.TrimSpace(browser),- TokenHash: hashToken(token),- CreatedAt: now,- LastSeenAt: now,- ExpiresAt: now.Add(s.cfg.MaxLifetime),- IdleTimeout: s.cfg.IdleTimeout,- Status: StatusActive,+ ID: id,+ AgentID: strings.TrimSpace(agentID),+ Label: strings.TrimSpace(label),+ Browser: strings.TrimSpace(browser),+ TokenHash: hashToken(token),+ CreatedAt: now,+ LastSeenAt: now,+ Status: StatusActive,}- s.mu.Lock()- s.sessions[id] = session- s.byTokenHash[session.TokenHash] = session- job, persist := s.snapshotLocked()- s.mu.Unlock()+ job, persist := s.registerSession(session, now)if persist {s.writeSnapshot(job)}@@ -208,6 +201,20 @@ func (s *Store) Create(agentID, label, browser string) (sessionID, sessionTokenreturn id, token, nil}+// registerSession stamps the lifetime from config and installs the session in both+// indexes, all under s.mu. It exists so Create names neither s.cfg nor the maps:+// the expiry used to be built from s.cfg.MaxLifetime BEFORE the lock was taken,+// which is a race against UpdateConfig, and a rule about where a field may be read+// is only enforceable when the reads have a named home.+func (s *Store) registerSession(session *Session, now time.Time) (snapshotJob, bool) {+ s.mu.Lock()+ defer s.mu.Unlock()+ session.ExpiresAt = now.Add(s.cfg.MaxLifetime)+ s.sessions[session.ID] = session+ s.byTokenHash[session.TokenHash] = session+ return s.snapshotLocked()+}+// Authenticate validates a token and returns the associated session.// It updates LastSeenAt on success.func (s *Store) Authenticate(token string) (*Session, bool) {@@ -553,8 +560,8 @@ func (sess *Session) toPersisted() persistedSession {// toSession maps an on-disk record back to an in-memory Session, decoding and// validating the token hash. ok=false means the record is malformed and should-// be skipped. idleTimeout is injected from store config (not persisted).-func (rec persistedSession) toSession(idleTimeout time.Duration) (*Session, bool) {+// be skipped.+func (rec persistedSession) toSession() (*Session, bool) {tokenHash, err := hex.DecodeString(strings.TrimSpace(rec.TokenHash))if err != nil || len(tokenHash) != sha256.Size {return nil, false@@ -563,17 +570,16 @@ func (rec persistedSession) toSession(idleTimeout time.Duration) (*Session, boolcopy(hash[:], tokenHash)return &Session{- ID: rec.ID,- AgentID: rec.AgentID,- Label: rec.Label,- Browser: rec.Browser,- TokenHash: hash,- CreatedAt: rec.CreatedAt,- LastSeenAt: rec.LastSeenAt,- ExpiresAt: rec.ExpiresAt,- IdleTimeout: idleTimeout,- Status: rec.Status,- Grants: append([]string(nil), rec.Grants...),+ ID: rec.ID,+ AgentID: rec.AgentID,+ Label: rec.Label,+ Browser: rec.Browser,+ TokenHash: hash,+ CreatedAt: rec.CreatedAt,+ LastSeenAt: rec.LastSeenAt,+ ExpiresAt: rec.ExpiresAt,+ Status: rec.Status,+ Grants: append([]string(nil), rec.Grants...),}, true}@@ -596,7 +602,7 @@ func (s *Store) loadPersisted() {now := s.now()for _, rec := range persisted.Sessions {- sess, ok := rec.toSession(s.cfg.IdleTimeout)+ sess, ok := rec.toSession()if !ok {continue}