Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): protect conversation-store files from agent tools
Alfredo Lopezd1f05bafbbda
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex f0dd480d9..9b4763764 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.559",+ "version": "0.1.560","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.559",+ "version": "0.1.560","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex c02498c8d..d9e813667 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.559",+ "version": "0.1.560","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/tools/shell.ts b/mcp-host/src/core/tools/shell.tsindex f459ffb59..70b31a489 100644--- a/mcp-host/src/core/tools/shell.ts+++ b/mcp-host/src/core/tools/shell.ts@@ -13,15 +13,16 @@ import {SHELL_TIMEOUT_CLEANUP_MS,} from './shellTimeouts'-// D3 (stateless-agents) §1.2 — lexical defense-in-depth: reject commands that-// reference the session state database (state.db + WAL laterals) or the-// reserved `.clerum-state/` runtime directory BEFORE spawning. Word-boundary-// on the left so "mystate.db" doesn't trip; the right side is anchored by the-// literal suffixes. Case-sensitive, matching the exact on-disk names (same-// stance as the identity-file guard). This is a loud tool-level gate, not a-// sandbox: POSIX permissions / a read-only mount remain the OS backstop.-const STATE_DB_COMMAND_PATTERN =- /(^|[^A-Za-z0-9_.-])state\.db(-wal|-shm)?([^A-Za-z0-9_]|$)|\.clerum-state(\/|[^A-Za-z0-9_.-]|$)/+// Reject commands that name a conversation-store file or the reserved+// `.clerum-state/` runtime directory before spawning. Every name starting+// with `state.db` is store data: the database, its journals and the+// `state.db*.pre-<ts>.bak` copies an older layout left at the workspace root.+// The left boundary keeps "mystate.db" usable. Case-sensitive, matching the+// on-disk names.+// This is a lexical name check only, not a security boundary: the shell runs+// with the database's UID, so a glob, a variable or a symlink reaches the same+// files. The workspace API checks resolved paths; the shell does not.+const STATE_DB_COMMAND_PATTERN = /(^|[^A-Za-z0-9_.-])state\.db|\.clerum-state(\/|[^A-Za-z0-9_.-]|$)/// Node/libuv error codes (E2BIG, ENOMEM, ERR_INVALID_ARG_VALUE) are fixed// identifiers; anything else is not echoed to the model.@@ -214,7 +215,7 @@ export class ShellTool implements Tool {return {content:'Command rejected: it references the session state database ' +- '(state.db / state.db-wal / state.db-shm / .clerum-state), which is ' ++ '(state.db* / .clerum-state), which is ' +'platform-managed state the agent cannot access.',duration_ms: Date.now() - startTime,is_error: true,diff --git a/mcp-host/src/workspace/__tests__/conversationStoreFiles.test.ts b/mcp-host/src/workspace/__tests__/conversationStoreFiles.test.tsnew file mode 100644index 000000000..0f88ef5a1--- /dev/null+++ b/mcp-host/src/workspace/__tests__/conversationStoreFiles.test.ts@@ -0,0 +1,146 @@+/**+ * With one PVC layout for every lifecycle, the conversation database sits at+ * the workspace root next to agent files, together with its journals and the+ * `state.db*.pre-<ts>.bak` copies an older layout left behind. Every name+ * starting with `state.db` is store data, so the workspace API, its listing+ * and search, and the file tools deny it, directly and through a symlink.+ * Ordinary files with similar names stay usable.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'node:fs'+import * as os from 'node:os'+import * as path from 'node:path'+import { FileReadTool } from '../../core/tools/fileRead'+import { FileWriteTool } from '../../core/tools/fileWrite'+import { ShellTool } from '../../core/tools/shell'+import { ProtectedWorkspacePathError } from '../protectedPaths'+import { WorkspaceService, isStateDbPath } from '../service'++const STORE_BYTES = 'STORE-FILE-DO-NOT-TOUCH'+const STORE_FILES = ['state.db.pre-1.bak', 'state.db-wal', 'state.db.export.md']+// Symlinks that resolve to store files.+const ALIASES = ['bak-link', 'alias.md']+const PROTECTED = [...STORE_FILES, ...ALIASES]++describe('isStateDbPath', () => {+ it.each([+ 'state.db',+ 'state.db-wal',+ 'state.db-shm',+ 'state.db.pre-1.bak',+ 'state.db-wal.pre-1.bak',+ 'nested/state.db.pre-1.bak',+ ])('rejects %s', p => {+ expect(isStateDbPath(p)).toBe(true)+ })++ it.each(['mystate.db.txt', 'state.database', 'state/notes.md', 'notes.md'])('allows %s', p => {+ expect(isStateDbPath(p)).toBe(false)+ })+})++describe('conversation-store files are not agent-accessible', () => {+ let root: string++ beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'store-files-'))+ for (const p of STORE_FILES) {+ fs.writeFileSync(path.join(root, p), `${STORE_BYTES}\n\nneedle`, 'utf-8')+ }+ fs.symlinkSync(path.join(root, 'state.db.pre-1.bak'), path.join(root, 'bak-link'))+ fs.symlinkSync(path.join(root, 'state.db.export.md'), path.join(root, 'alias.md'))+ fs.writeFileSync(path.join(root, 'mystate.db.txt'), 'lookalike-ok', 'utf-8')+ fs.writeFileSync(path.join(root, 'notes.md'), 'ordinary-ok\n\nneedle', 'utf-8')+ })++ afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true })+ })++ function storeFilesUntouched(): void {+ for (const p of STORE_FILES) {+ expect(fs.readFileSync(path.join(root, p), 'utf-8')).toBe(`${STORE_BYTES}\n\nneedle`)+ }+ }++ it('WorkspaceService denies reads and writes, directly and through a symlink', async () => {+ const workspace = new WorkspaceService(root)+ for (const p of PROTECTED) {+ await expect(workspace.read(p), `read ${p}`).rejects.toBeInstanceOf(+ ProtectedWorkspacePathError+ )+ await expect(workspace.write(p, 'x'), `write ${p}`).rejects.toBeInstanceOf(+ ProtectedWorkspacePathError+ )+ }+ storeFilesUntouched()+ // Witness: the lookalike is served and the ordinary file is written.+ expect(await workspace.read('mystate.db.txt')).toBe('lookalike-ok')+ await workspace.write('notes.md', 'ordinary-written')+ expect(fs.readFileSync(path.join(root, 'notes.md'), 'utf-8')).toBe('ordinary-written')+ })++ it('list omits store files and search never returns them', async () => {+ const workspace = new WorkspaceService(root)+ const names = (await workspace.list()).map(e => e.name)+ // Witness: the listing has the ordinary files.+ expect(names).toEqual(expect.arrayContaining(['mystate.db.txt', 'notes.md']))+ for (const p of STORE_FILES) expect(names).not.toContain(p)++ const hits = (await workspace.search('needle')).map(r => r.path)+ // Witness: the same query finds the ordinary note.+ expect(hits).toContain('notes.md')+ expect(hits).not.toContain('state.db.export.md')+ expect(hits).not.toContain('alias.md')+ })++ it('file_read and file_write deny them, directly and through a symlink', async () => {+ const reader = new FileReadTool(root)+ const writer = new FileWriteTool(root)+ for (const p of PROTECTED) {+ const read = await reader.execute({ path: p })+ expect(read.is_error, `file_read ${p}`).toBe(true)+ expect(read.content).not.toContain(STORE_BYTES)+ const write = await writer.execute({ path: p, content: 'x' })+ expect(write.is_error, `file_write ${p}`).toBe(true)+ }+ storeFilesUntouched()+ // Witness: the same tools read the lookalike and write the ordinary file.+ const lookalike = await reader.execute({ path: 'mystate.db.txt' })+ expect(lookalike.is_error).toBe(false)+ expect(lookalike.content).toContain('lookalike-ok')+ const ordinary = await writer.execute({ path: 'notes.md', content: 'tool-written' })+ expect(ordinary.is_error).toBe(false)+ expect(fs.readFileSync(path.join(root, 'notes.md'), 'utf-8')).toBe('tool-written')+ })++ // The shell gate is lexical only and is not a security boundary; these are+ // regression tests of the name check.+ describe('shell_exec lexical gate', () => {+ function shell(): ShellTool {+ return new ShellTool(root, 5000, ['PATH'])+ }++ it.each(['cat state.db.pre-1.bak', 'cat state.db-wal', 'echo y > state.db.pre-2.bak'])(+ 'rejects by name: %s',+ async command => {+ const out = await shell().execute({ command })+ expect(out.is_error).toBe(true)+ expect(out.content).toContain('Command rejected')+ expect(out.content).not.toContain(STORE_BYTES)+ storeFilesUntouched()+ expect(fs.existsSync(path.join(root, 'state.db.pre-2.bak'))).toBe(false)+ }+ )++ it('runs commands on the lookalike and the ordinary file', async () => {+ const out = await shell().execute({+ command: 'cat mystate.db.txt notes.md && echo z > notes.md',+ })+ expect(out.is_error).toBe(false)+ expect(out.content).toContain('lookalike-ok')+ expect(out.content).toContain('ordinary-ok')+ expect(fs.readFileSync(path.join(root, 'notes.md'), 'utf-8')).toBe('z\n')+ })+ })+})diff --git a/mcp-host/src/workspace/__tests__/stateDbGuard.test.ts b/mcp-host/src/workspace/__tests__/stateDbGuard.test.tsindex e04cbb1c1..5e57d439b 100644--- a/mcp-host/src/workspace/__tests__/stateDbGuard.test.ts+++ b/mcp-host/src/workspace/__tests__/stateDbGuard.test.ts@@ -1,7 +1,7 @@/*** D3 (stateless-agents) §1.2 — defense-in-depth guard: agent file tools and* shell_exec must reject any path resolving to the session state database- * (state.db / state.db-wal / state.db-shm) or the reserved `.clerum-state/`+ * (every `state.db*` name) or the reserved `.clerum-state/`* directory — loudly, with the database left untouched.*/import { afterEach, beforeEach, describe, expect, it } from 'vitest'@@ -21,6 +21,7 @@ describe('isStateDbPath', () => {'/state.db','state.db-wal','state.db-shm',+ 'state.db.bak','sub/state.db','sub/deep/state.db-wal','.clerum-state',@@ -32,7 +33,6 @@ describe('isStateDbPath', () => {it.each(['notes.md',- 'state.db.bak','state.database','mystate.db','daily/2026-07-03.md',diff --git a/mcp-host/src/workspace/protectedPaths.ts b/mcp-host/src/workspace/protectedPaths.tsindex fd310d2e7..1172c0d1d 100644--- a/mcp-host/src/workspace/protectedPaths.ts+++ b/mcp-host/src/workspace/protectedPaths.ts@@ -31,11 +31,15 @@ function isProtectedSegment(segment: string): boolean {return PROTECTED_WORKSPACE_DIRS.has(segment) || isRetiredGfsStoreSegment(segment)}-export const PROTECTED_STATE_DB_FILES: ReadonlySet<string> = new Set([- 'state.db',- 'state.db-wal',- 'state.db-shm',-])+/**+ * True for every name of the conversation database family: the database, its+ * journals, and copies such as `state.db.pre-<ts>.bak` an older layout left+ * next to it at the workspace root. `mystate.db.txt` and `state.database` are+ * ordinary files.+ */+export function isStateDbName(name: string): boolean {+ return name.startsWith('state.db')+}function normalizeWorkspacePath(relativePath: string): string {let normalized = path.posix.normalize(relativePath || '')@@ -57,7 +61,7 @@ export function isProtectedWorkspacePath(relativePath: string): boolean {.filter(segment => segment.length > 0 && segment !== '.')if (segments.some(isProtectedSegment)) return trueconst base = segments[segments.length - 1]- return base !== undefined && PROTECTED_STATE_DB_FILES.has(base)+ return base !== undefined && isStateDbName(base)}/** Backward-compatible helper for callers that specifically report state-db access. */@@ -68,7 +72,7 @@ export function isStateDbPath(relativePath: string): boolean {.filter(segment => segment.length > 0 && segment !== '.')if (segments.includes('.clerum-state')) return trueconst base = segments[segments.length - 1]- return base !== undefined && PROTECTED_STATE_DB_FILES.has(base)+ return base !== undefined && isStateDbName(base)}export function isGfsDownloadPath(relativePath: string): boolean {@@ -131,7 +135,7 @@ function isProtectedAbsoluteRealPath(realPath: string): boolean {const segments = realPath.split(path.sep).filter(segment => segment.length > 0)if (segments.some(isProtectedSegment)) return trueconst base = segments[segments.length - 1]- return base !== undefined && PROTECTED_STATE_DB_FILES.has(base)+ return base !== undefined && isStateDbName(base)}export function isProtectedGfsRealPath(realPath: string): boolean {@@ -157,5 +161,5 @@ export function isProtectedRealPath(realPath: string, realWorkspaceRoot: string)const segments = relative.split(path.sep).filter(segment => segment.length > 0)if (segments.some(isProtectedSegment)) return trueconst base = segments[segments.length - 1]- return base !== undefined && PROTECTED_STATE_DB_FILES.has(base)+ return base !== undefined && isStateDbName(base)}diff --git a/mcp-host/src/workspace/service.ts b/mcp-host/src/workspace/service.tsindex 8bbadfe9d..399391df3 100644--- a/mcp-host/src/workspace/service.ts+++ b/mcp-host/src/workspace/service.ts@@ -65,8 +65,8 @@ export function isLockedPath(relativePath: string): boolean {export {GfsDownloadPathError,- PROTECTED_STATE_DB_FILES,StateDbPathError,+ isStateDbName,isStateDbPath,stateDbProtectedMessage,} from './protectedPaths'