Skip to content

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

TypeScript

fix(mcp-host): backfill session ownership safely

Josué1d7f65ea8081
diff --git a/mcp-host/src/__tests__/integration/contextBreakdownEndToEnd.test.ts b/mcp-host/src/__tests__/integration/contextBreakdownEndToEnd.test.ts
index 8f198d969..335467d9b 100644
--- a/mcp-host/src/__tests__/integration/contextBreakdownEndToEnd.test.ts
+++ b/mcp-host/src/__tests__/integration/contextBreakdownEndToEnd.test.ts
@@ -126,7 +126,7 @@ describe('F1 — context breakdown end-to-end (factory → port → sink → pro
const handleContextBreakdown = async (userSub: string, agent: string, chatId: string) => {
const key = `${userSub}:rpc:${agent}:${chatId}`
- const conv = await manager.getSessionByKeyAsync(key)
+ const conv = await manager.getSessionByKeyForUserAsync(key, userSub)
if (!conv) return null
return { breakdown: projectContextBreakdown(conv) ?? null }
}
diff --git a/mcp-host/src/agent/__tests__/sessionModelSelection.test.ts b/mcp-host/src/agent/__tests__/sessionModelSelection.test.ts
index 043a45955..5fe3894d3 100644
--- a/mcp-host/src/agent/__tests__/sessionModelSelection.test.ts
+++ b/mcp-host/src/agent/__tests__/sessionModelSelection.test.ts
@@ -91,6 +91,17 @@ describe('applySessionModelSelection (R2 shared core)', () => {
expect(resolved).toEqual({ model: 'claude-haiku-4-5' })
})
+ it('fails closed when an exact session key is already owned by another subject', async () => {
+ await cm.getOrCreate(sessionKey, { userId: 'different-owner' })
+
+ await expect(
+ applySessionModelSelection(makeDeps(cm), USER, HOST, CHAT, 'claude-haiku-4-5')
+ ).rejects.toMatchObject({
+ name: 'ConversationError',
+ code: 'CONV_OWNERSHIP_MISMATCH',
+ })
+ })
+
it('(b) rejects a non-allowlisted model and leaves the existing selection unchanged', async () => {
// Seed a valid prior selection on the session.
const seeded = await cm.getOrCreate(sessionKey, {
diff --git a/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts b/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts
index db71be23c..566159908 100644
--- a/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts
+++ b/mcp-host/src/core/conversation/__tests__/listSessionsForUser.test.ts
@@ -129,8 +129,9 @@ describe('ConversationManager.getSessionByKey', () => {
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'
- )
+ await expect(manager.getOrCreate(key, { userId: 'subject' })).rejects.toMatchObject({
+ name: 'ConversationError',
+ code: 'CONV_OWNERSHIP_MISMATCH',
+ })
})
})
diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.ts
index 338e0a919..a57831d66 100644
--- a/mcp-host/src/core/conversation/conversation.ts
+++ b/mcp-host/src/core/conversation/conversation.ts
@@ -215,7 +215,10 @@ export class ConversationManager {
private assertSessionOwner(conversation: Conversation, expectedUserId?: string): void {
if (expectedUserId !== undefined && conversation.user_id !== expectedUserId) {
- throw new Error('Session ownership mismatch')
+ throw new ConversationError(
+ 'Session access denied',
+ ConversationErrorCode.OwnershipMismatch
+ )
}
}
diff --git a/mcp-host/src/core/errors.ts b/mcp-host/src/core/errors.ts
index 120342e4a..62b5a92b5 100644
--- a/mcp-host/src/core/errors.ts
+++ b/mcp-host/src/core/errors.ts
@@ -89,6 +89,7 @@ export enum ConversationErrorCode {
InvalidTransition = 'CONV_INVALID_TRANSITION',
NotFound = 'CONV_NOT_FOUND',
ConcurrentMutation = 'CONV_CONCURRENT_MUTATION',
+ OwnershipMismatch = 'CONV_OWNERSHIP_MISMATCH',
}
export class ConversationError extends AgentError {
diff --git a/mcp-host/src/db/migrations/012-session-ownership-backfill.ts b/mcp-host/src/db/migrations/012-session-ownership-backfill.ts
new file mode 100644
index 000000000..d177c4896
--- /dev/null
+++ b/mcp-host/src/db/migrations/012-session-ownership-backfill.ts
@@ -0,0 +1,44 @@
+/**
+ * Migration 012 — repair legacy session ownership when persisted structured
+ * columns prove the exact serialized session-key suffix.
+ *
+ * The user portion may itself contain `:`, so ownership is derived by removing
+ * the complete structured suffix from the end. Rows with a real non-null
+ * mismatch, missing channel type, or a non-matching suffix remain unchanged and
+ * therefore fail closed at runtime.
+ */
+import type { Database } from 'better-sqlite3'
+
+export const name = '012-session-ownership-backfill'
+
+const structuredSuffix = `
+ ':' || channel_type ||
+ ':' || COALESCE(NULLIF(channel_id, ''), 'default') ||
+ ':' || COALESCE(NULLIF(thread_id, ''), 'default')
+`
+
+export function up(db: Database): void {
+ db.exec(`
+ UPDATE sessions
+ SET user_id = substr(
+ session_key,
+ 1,
+ length(session_key) - length(${structuredSuffix})
+ )
+ WHERE (user_id IS NULL OR trim(user_id) = '' OR user_id = session_key)
+ AND channel_type IS NOT NULL
+ AND trim(channel_type) <> ''
+ AND length(session_key) > length(${structuredSuffix})
+ AND substr(session_key, -length(${structuredSuffix})) = (${structuredSuffix})
+ AND trim(substr(
+ session_key,
+ 1,
+ length(session_key) - length(${structuredSuffix})
+ )) <> '';
+ `)
+}
+
+export function down(_db: Database): void {
+ // Forward-only data repair: reverting cannot distinguish repaired legacy rows
+ // from rows that already stored the correct owner without risking data loss.
+}
diff --git a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
index 2d47677e8..df6e53464 100644
--- a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
+++ b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
@@ -73,6 +73,7 @@ describe('migration 008 — active trace context', () => {
'009-session-summary-indexes',
'010-materialized-session-summaries',
'011-session-summary-user-activity-index',
+ '012-session-ownership-backfill',
],
pending: [],
})
diff --git a/mcp-host/src/db/migrations/__tests__/012-session-ownership-backfill.test.ts b/mcp-host/src/db/migrations/__tests__/012-session-ownership-backfill.test.ts
new file mode 100644
index 000000000..1e7e10a1a
--- /dev/null
+++ b/mcp-host/src/db/migrations/__tests__/012-session-ownership-backfill.test.ts
@@ -0,0 +1,117 @@
+import Database from 'better-sqlite3'
+import { describe, expect, it } from 'vitest'
+import { migrations } from '../index'
+
+const MIGRATION_NAME = '012-session-ownership-backfill'
+
+describe('migration 012 — session ownership backfill', () => {
+ it('repairs only legacy owners proven by the exact structured session-key suffix', () => {
+ const migration = migrations.find(candidate => candidate.name === MIGRATION_NAME)
+ expect(migration, `${MIGRATION_NAME} must be registered`).toBeDefined()
+
+ const db = new Database(':memory:')
+ for (const candidate of migrations) {
+ if (candidate.name === MIGRATION_NAME) break
+ candidate.up(db)
+ }
+
+ const owner = 'subject:rpc:embedded'
+ const insert = db.prepare(
+ `INSERT INTO sessions (
+ id, session_key, source, user_id, channel_type, channel_id, thread_id, started_at
+ ) VALUES (?, ?, 'rpc', ?, ?, ?, ?, 1)`
+ )
+ insert.run(
+ 'legacy-null-owner',
+ `${owner}:rpc:agent-x:chat-null`,
+ null,
+ 'rpc',
+ 'agent-x',
+ 'chat-null'
+ )
+ insert.run(
+ 'legacy-blank-owner',
+ `${owner}:rpc:agent-x:chat-blank`,
+ ' ',
+ 'rpc',
+ 'agent-x',
+ 'chat-blank'
+ )
+ insert.run(
+ 'legacy-full-key-owner',
+ `${owner}:rpc:agent-x:chat-full`,
+ `${owner}:rpc:agent-x:chat-full`,
+ 'rpc',
+ 'agent-x',
+ 'chat-full'
+ )
+ insert.run(
+ 'legacy-default-fields',
+ `${owner}:rpc:default:default`,
+ null,
+ 'rpc',
+ null,
+ null
+ )
+ insert.run(
+ 'legacy-real-mismatch',
+ `${owner}:rpc:agent-x:chat-mismatch`,
+ 'different-owner',
+ 'rpc',
+ 'agent-x',
+ 'chat-mismatch'
+ )
+ insert.run(
+ 'legacy-suffix-mismatch',
+ `${owner}:rpc:agent-x:chat-ambiguous`,
+ null,
+ 'rpc',
+ 'different-agent',
+ 'chat-ambiguous'
+ )
+ insert.run(
+ 'legacy-missing-channel-type',
+ `${owner}:rpc:agent-x:chat-unknown`,
+ null,
+ null,
+ 'agent-x',
+ 'chat-unknown'
+ )
+
+ const legacyCount = () =>
+ (
+ db
+ .prepare(
+ `SELECT COUNT(*) AS count
+ FROM sessions
+ WHERE user_id IS NULL
+ OR trim(user_id) = ''
+ OR user_id = session_key`
+ )
+ .get() as { count: number }
+ ).count
+
+ expect(legacyCount()).toBe(6)
+ migration!.up(db)
+ expect(legacyCount()).toBe(2)
+
+ const rows = db
+ .prepare('SELECT id, user_id FROM sessions ORDER BY id')
+ .all() as Array<{ id: string; user_id: string | null }>
+ expect(rows).toEqual([
+ { id: 'legacy-blank-owner', user_id: owner },
+ { id: 'legacy-default-fields', user_id: owner },
+ { id: 'legacy-full-key-owner', user_id: owner },
+ { id: 'legacy-missing-channel-type', user_id: null },
+ { id: 'legacy-null-owner', user_id: owner },
+ { id: 'legacy-real-mismatch', user_id: 'different-owner' },
+ { id: 'legacy-suffix-mismatch', user_id: null },
+ ])
+
+ migration!.up(db)
+ expect(
+ db.prepare('SELECT id, user_id FROM sessions ORDER BY id').all()
+ ).toEqual(rows)
+ db.close()
+ })
+})
diff --git a/mcp-host/src/db/migrations/index.ts b/mcp-host/src/db/migrations/index.ts
index b4b37fe82..a489bf081 100644
--- a/mcp-host/src/db/migrations/index.ts
+++ b/mcp-host/src/db/migrations/index.ts
@@ -9,6 +9,7 @@ import * as activeTraceContext from './008-active-trace-context'
import * as sessionSummaryIndexes from './009-session-summary-indexes'
import * as materializedSessionSummaries from './010-materialized-session-summaries'
import * as sessionSummaryUserActivityIndex from './011-session-summary-user-activity-index'
+import * as sessionOwnershipBackfill from './012-session-ownership-backfill'
/**
* Ordered list of migrations. New migrations append; never reorder or rename.
@@ -31,4 +32,5 @@ export const migrations: Array<{
sessionSummaryIndexes,
materializedSessionSummaries,
sessionSummaryUserActivityIndex,
+ sessionOwnershipBackfill,
]
diff --git a/mcp-host/src/server/__tests__/messageRoute.test.ts b/mcp-host/src/server/__tests__/messageRoute.test.ts
index 13f70f755..0815ac0f8 100644
--- a/mcp-host/src/server/__tests__/messageRoute.test.ts
+++ b/mcp-host/src/server/__tests__/messageRoute.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Request, Response } from 'express'
import { config } from '../../config'
+import { ConversationError, ConversationErrorCode } from '../../core/errors'
import { handleMessageRoute } from '../routes'
import { makeHandlers } from './testHelpers'
@@ -191,6 +192,35 @@ describe('handleMessageRoute — rpc sender identity invariant', () => {
expect(captured.statusCode).toBe(403)
expect(messageHandler).not.toHaveBeenCalled()
})
+
+ it('maps persisted ownership mismatches to a generic 403', async () => {
+ const messageHandler = vi.fn().mockRejectedValue(
+ new ConversationError(
+ 'sensitive ownership detail',
+ ConversationErrorCode.OwnershipMismatch
+ )
+ )
+ const req = {
+ runtimeCaller: { caller: 'rpc-proxy', hostRef: 'chatllm', userId: 'legit-user' },
+ body: {
+ sender: 'legit-user',
+ channelType: 'rpc',
+ channelId: 'agent-x',
+ threadId: 'chat-1',
+ content: 'hi',
+ timestamp: 'now',
+ messageId: 'm1',
+ hostRef: 'chatllm',
+ },
+ query: {},
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleMessageRoute(req, captured.res, makeHandlers({ messageHandler }))
+
+ expect(captured.statusCode).toBe(403)
+ expect(captured.jsonBody).toEqual({ success: false, error: 'session access denied' })
+ })
})
describe('handleMessageRoute — async response serialization', () => {
diff --git a/mcp-host/src/server/__tests__/modelRoutes.test.ts b/mcp-host/src/server/__tests__/modelRoutes.test.ts
index a578822fc..2ca5f58e4 100644
--- a/mcp-host/src/server/__tests__/modelRoutes.test.ts
+++ b/mcp-host/src/server/__tests__/modelRoutes.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { Request, Response } from 'express'
+import { ConversationError, ConversationErrorCode } from '../../core/errors'
import { handleModelsListRoute, handleSetModelRoute } from '../routes'
import type { ModelsListHandler, SetModelHandler } from '../types'
import { makeHandlers } from './testHelpers'
@@ -186,4 +187,25 @@ describe('handleSetModelRoute (POST /v1/runtime/model)', () => {
await handleSetModelRoute(req, captured.res, makeHandlers({ setModelHandler: vi.fn() }))
expect(captured.statusCode).toBe(401)
})
+
+ it('maps persisted ownership mismatches to a generic 403', async () => {
+ const setModelHandler: SetModelHandler = vi.fn().mockRejectedValue(
+ new ConversationError(
+ 'sensitive ownership detail',
+ ConversationErrorCode.OwnershipMismatch
+ )
+ )
+ const req = makeReq({
+ caller: 'rpc-proxy',
+ userId: 'u-1',
+ hostRef: 'chatllm',
+ body: { chatId: 'c-9', model: 'claude-haiku-4-5' },
+ })
+ const captured = makeRes()
+
+ await handleSetModelRoute(req, captured.res, makeHandlers({ setModelHandler }))
+
+ expect(captured.statusCode).toBe(403)
+ expect(captured.jsonBody).toEqual({ error: 'session access denied' })
+ })
})
diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.ts
index a867d5dfc..38308df64 100644
--- a/mcp-host/src/server/routes.ts
+++ b/mcp-host/src/server/routes.ts
@@ -1,4 +1,5 @@
import type { Request, Response } from 'express'
+import { ConversationError, ConversationErrorCode } from '../core/errors'
import type { ApprovalDecision } from '../core/extensions/approvalTypes'
import { isTraceContextV1 } from '../core/types'
import { getRuntimeCallerContext } from './edgeRuntimeAuth'
@@ -64,6 +65,13 @@ export type RouteHandlers = {
setModelHandler?: SetModelHandler | null
}
+function isSessionOwnershipError(error: unknown): boolean {
+ return (
+ error instanceof ConversationError &&
+ error.code === ConversationErrorCode.OwnershipMismatch
+ )
+}
+
function parseSessionsCursorParam(
cursor: unknown,
expectedScope: string
@@ -339,6 +347,10 @@ export async function handleMessageRoute(
json(res, 200, response)
} catch (error) {
console.error('[Server] Error processing message:', error)
+ if (isSessionOwnershipError(error)) {
+ json(res, 403, { success: false, error: 'session access denied' })
+ return
+ }
json(res, 500, {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
@@ -1405,6 +1417,10 @@ export async function handleSetModelRoute(
json(res, 200, { effective: 'next-task', provider: result.provider, model: result.model })
} catch (error) {
console.error('[Server] Error setting model:', error)
+ if (isSessionOwnershipError(error)) {
+ json(res, 403, { error: 'session access denied' })
+ return
+ }
json(res, 500, { error: error instanceof Error ? error.message : 'Unknown error' })
}
}