Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): isolate malformed pending approvals

Josuéab625975e48b
diff --git a/mcp-host/src/core/conversation/__tests__/sessionKeyParts.test.ts b/mcp-host/src/core/conversation/__tests__/sessionKeyParts.test.ts
index 1292d6db7..d1d571d55 100644
--- a/mcp-host/src/core/conversation/__tests__/sessionKeyParts.test.ts
+++ b/mcp-host/src/core/conversation/__tests__/sessionKeyParts.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest'
-import { sessionPartsFromPrefixedKey } from '../sessionKeyParts'
+import {
+ sessionPartsFromPrefixedKey,
+ userIdFromStructuredSessionKey,
+} from '../sessionKeyParts'
describe('sessionPartsFromPrefixedKey', () => {
it('preserves scoped chat ids when the explicit agent matches the prefix', () => {
@@ -25,3 +28,43 @@ describe('sessionPartsFromPrefixedKey', () => {
})
})
})
+
+describe('userIdFromStructuredSessionKey', () => {
+ it('preserves a colon-bearing owner by removing only the exact suffix', () => {
+ expect(
+ userIdFromStructuredSessionKey({
+ sessionKey: 'subject:rpc:embedded:rpc:agent-x:chat-1',
+ channelType: 'rpc',
+ channelId: 'agent-x',
+ threadId: 'chat-1',
+ })
+ ).toBe('subject:rpc:embedded')
+ })
+
+ it('uses serialized defaults and rejects missing or mismatched structure', () => {
+ expect(
+ userIdFromStructuredSessionKey({
+ sessionKey: 'subject:rpc:default:default',
+ channelType: 'rpc',
+ channelId: null,
+ threadId: null,
+ })
+ ).toBe('subject')
+ expect(
+ userIdFromStructuredSessionKey({
+ sessionKey: 'subject:rpc:agent-x:chat-1',
+ channelType: 'rpc',
+ channelId: 'other-agent',
+ threadId: 'chat-1',
+ })
+ ).toBeNull()
+ expect(
+ userIdFromStructuredSessionKey({
+ sessionKey: 'subject:rpc:agent-x:chat-1',
+ channelType: null,
+ channelId: 'agent-x',
+ threadId: 'chat-1',
+ })
+ ).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/conversation/persistence/__tests__/crossPodRestart.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/crossPodRestart.test.ts
index b10f906b0..892304512 100644
--- a/mcp-host/src/core/conversation/persistence/__tests__/crossPodRestart.test.ts
+++ b/mcp-host/src/core/conversation/persistence/__tests__/crossPodRestart.test.ts
@@ -4,7 +4,7 @@
* worker terminates, "Pod B" rehydrates the store and finds the same
* approval — the user retry no longer races a phantom in-memory state.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
@@ -153,6 +153,60 @@ describe('Cross-pod-restart resume — P.3 invariant #3', () => {
}
})
+ it('skips an unauthorized pending approval without rejecting agent bootstrap', async () => {
+ const pod = makeSqliteStore({ dbPath, cacheSize: 4 })
+ const manager = new ConversationManager(pod.store)
+ const sessionKey = 'user-1:rpc:agent:default'
+ const conv = await manager.getOrCreate(sessionKey, {
+ userId: 'user-1',
+ channelType: 'rpc',
+ channelId: 'agent',
+ source: 'rpc',
+ })
+ await manager.startTurn(conv, 'needs approval', 'task-unsafe-owner')
+ await manager.suspendForApproval(conv, {
+ request_id: 'req-unsafe-owner',
+ tool_name: 'shell_exec',
+ tool_call_id: 'tc-unsafe-owner',
+ parameters: {},
+ description: 'unsafe owner fixture',
+ context_snapshot: [],
+ })
+ pod.worker.db
+ .prepare('UPDATE sessions SET user_id = ? WHERE id = ?')
+ .run('different-owner', conv.id)
+ pod.store['cache'].clear()
+ pod.store['ordinals'].clear()
+ pod.store['sessionKeyById'].clear()
+
+ const agent = new AgentStateMachine(new MessageQueue(), new TaskLifecycle(), {
+ autoStart: false,
+ })
+ agent.setLLMProvider({
+ completeSingleTurn: async () => ({ content: 'done' }),
+ completeSingleTurnWithTools: async () => ({ type: 'response', content: 'done' }),
+ getProviderType: () => 'openai',
+ } as never)
+ agent.setMcpManager({ getAllTools: () => [], callTool: async () => ({}) } as never)
+ agent.setConversationStore(pod.store)
+ agent.setColdStartLoader(new SqliteColdStartLoader(pod.store))
+ const log = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ try {
+ await expect(agent.bootstrap()).resolves.toBeUndefined()
+ expect(agent.getPendingApprovals()).toEqual([])
+ expect(log).toHaveBeenCalledWith(
+ expect.stringContaining('CONV_OWNERSHIP_MISMATCH')
+ )
+ await expect(
+ manager.getOrCreate(sessionKey, { userId: 'user-1' })
+ ).rejects.toMatchObject({ code: 'CONV_OWNERSHIP_MISMATCH' })
+ } finally {
+ log.mockRestore()
+ await pod.shutdown()
+ }
+ })
+
it('D.2 — a processing session left by a crashed Pod A is reaped on Pod B boot, then usable', async () => {
// Pod A — start a turn but crash (shutdown) before completing it.
const podA = makeSqliteStore({ dbPath, cacheSize: 4 })
diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
index c4caba9be..bbb6d8cbb 100644
--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
@@ -24,6 +24,7 @@ import type {
SessionRow,
} from '../../../db/worker/protocol'
import { parseSessionKey } from '../../../session/types'
+import { ConversationError, ConversationErrorCode } from '../../errors'
import {
type ChatMessage,
type Conversation,
@@ -43,7 +44,11 @@ import {
type SessionTokenUsage,
boundedTurns,
} from '../conversationStore'
-import { sessionPartsFromPrefixedKey, userIdFromRpcPrefix } from '../sessionKeyParts'
+import {
+ sessionPartsFromPrefixedKey,
+ userIdFromRpcPrefix,
+ userIdFromStructuredSessionKey,
+} from '../sessionKeyParts'
import type { PersistQueue } from './persistQueue'
import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'
import {
@@ -489,6 +494,28 @@ export class SqliteConversationStore implements ConversationStore {
const out: PersistedSessionListing[] = []
for (const row of rows) {
const sessionKey = row.session_key
+ const derivedOwner = userIdFromStructuredSessionKey({
+ sessionKey,
+ channelType: row.ownership.channel_type,
+ channelId: row.ownership.channel_id,
+ threadId: row.ownership.thread_id,
+ })
+ if (!derivedOwner || row.ownership.user_id !== derivedOwner) {
+ const error = new ConversationError(
+ 'Pending approval session ownership could not be verified',
+ ConversationErrorCode.OwnershipMismatch
+ )
+ console.error(
+ JSON.stringify({
+ level: 'error',
+ event: 'pending_approval_ownership_rejected',
+ code: error.code,
+ requestId: row.approval.request_id,
+ reason: derivedOwner ? 'owner_mismatch' : 'unverifiable_session_suffix',
+ })
+ )
+ continue
+ }
let conv = this.cache.get(sessionKey)
if (!conv) {
// Chain after pending per-session writes (same rationale as getOrLoad).
diff --git a/mcp-host/src/core/conversation/sessionKeyParts.ts b/mcp-host/src/core/conversation/sessionKeyParts.ts
index 00cb5cbe5..3857d550b 100644
--- a/mcp-host/src/core/conversation/sessionKeyParts.ts
+++ b/mcp-host/src/core/conversation/sessionKeyParts.ts
@@ -3,6 +3,32 @@ export interface AgentChatSessionParts {
chatId: string
}
+export interface StructuredSessionKeyParts {
+ sessionKey: string
+ channelType: string | null
+ channelId: string | null
+ threadId: string | null
+}
+
+/**
+ * Recover the owner only when persisted structured columns prove the complete
+ * serialized suffix. The owner prefix may contain any number of `:` characters;
+ * parsing from the front would therefore cross tenant boundaries.
+ */
+export function userIdFromStructuredSessionKey(
+ parts: StructuredSessionKeyParts
+): string | null {
+ if (!parts.channelType || !parts.channelType.trim()) return null
+ const channelId = parts.channelId || 'default'
+ const threadId = parts.threadId || 'default'
+ const suffix = `:${parts.channelType}:${channelId}:${threadId}`
+ if (parts.sessionKey.length <= suffix.length || !parts.sessionKey.endsWith(suffix)) {
+ return null
+ }
+ const userId = parts.sessionKey.slice(0, -suffix.length)
+ return userId.trim() ? userId : null
+}
+
/**
* Parse a key relative to the exact prefix used to fetch it.
*
diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.ts
index ceb3e7c2e..c39676a97 100644
--- a/mcp-host/src/db/statements.ts
+++ b/mcp-host/src/db/statements.ts
@@ -402,7 +402,12 @@ export function prepareStatements(db: Database): PreparedStatements {
DELETE FROM pending_approvals WHERE request_id = ?
`),
selectPendingApprovalsAll: db.prepare(`
- SELECT pa.*, s.session_key AS session_key
+ SELECT pa.*,
+ s.session_key AS session_key,
+ s.user_id AS session_user_id,
+ s.channel_type AS session_channel_type,
+ s.channel_id AS session_channel_id,
+ s.thread_id AS session_thread_id
FROM pending_approvals pa
JOIN sessions s
ON s.id = pa.session_id
diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.ts
index 11f6c2eed..7619f3ff4 100644
--- a/mcp-host/src/db/worker/dispatcher.ts
+++ b/mcp-host/src/db/worker/dispatcher.ts
@@ -697,12 +697,34 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
case 'load_all_pending_approvals': {
const rows = s.selectPendingApprovalsAll.all() as Array<
- PendingApprovalRow & { session_key: string }
+ PendingApprovalRow & {
+ session_key: string
+ session_user_id: string | null
+ session_channel_type: string | null
+ session_channel_id: string | null
+ session_thread_id: string | null
+ }
>
const out: LoadAllPendingApprovalsRow[] = []
for (const row of rows) {
- const { session_key, ...approval } = row
- out.push({ approval: approval as PendingApprovalRow, session_key })
+ const {
+ session_key,
+ session_user_id,
+ session_channel_type,
+ session_channel_id,
+ session_thread_id,
+ ...approval
+ } = row
+ out.push({
+ approval: approval as PendingApprovalRow,
+ session_key,
+ ownership: {
+ user_id: session_user_id,
+ channel_type: session_channel_type,
+ channel_id: session_channel_id,
+ thread_id: session_thread_id,
+ },
+ })
}
return out
}
diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.ts
index 5b953404e..361f0a390 100644
--- a/mcp-host/src/db/worker/protocol.ts
+++ b/mcp-host/src/db/worker/protocol.ts
@@ -136,6 +136,7 @@ export interface PersistedSessionMessagePage {
export interface LoadAllPendingApprovalsRow {
approval: PendingApprovalRow
session_key: string
+ ownership: Pick<SessionRow, 'user_id' | 'channel_type' | 'channel_id' | 'thread_id'>
}
/**