diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go index 586bb7981..754c75671 100644 --- a/internal/gateway/session_commands.go +++ b/internal/gateway/session_commands.go @@ -38,7 +38,10 @@ func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channel t.mu.RLock() id, ok := t.active[key] t.mu.RUnlock() - if ok { + // An empty cached value is treated as a miss rather than an answer, so a + // poisoned entry repairs itself instead of persisting every subsequent + // message under session "". + if ok && id != "" { return id, nil } @@ -100,7 +103,7 @@ func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channel func (t *sessionTracker) cacheActive(key, sessionID string) string { t.mu.Lock() defer t.mu.Unlock() - if existing, ok := t.active[key]; ok { + if existing, ok := t.active[key]; ok && existing != "" { return existing } t.active[key] = sessionID @@ -117,11 +120,37 @@ func sessionKeyFromFields(channelID, threadID string) string { // setActive sets the current session for a channel+thread, overriding any // previously resolved session (used by /new, /branch and /topic). func (t *sessionTracker) setActive(channelID, threadID, sessionID string) { + // An empty session ID is never meaningful, and caching one is actively + // destructive: resolve treats map presence as authoritative, so a "" here + // makes every later message in this chat persist under session "" with no + // way to recover. Rejecting it at the setter means no caller can poison + // the map, whatever it computes. + if sessionID == "" { + return + } t.mu.Lock() defer t.mu.Unlock() t.active[sessionTrackerKey(channelID, threadID)] = sessionID } +// flattenTopic points a channel's flat key at whatever session its thread is +// currently using, in one critical section. +// +// Doing this as setActive(get(...)) was two separate critical sections, so a +// /resume or /branch landing between them was silently clobbered by the value +// read before the switch. +func (t *sessionTracker) flattenTopic(channelID, threadID string) { + t.mu.Lock() + defer t.mu.Unlock() + current, ok := t.active[sessionTrackerKey(channelID, threadID)] + if !ok || current == "" { + // Nothing to carry over. The next message resolves from the store, + // which is the correct answer anyway. + return + } + t.active[sessionTrackerKey(channelID, "")] = current +} + // getActive returns the current session ID for a channel+thread. func (t *sessionTracker) getActive(channelID, threadID string) string { t.mu.RLock() @@ -212,7 +241,7 @@ func (r *Router) handleTopic(ctx context.Context, msg Message, rest string) (str switch rest { case "off": - r.sessionTracker.setActive(msg.ChannelID, "", r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)) + r.sessionTracker.flattenTopic(msg.ChannelID, msg.ThreadID) return "Topic routing disabled. Messages will use the General topic.", nil case "help": return topicHelpText(), nil diff --git a/internal/gateway/session_topic_test.go b/internal/gateway/session_topic_test.go new file mode 100644 index 000000000..c0843187b --- /dev/null +++ b/internal/gateway/session_topic_test.go @@ -0,0 +1,104 @@ +package gateway + +import ( + "context" + "testing" +) + +// /topic off copied the thread's active session onto the flat key. When +// nothing was cached for that thread it copied the empty string -- and +// resolve treats map presence as authoritative, so it returned "" from then +// on, permanently. Every later message in the chat persisted under session +// ID "", history was shared with any other poisoned chat, and the turn-lane +// key became "" so /stop in one chat cancelled a turn in another. +// +// Reachable as a first message on the webhook and email channels, which call +// Route directly without resolving a session first. +func TestTopicOffDoesNotPoisonTheCache(t *testing.T) { + tests := []struct { + name string + // preResolve simulates a channel that resolves before routing (as + // telegram's submitTurn does) versus one that does not. + preResolve bool + }{ + {name: "no session resolved yet"}, + {name: "session already resolved", preResolve: true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + store := NewSessionStoreMemory("test-node") + t.Cleanup(func() { _ = store.Close() }) + + r := NewRouter(nil, nil, "telegram") + r.InitSessions(store) + r.Identity = "archie" + + var want string + if tc.preResolve { + id, err := r.sessionTracker.resolve(ctx, "telegram", "", "chat-x", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + want = id + } + + if _, err := r.Route(ctx, Message{Text: "/topic off", ChannelID: "chat-x"}); err != nil { + t.Fatalf("Route(/topic off): %v", err) + } + + got, err := r.sessionTracker.resolve(ctx, "telegram", "", "chat-x", "") + if err != nil { + t.Fatalf("resolve after /topic off: %v", err) + } + if got == "" { + t.Fatal("resolve returned an empty session ID: the cache was poisoned " + + "and every later message would persist under session \"\"") + } + if tc.preResolve && got != want { + t.Errorf("resolve = %q, want the session that was already active %q", got, want) + } + + // Sticky check: the damage previously survived repeat calls + // because cacheActive also returned the empty existing value. + again, err := r.sessionTracker.resolve(ctx, "telegram", "", "chat-x", "") + if err != nil { + t.Fatalf("resolve (repeat): %v", err) + } + if again != got { + t.Errorf("resolve is unstable: %q then %q", got, again) + } + }) + } +} + +// An empty session ID is never a meaningful value to cache. Rejecting it at +// the setter means no caller can poison the map, whatever it computes. +func TestSetActiveRejectsAnEmptySession(t *testing.T) { + store := NewSessionStoreMemory("test-node") + t.Cleanup(func() { _ = store.Close() }) + tr := newSessionTracker(store) + + tr.setActive("chat-1", "", "real-session") + tr.setActive("chat-1", "", "") + + if got := tr.getActive("chat-1", ""); got != "real-session" { + t.Errorf("getActive = %q, want the previous value %q: an empty set must not "+ + "overwrite a real session", got, "real-session") + } + + tr.setActive("chat-2", "", "") + if got := tr.getActive("chat-2", ""); got != "" { + t.Errorf("getActive = %q, want empty", got) + } + // The key must be absent, not present-and-empty: resolve treats presence + // as authoritative. + id, err := tr.resolve(context.Background(), "telegram", "", "chat-2", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + if id == "" { + t.Fatal("resolve returned empty: an empty setActive left a poisoned entry") + } +}