High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: eliminate data races in session store auth and config accessors
Luigi Agosti525e7e85c7e8
diff --git a/internal/session/store.go b/internal/session/store.goindex 763c5784..b705707c 100644--- a/internal/session/store.go+++ b/internal/session/store.go@@ -261,7 +261,7 @@ func (s *Store) authenticate(token string, touch bool) (*Session, bool) {sess.LastSeenAt = nowjob, persist = s.maybeSnapshotTouchLocked(now)}- match = sess+ match = cloneSessionLocked(sess)ok = true}()@@ -307,9 +307,16 @@ func (s *Store) Touch(sessionID string) bool {return true}-// Get returns a defensive copy of a session by its public ID. Callers must not-// be able to mutate store-owned state outside the store lock, so the Grants-// slice is cloned rather than aliased.+// cloneSessionLocked returns a copy no caller can use to mutate store-owned+// state outside the store lock: the Grants slice is cloned rather than aliased.+// Caller must hold s.mu.+func cloneSessionLocked(sess *Session) *Session {+ cp := *sess+ cp.Grants = append([]string(nil), sess.Grants...)+ return &cp+}++// Get returns a defensive copy of a session by its public ID.func (s *Store) Get(sessionID string) (*Session, bool) {if s == nil {return nil, false@@ -320,13 +327,10 @@ func (s *Store) Get(sessionID string) (*Session, bool) {if !ok {return nil, false}- cp := *sess- cp.Grants = append([]string(nil), sess.Grants...)- return &cp, true+ return cloneSessionLocked(sess), true}-// List returns defensive copies of all sessions. Each element's Grants slice is-// cloned so callers cannot mutate store-owned state through the returned values.+// List returns defensive copies of all sessions.func (s *Store) List() []Session {if s == nil {return nil@@ -336,9 +340,7 @@ func (s *Store) List() []Session {out := make([]Session, 0, len(s.sessions))for _, sess := range s.sessions {- cp := *sess- cp.Grants = append([]string(nil), sess.Grants...)- out = append(out, cp)+ out = append(out, *cloneSessionLocked(sess))}return out}@@ -419,6 +421,8 @@ func (s *Store) Enabled() bool {if s == nil {return false}+ s.mu.Lock()+ defer s.mu.Unlock()return s.cfg.Enabled}@@ -427,6 +431,8 @@ func (s *Store) Mode() string {if s == nil {return "off"}+ s.mu.Lock()+ defer s.mu.Unlock()return s.cfg.Mode}@@ -563,6 +569,7 @@ func (s *Store) loadPersisted() {type snapshotJob struct {snapshot persistedStoreseq uint64+ path string}// snapshotLocked builds a self-contained value-copy snapshot of every session@@ -580,7 +587,7 @@ func (s *Store) snapshotLocked() (snapshotJob, bool) {for _, sess := range s.sessions {snapshot.Sessions = append(snapshot.Sessions, sess.toPersisted())}- return snapshotJob{snapshot: snapshot, seq: s.saveSeq}, true+ return snapshotJob{snapshot: snapshot, seq: s.saveSeq, path: s.cfg.PersistPath}, true}// maybeSnapshotTouchLocked builds a snapshot for a LastSeen-only update at most@@ -599,6 +606,9 @@ func (s *Store) maybeSnapshotTouchLocked(now time.Time) (snapshotJob, bool) {// serialize on saveMu; a snapshot older than one already written is skipped so a// stale snapshot can never clobber a fresher one.func (s *Store) writeSnapshot(job snapshotJob) {+ if job.path == "" {+ return+ }s.saveMu.Lock()defer s.saveMu.Unlock()if job.seq <= s.writtenSeq {@@ -610,15 +620,14 @@ func (s *Store) writeSnapshot(job snapshotJob) {if err != nil {return}- if err := os.MkdirAll(filepath.Dir(s.cfg.PersistPath), 0755); err != nil {+ if err := os.MkdirAll(filepath.Dir(job.path), 0755); err != nil {return}- // Atomic write: temp file + rename- tmpPath := s.cfg.PersistPath + ".tmp"+ tmpPath := job.path + ".tmp"if err := os.WriteFile(tmpPath, data, 0600); err != nil {return}- _ = os.Rename(tmpPath, s.cfg.PersistPath)+ _ = os.Rename(tmpPath, job.path)}func generateSessionID() (string, error) {diff --git a/internal/session/store_concurrency_test.go b/internal/session/store_concurrency_test.goindex 95ff447c..49483a98 100644--- a/internal/session/store_concurrency_test.go+++ b/internal/session/store_concurrency_test.go@@ -81,8 +81,8 @@ func TestStore_WriteSnapshotSkipsStale(t *testing.T) {path := filepath.Join(t.TempDir(), "sessions.json")s := NewStore(Config{Enabled: true, PersistPath: path, IdleTimeout: time.Hour, MaxLifetime: 24 * time.Hour})- fresh := snapshotJob{snapshot: persistedStore{SavedAt: time.Unix(200, 0).UTC()}, seq: 5}- stale := snapshotJob{snapshot: persistedStore{SavedAt: time.Unix(100, 0).UTC()}, seq: 3}+ fresh := snapshotJob{snapshot: persistedStore{SavedAt: time.Unix(200, 0).UTC()}, seq: 5, path: path}+ stale := snapshotJob{snapshot: persistedStore{SavedAt: time.Unix(100, 0).UTC()}, seq: 3, path: path}s.writeSnapshot(fresh)s.writeSnapshot(stale) // lower seq → must be skippeddiff --git a/internal/session/store_race_test.go b/internal/session/store_race_test.gonew file mode 100644index 00000000..0c866263--- /dev/null+++ b/internal/session/store_race_test.go@@ -0,0 +1,62 @@+package session++import (+ "sync"+ "testing"+)++// Authenticate must hand back a defensive copy like Get/List do. The middleware+// keeps the returned session for the whole request (grant checks, request+// context), so a store-owned pointer races with concurrent SetGrants/Touch.+func TestAuthenticateReturnsDefensiveCopy(t *testing.T) {+ s := NewStore(Config{Enabled: true, Mode: "required"})+ id, token, err := s.Create("agent-1", "", "")+ if err != nil {+ t.Fatalf("create: %v", err)+ }++ sess, ok := s.Authenticate(token)+ if !ok || sess == nil {+ t.Fatal("authenticate should succeed")+ }++ var wg sync.WaitGroup+ wg.Add(2)+ go func() {+ defer wg.Done()+ for i := 0; i < 500; i++ {+ s.SetGrants(id, []string{"GET /snapshot", "POST /action"})+ }+ }()+ go func() {+ defer wg.Done()+ for i := 0; i < 500; i++ {+ _ = len(sess.Grants)+ _ = sess.LastSeenAt+ }+ }()+ wg.Wait()+}++// Enabled/Mode are read on every authenticated request; UpdateConfig replaces+// the whole config struct, so unsynchronized reads race.+func TestConfigAccessorsAreSynchronized(t *testing.T) {+ s := NewStore(Config{Enabled: true, Mode: "preferred"})++ var wg sync.WaitGroup+ wg.Add(2)+ go func() {+ defer wg.Done()+ for i := 0; i < 500; i++ {+ s.UpdateConfig(Config{Enabled: i%2 == 0, Mode: "required"})+ }+ }()+ go func() {+ defer wg.Done()+ for i := 0; i < 500; i++ {+ _ = s.Enabled()+ _ = s.Mode()+ }+ }()+ wg.Wait()+}