Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): enforce persisted session ownership
Josuée94390c60800
diff --git a/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts b/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.tsindex d2d42a524..9fa8a55d7 100644--- a/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts+++ b/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts@@ -45,7 +45,7 @@ describe('ConversationManager.listSessionsForUser', () => {it('extracts agent and chatId correctly even if auth.sub contains a colon', async () => {const keyWithColonSub = `admin:u-99:rpc:agent-y:chat-7`- await manager.getOrCreate(keyWithColonSub)+ await manager.getOrCreate(keyWithColonSub, { userId: 'admin:u-99' })const result = manager.listSessionsForUser('admin:u-99:rpc:')expect(result).toHaveLength(1)expect(result[0].agent).toBe('agent-y')@@ -109,4 +109,16 @@ describe('ConversationManager.getSessionByKey', () => {await manager.getOrCreate(keyA)expect(manager.getSessionByKey(keyB)).toBeUndefined()})++ it('fails authenticated exact-key reads closed on an ownership mismatch', async () => {+ const ownerUserId = 'subject:rpc:embedded'+ const key = `${ownerUserId}:rpc:agent-x:chat-1`+ const conv = await manager.getOrCreate(key, { userId: ownerUserId })++ await expect(manager.getSessionByKeyForUserAsync(key, ownerUserId)).resolves.toBe(conv)+ await expect(manager.getSessionByKeyForUserAsync(key, 'subject')).resolves.toBeUndefined()+ await expect(manager.getOrCreate(key, { userId: 'subject' })).rejects.toThrow(+ 'Session ownership mismatch'+ )+ })})diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.tsindex 24d29f7ce..338e0a919 100644--- a/mcp-host/src/core/conversation/conversation.ts+++ b/mcp-host/src/core/conversation/conversation.ts@@ -1,3 +1,4 @@+import { parseSessionKey } from '../../session/types'import { ConversationError, ConversationErrorCode } from '../errors'import { isMcpToolName } from '../extensions/mcpApprovalGateController'import {@@ -19,6 +20,7 @@ import {SessionListQuery,SessionMessagesQuery,} from './conversationStore'+import { userIdFromRpcPrefix } from './sessionKeyParts'/*** Manages conversation state and turn tracking.@@ -78,15 +80,23 @@ export class ConversationManager {*/async getOrCreate(sessionKey: string, opts?: GetOrCreateOptions): Promise<Conversation> {const cached = this.store.get(sessionKey)- if (cached) return cached+ if (cached) {+ this.assertSessionOwner(cached, opts?.userId)+ return cached+ }const loaded = await this.store.getOrLoad(sessionKey)- if (loaded) return loaded+ if (loaded) {+ this.assertSessionOwner(loaded, opts?.userId)+ return loaded+ }++ const parsed = parseSessionKey(sessionKey)const conv: Conversation = {id: `conv-${sessionKey}-${Date.now()}`,session_key: sessionKey,- user_id: opts?.userId ?? sessionKey,+ user_id: opts?.userId ?? parsed?.userId ?? sessionKey,state: ConversationState.Idle,turns: [],auto_approved_tools: new Set(),@@ -113,6 +123,8 @@ export class ConversationManager {agent: stringchatId: string}> {+ const userId = userIdFromRpcPrefix(keyPrefix)+ if (!userId) return []const out = [] as Array<{key: stringconversation: Conversation@@ -120,6 +132,7 @@ export class ConversationManager {chatId: string}>for (const { key, conversation } of this.store.listByPrefix(keyPrefix)) {+ if (conversation.user_id !== userId) continueconst rest = key.slice(keyPrefix.length)const colonIdx = rest.indexOf(':')if (colonIdx < 0) continue@@ -191,6 +204,21 @@ export class ConversationManager {return this.store.getOrLoad(key)}+ /** Authenticated exact-key lookup that treats persisted ownership as authoritative. */+ async getSessionByKeyForUserAsync(+ key: string,+ userId: string+ ): Promise<Conversation | undefined> {+ const conversation = await this.store.getOrLoad(key)+ return conversation?.user_id === userId ? conversation : undefined+ }++ private assertSessionOwner(conversation: Conversation, expectedUserId?: string): void {+ if (expectedUserId !== undefined && conversation.user_id !== expectedUserId) {+ throw new Error('Session ownership mismatch')+ }+ }+/*** Start a new turn in the conversation.* Transitions: Idle → Processingdiff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex e6d7055ad..94eedd7a8 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -6,7 +6,7 @@ import {type Turn,type TurnToolCall,} from '../types'-import { sessionPartsFromPrefixedKey } from './sessionKeyParts'+import { sessionPartsFromPrefixedKey, userIdFromRpcPrefix } from './sessionKeyParts'/*** Token usage from a SINGLE LLM call, accumulated additively into the durable@@ -384,8 +384,11 @@ export class InMemoryConversationStore implements ConversationStore {prefix: string,query: SessionListQuery = {}): Promise<ConversationSessionSummary[]> {+ const userId = userIdFromRpcPrefix(prefix, query.agent)+ if (!userId) return []const summaries: ConversationSessionSummary[] = []for (const { key, conversation } of this.listByPrefix(prefix)) {+ if (conversation.user_id !== userId) continueconst parts = sessionPartsFromPrefixedKey(key, prefix, query.agent)if (!parts) continuesummaries.push({@@ -432,7 +435,8 @@ export class InMemoryConversationStore implements ConversationStore {query: SessionMessagesQuery = {}): Promise<ConversationSessionMessages | undefined> {const conversation = this.map.get(key)- if (!conversation) return undefined+ const userId = userIdFromRpcPrefix(prefix)+ if (!conversation || !userId || conversation.user_id !== userId) return undefinedreturn sessionMessagesFromConversation(key, prefix, conversation, query)}diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex 9217984f5..d2e45b43e 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -378,33 +378,54 @@ describe('SqliteConversationStore — session summary listing', () => {}})- it('keeps unscoped parsing stable when the user subject contains :rpc:', async () => {+ it('fails closed when colon-bearing user subjects have overlapping key prefixes', async () => {const handle = await freshStore({ cacheSize: 4 })try {const manager = new ConversationManager(handle.store)- const userId = 'subject:rpc:embedded'- const key = `${userId}:rpc:agent-x:chat-1`- // Catalog visibility remains keyed by the authenticated prefix even when- // an older persistence path derived user_id differently.- const conversation = await manager.getOrCreate(key)+ const callerUserId = 'subject'+ const ownerUserId = 'subject:rpc:embedded'+ const key = `${ownerUserId}:rpc:agent-x:chat-1`+ const conversation = await manager.getOrCreate(key, {+ userId: ownerUserId,+ channelType: 'rpc',+ channelId: 'agent-x',+ threadId: 'chat-1',+ source: 'rpc',+ })await manager.startTurn(conversation, 'hello', 'task-1')await manager.completeTurn(conversation, 'done')await handle.persistQueue.drainSessionKey(key)- handle.store['cache'].clear()- const summaries = await handle.store.listSessionSummariesByPrefix(`${userId}:rpc:`)+ await expect(+ handle.store.getSessionMessagesByKey(key, `${callerUserId}:rpc:`)+ ).resolves.toBeUndefined()+ handle.store['cache'].clear()- expect(summaries.map(session => [session.agent, session.chatId])).toEqual([+ const ownerSummaries = await handle.store.listSessionSummariesByPrefix(+ `${ownerUserId}:rpc:`+ )+ expect(ownerSummaries.map(session => [session.agent, session.chatId])).toEqual([['agent-x', 'chat-1'],])+ const callerSummaries = await handle.store.listSessionSummariesByPrefix(+ `${callerUserId}:rpc:`+ )+ expect(callerSummaries).toEqual([])+ await expect(+ handle.store.getSessionMessagesByKey(key, `${callerUserId}:rpc:`)+ ).resolves.toBeUndefined()+handle.worker.db.prepare('UPDATE sessions SET user_id = NULL WHERE id = ?').run(conversation.id)- const legacySummaries = await handle.store.listSessionSummariesByPrefix(`${userId}:rpc:`)- expect(legacySummaries.map(session => [session.agent, session.chatId])).toEqual([- ['agent-x', 'chat-1'],- ])+ const ambiguousLegacySummaries = await handle.store.listSessionSummariesByPrefix(+ `${ownerUserId}:rpc:`+ )+ expect(ambiguousLegacySummaries).toEqual([])+ await expect(+ handle.store.getSessionMessagesByKey(key, `${ownerUserId}:rpc:`)+ ).resolves.toBeUndefined()} finally {await handle.shutdown()}diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 0a04dd116..c4caba9be 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -43,7 +43,7 @@ import {type SessionTokenUsage,boundedTurns,} from '../conversationStore'-import { sessionPartsFromPrefixedKey } from '../sessionKeyParts'+import { sessionPartsFromPrefixedKey, userIdFromRpcPrefix } from '../sessionKeyParts'import type { PersistQueue } from './persistQueue'import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'import {@@ -357,9 +357,7 @@ export class SqliteConversationStore implements ConversationStore {prefix: string,query: SessionListQuery = {}): Promise<ConversationSessionSummary[]> {- const suffix = query.agent === undefined ? ':rpc:' : `:rpc:${query.agent}:`- if (!prefix.endsWith(suffix)) return []- const userId = prefix.slice(0, -suffix.length)+ const userId = userIdFromRpcPrefix(prefix, query.agent)if (!userId) return []await this.persistQueue.drainPrefix(prefix)const rows = await this.persistQueue.enqueueSync<PersistedSessionSummary[]>({@@ -417,9 +415,12 @@ export class SqliteConversationStore implements ConversationStore {query: SessionMessagesQuery = {}): Promise<ConversationSessionMessages | undefined> {const cached = this.cache.get(sessionKey)+ const userId = userIdFromRpcPrefix(prefix)+ if (!userId) return undefinedconst parts = sessionPartsFromPrefixedKey(sessionKey, prefix)if (!parts) return undefinedif (cached) {+ if (cached.user_id !== userId) return undefinedconst turns = boundedTurns(cached.turns, query)return {key: sessionKey,@@ -455,7 +456,7 @@ export class SqliteConversationStore implements ConversationStore {},sessionKey)- if (!page) return undefined+ if (!page || page.session.user_id !== userId) return undefinedreturn {key: sessionKey,diff --git a/mcp-host/src/core/conversation/sessionKeyParts.ts b/mcp-host/src/core/conversation/sessionKeyParts.tsindex 108593284..00cb5cbe5 100644--- a/mcp-host/src/core/conversation/sessionKeyParts.ts+++ b/mcp-host/src/core/conversation/sessionKeyParts.ts@@ -32,3 +32,15 @@ export function sessionPartsFromPrefixedKey(chatId: rest.slice(colonIndex + 1),}}++/**+ * Extract the trusted user ID from an RPC catalog/transcript prefix. The suffix+ * is removed from the end instead of splitting on `:rpc:` because authenticated+ * subjects may themselves contain that sequence.+ */+export function userIdFromRpcPrefix(prefix: string, scopedAgent?: string): string | null {+ const suffix = scopedAgent === undefined ? ':rpc:' : `:rpc:${scopedAgent}:`+ if (!prefix.endsWith(suffix)) return null+ const userId = prefix.slice(0, -suffix.length)+ return userId || null+}diff --git a/mcp-host/src/db/migrations/__tests__/011-session-summary-user-activity-index.test.ts b/mcp-host/src/db/migrations/__tests__/011-session-summary-user-activity-index.test.tsindex 07e2c449d..e21b1712f 100644--- a/mcp-host/src/db/migrations/__tests__/011-session-summary-user-activity-index.test.ts+++ b/mcp-host/src/db/migrations/__tests__/011-session-summary-user-activity-index.test.ts@@ -5,7 +5,7 @@ import * as m011 from '../011-session-summary-user-activity-index'import { migrations } from '../index'describe('migration 011 — session summary user/activity index', () => {- it('serves current rows by activity and legacy rows by session-key range', () => {+ it('serves owned rows without sorting unbounded catalog candidates', () => {const db = new Database(':memory:')for (const migration of migrations) migration.up(db)@@ -33,7 +33,11 @@ describe('migration 011 — session summary user/activity index', () => {}) as Array<{ detail: string }>expect(plan.some(step => step.detail.includes('idx_sessions_summary_activity'))).toBe(true)- expect(plan.some(step => step.detail.includes('idx_sessions_session_key'))).toBe(true)+ // The approval join may sort the already-limited page once. A second sort+ // means the catalog candidates were materialized before LIMIT.+ expect(plan.filter(step => step.detail.includes('USE TEMP B-TREE FOR ORDER BY'))).toHaveLength(+ 1+ )m011.down(db)const downgraded = dbdiff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex 8b6204bb8..96c160516 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -239,27 +239,13 @@ export function prepareStatements(db: Database): PreparedStatements {SELECT * FROM sessions WHERE session_key LIKE ? ORDER BY started_at DESC`),selectSessionSummariesByPrefix: db.prepare(`- WITH candidate_sessions AS (- -- Current rows take the user/activity index fast path. The second arm- -- preserves catalog visibility for legacy rows whose nullable user_id- -- was absent or derived differently; the authenticated key range still- -- provides the tenant boundary for both arms.+ WITH scoped_sessions AS (SELECT *- FROM sessions+ FROM sessionsWHERE user_id = @user_idAND session_key >= @prefix_startAND session_key < @prefix_end- UNION ALL- SELECT *- FROM sessions- WHERE (user_id IS NULL OR user_id <> @user_id)- AND session_key >= @prefix_start- AND session_key < @prefix_end- ),- scoped_sessions AS (- SELECT *- FROM candidate_sessions- WHERE (+ AND ((@agent_scoped = 1 AND length(session_key) > length(@prefix_start))OR(diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex ab633837b..787f1ecea 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2140,11 +2140,10 @@ async function startRPCServer(): Promise<void> {const handleContextBreakdown = async (userSub: string, agentName: string, chatId: string) => {const convManager = agent!.getConversationManager()- // Same O(1) key lookup + anti-enumeration semantics as handleSessionMessages:- // the userSub comes from the verified rpc edge caller (routes.ts), never a- // client param, so a caller cannot read another user's session.+ // Same O(1) key lookup + ownership check as handleSessionMessages: userSub+ // comes from the verified edge caller and must match persisted ownership.const key = `${userSub}:rpc:${agentName}:${chatId}`- const conversation = await convManager.getSessionByKeyAsync(key)+ const conversation = await convManager.getSessionByKeyForUserAsync(key, userSub)if (!conversation) return null// `breakdown: null` when the session exists but has no snapshot yet (cold-load// before the first turn) — distinct from the 404 the route returns for a@@ -2180,7 +2179,9 @@ async function startRPCServer(): Promise<void> {channelId: hostRef,threadId: chatId,})- const conversation = await agent!.getConversationManager().getSessionByKeyAsync(key)+ const conversation = await agent!+ .getConversationManager()+ .getSessionByKeyForUserAsync(key, userSub)const saved = conversation?.modelSelections?.[provider]if (saved) {const resolution = resolveSessionModel(