From 146de164259cfe99e26b00dd3b61ff3397e000bf Mon Sep 17 00:00:00 2001 From: r Date: Wed, 4 Nov 2026 21:38:12 -0500 Subject: [PATCH] fix(memory): contain MCP export/import paths to the project memory_export and memory_import now resolve outputPath/inputPath inside the project directory (no symlinks, not in .git, no executables, nothing when the server runs from a home or filesystem root), and import parse errors no longer quote the file. An explicit dbPath must be a SQLite database file. The local CLI keeps operator-chosen paths. session_export shares the helper. Co-Authored-By: RuFlo --- .../memory-export-both-stores-4148.test.ts | 1 + .../memory-export-completeness.test.ts | 1 + ...ory-export-import-path-containment.test.ts | 135 ++++++++++++++++++ .../memory-export-native-pages.test.ts | 1 + .../__tests__/memory-export-path-3196.test.ts | 1 + .../memory-import-db-path-3196.test.ts | 5 +- .../memory-import-write-results.test.ts | 1 + ...ry-sibling-disclosure-partial-3566.test.ts | 1 + .../memory-stats-selected-store.test.ts | 7 +- ...memory-store-import-namespace-3570.test.ts | 1 + v3/@claude-flow/cli/src/commands/memory.ts | 7 +- .../cli/src/mcp-tools/memory-tools.ts | 73 ++++++---- .../cli/src/mcp-tools/path-containment.ts | 119 +++++++++++++++ .../cli/src/mcp-tools/session-tools.ts | 35 +---- 14 files changed, 320 insertions(+), 68 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts create mode 100644 v3/@claude-flow/cli/src/mcp-tools/path-containment.ts diff --git a/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts index 563af5ab46..a02089ff7a 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts @@ -23,6 +23,7 @@ vi.mock('../src/memory/memory-initializer.js', () => ({ let dir: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-export-4148-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project state.cliStore = join(dir, 'memory.db'); writeFileSync(state.cliStore, 'x'); // the CLI store exists on disk state.stores = {}; diff --git a/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts index 9d68dce276..bf64e7801b 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts @@ -13,6 +13,7 @@ let dir: string; let outputPath: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-export-pages-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project outputPath = join(dir, 'backup.json'); writeFileSync(outputPath, 'existing complete backup'); layer.listEntries.mockReset(); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts new file mode 100644 index 0000000000..42bd972fde --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts @@ -0,0 +1,135 @@ +/** + * SECURITY: memory_export wrote to any outputPath and memory_import read any + * inputPath (echoing parser errors that quote the file), so an MCP caller could + * overwrite or probe files anywhere the server can reach. MCP callers are now + * contained to the project; the local CLI keeps operator-chosen paths. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const layer = vi.hoisted(() => ({ storeEntry: vi.fn(), listEntries: vi.fn() })); +vi.mock('../src/memory/memory-initializer.js', () => ({ + storeEntry: layer.storeEntry, + listEntries: layer.listEntries, + searchEntries: vi.fn(), getEntry: vi.fn(), deleteEntry: vi.fn(), + initializeMemoryDatabase: vi.fn(), + checkMemoryInitialization: vi.fn(async () => ({ initialized: true })), +})); +const { memoryTools } = await import('../src/mcp-tools/memory-tools.js'); +const { localCliContext, dbPathError, containedWritePath } = await import('../src/mcp-tools/path-containment.js'); +const tool = (name: string) => memoryTools.find(t => t.name === name)!; + +const originalCwd = process.env.CLAUDE_FLOW_CWD; +let project: string; +let outside: string; + +beforeEach(() => { + project = mkdtempSync(join(tmpdir(), 'ruflo-mem-contain-')); + outside = mkdtempSync(join(tmpdir(), 'ruflo-mem-outside-')); + process.env.CLAUDE_FLOW_CWD = project; + layer.storeEntry.mockReset().mockResolvedValue({ success: true, id: 'saved' }); + layer.listEntries.mockReset().mockResolvedValue({ success: true, entries: [{ key: 'k', namespace: 'default', content: 'v', tags: [] }], total: 1 }); +}); +afterEach(() => { + if (originalCwd === undefined) delete process.env.CLAUDE_FLOW_CWD; + else process.env.CLAUDE_FLOW_CWD = originalCwd; + rmSync(project, { recursive: true, force: true }); + rmSync(outside, { recursive: true, force: true }); +}); + +const exportTo = (outputPath: string, context?: Record) => + tool('memory_export').handler({ outputPath }, context) as Promise>; + +describe('memory_export outputPath', () => { + it('writes a .json file inside the project', async () => { + const r = await exportTo('backup.json'); + expect(r.error).toBeUndefined(); + expect(JSON.parse(readFileSync(join(project, 'backup.json'), 'utf8')).schema).toMatch(/ruflo-memory-export/); + }); + + it('refuses paths outside the project, non-.json targets, symlinks, .git and executables', async () => { + const victim = join(outside, 'victim.json'); + writeFileSync(victim, 'original'); + symlinkSync(victim, join(project, 'link.json')); + mkdirSync(join(project, '.git', 'hooks'), { recursive: true }); + writeFileSync(join(project, 'run.json'), '#!/bin/sh\n'); + chmodSync(join(project, 'run.json'), 0o755); + for (const p of [victim, '../escape.json', 'link.json', 'notes.sh', '.git/hooks/pre-commit.json', 'run.json']) { + const r = await exportTo(p); + expect(r.error, p).toMatch(/inside the project/); + } + expect(readFileSync(victim, 'utf8')).toBe('original'); + expect(readFileSync(join(project, 'run.json'), 'utf8')).toBe('#!/bin/sh\n'); + }); + + it('refuses everything when the project root is the home directory', () => { + process.env.CLAUDE_FLOW_CWD = '/'; + vi.spyOn(process, 'cwd').mockReturnValue(process.env.HOME ?? '/'); + try { + expect(containedWritePath('backup.json', ['.json'])).toBeNull(); + } finally { + vi.restoreAllMocks(); + } + }); + + it('lets the local CLI write where the operator asked', async () => { + const target = join(outside, 'cli-backup.json'); + const r = await exportTo(target, localCliContext()); + expect(r.error).toBeUndefined(); + expect(existsSync(target)).toBe(true); + }); +}); + +describe('memory_import inputPath', () => { + it('refuses a file outside the project and does not echo its contents', async () => { + const secret = join(outside, 'secret.txt'); + writeFileSync(secret, 'root:x:0:0:topsecret'); + const r = await tool('memory_import').handler({ inputPath: secret }) as Record; + expect(r.error).toMatch(/inside the project/); + expect(JSON.stringify(r)).not.toContain('topsecret'); + }); + + it('returns a generic error for a non-JSON file inside the project', async () => { + writeFileSync(join(project, 'notes.txt'), 'topsecret line'); + const r = await tool('memory_import').handler({ inputPath: 'notes.txt' }) as Record; + expect(r.error).toMatch(/not a valid memory export/); + expect(JSON.stringify(r)).not.toContain('topsecret'); + expect(layer.storeEntry).not.toHaveBeenCalled(); + }); + + it('imports a file inside the project, and the CLI may import from elsewhere', async () => { + const doc = JSON.stringify({ entries: [{ key: 'a', namespace: 'notes', value: 'x' }] }); + writeFileSync(join(project, 'in.json'), doc); + expect((await tool('memory_import').handler({ inputPath: 'in.json' }) as any).error).toBeUndefined(); + writeFileSync(join(outside, 'in.json'), doc); + expect((await tool('memory_import').handler({ inputPath: join(outside, 'in.json') }, localCliContext()) as any).error).toBeUndefined(); + }); +}); + +describe('dbPath', () => { + it('accepts a new or existing SQLite file and refuses anything else', () => { + expect(dbPathError(join(outside, 'new.db'))).toBeNull(); + writeFileSync(join(outside, 'real.db'), Buffer.concat([Buffer.from('SQLite format 3\0', 'latin1'), Buffer.alloc(84)])); + expect(dbPathError(join(outside, 'real.db'))).toBeNull(); + writeFileSync(join(outside, 'fake.db'), 'export PATH=evil'); + expect(dbPathError(join(outside, 'fake.db'))).toMatch(/not a SQLite database/); + expect(dbPathError(join(outside, '.bashrc'))).toMatch(/must end in/); + symlinkSync(join(outside, 'real.db'), join(outside, 'link.db')); + expect(dbPathError(join(outside, 'link.db'))).toMatch(/symlink/); + }); + + it('is enforced on the MCP memory tools', async () => { + writeFileSync(join(outside, 'fake.db'), 'not a database'); + await expect(tool('memory_store').handler({ key: 'k', value: 'v', dbPath: join(outside, 'fake.db') })).rejects.toThrow(/not a SQLite database/); + expect(readFileSync(join(outside, 'fake.db'), 'utf8')).toBe('not a database'); + }); +}); + +describe('dbPath with encryption at rest', () => { + it('accepts an RFE1-encrypted database file', () => { + writeFileSync(join(outside, 'enc.db'), Buffer.concat([Buffer.from('RFE1'), Buffer.alloc(64)])); + expect(dbPathError(join(outside, 'enc.db'))).toBeNull(); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts index 3199111a35..6ddc63b4ac 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts @@ -14,6 +14,7 @@ vi.mock('../src/memory/memory-initializer.js', () => ({ }, })); const dir = mkdtempSync(join(tmpdir(), 'ruflo-export-native-')); +process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project state.dbPath = join(dir, 'memory.db'); const db = new Database(state.dbPath); afterAll(() => { db.close(); rmSync(dir, { recursive: true, force: true }); }); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts index daeda676da..f710dce9c5 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts @@ -52,6 +52,7 @@ describe('memory export explicit dbPath (#3196)', () => { beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'memory-export-path-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project prevMemoryPath = process.env.CLAUDE_FLOW_MEMORY_PATH; prevBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE; process.env.CLAUDE_FLOW_MEMORY_PATH = join(dir, 'default-memory-root'); diff --git a/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts index 299b198c8c..de42f32340 100644 --- a/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts @@ -33,6 +33,7 @@ import { memoryTools } from '../src/mcp-tools/memory-tools.js'; const importCommand = memoryCommand.subcommands!.find(command => command.name === 'import')!; const importTool = memoryTools.find(tool => tool.name === 'memory_import')!; const tempDir = mkdtempSync(join(tmpdir(), 'ruflo-import-3196-')); +process.env.CLAUDE_FLOW_CWD = tempDir; // MCP import paths are contained to the project const importPath = join(tempDir, 'export.json'); writeFileSync(importPath, JSON.stringify({ entries: [{ key: 'remember-me', namespace: 'project', value: 'persisted' }], @@ -62,7 +63,7 @@ describe('memory import database selection', () => { } as any); expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({ dbPath: '/project/custom.db', - })); + }), expect.anything()); }); it('uses the same default database as CLI store when --path is omitted', async () => { @@ -72,7 +73,7 @@ describe('memory import database selection', () => { } as any); expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({ dbPath: '/project/.swarm/memory.db', - })); + }), expect.anything()); }); it('initializes and writes the selected file rather than the bridge fallback', async () => { diff --git a/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts b/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts index 2197b75f4b..0cc0500dc0 100644 --- a/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts @@ -14,6 +14,7 @@ const importer = memoryTools.find(t => t.name === 'memory_import')!; let dir: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-import-result-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP import paths are contained to the project layer.storeEntry.mockReset().mockResolvedValue({ success: true, id: 'saved' }); }); afterEach(() => rmSync(dir, { recursive: true, force: true })); diff --git a/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts b/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts index 0b9bf18200..95db7c186e 100644 --- a/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts @@ -46,6 +46,7 @@ const run = (cmd: typeof search, flags: Record) => const siblingWarnings = () => mocks.warning.mock.calls.map(c => String(c[0])).filter(m => m.includes(SIBLING.path)); const dir = mkdtempSync(join(tmpdir(), 'mem-3566-')); +process.env.CLAUDE_FLOW_CWD = dir; // MCP import paths are contained to the project afterAll(() => rmSync(dir, { recursive: true, force: true })); beforeEach(() => { diff --git a/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts index c713f6a957..3b9ba5be78 100644 --- a/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts @@ -39,7 +39,8 @@ beforeEach(() => { vi.clearAllMocks(); dir = mkdtempSync(join(tmpdir(), 'stats-selected-')); selected = join(dir, 'selected.db'); - writeFileSync(selected, 'store'); + // MCP callers may only name a real SQLite file, so the fixture carries the header. + writeFileSync(selected, Buffer.concat([Buffer.from('SQLite format 3\0', 'latin1'), Buffer.from('store')])); writeFileSync(selected + '-wal', 'wal'); vi.stubEnv('CLAUDE_FLOW_DB_PATH', ''); mocks.labels.mockResolvedValue({ initialized: true, version: 'selected-version' }); @@ -58,7 +59,7 @@ describe('stats describes the selected store', () => { expect(mocks.labels).toHaveBeenCalledWith(selected); expect(mocks.init).not.toHaveBeenCalled(); expect(result.location).toBe(selected); - expect(result.totalSize).toBe('8 B'); + expect(result.totalSize).toBe('24 B'); expect(result.oldestEntry).toBe('2026-01-01T00:00:00.000Z'); expect(result.newestEntry).toBe('2026-03-01T00:00:00.000Z'); }); @@ -69,7 +70,7 @@ describe('stats describes the selected store', () => { const result = await run({ path: selected }) as any; expect(result.success).toBe(true); expect(result.data.entries.total).toBe(2); - expect(result.data.storage).toEqual({ total: '8 B', location: selected }); + expect(result.data.storage).toEqual({ total: '24 B', location: selected }); expect(result.data.unreadStore.rows).toBe(9); expect(mocks.sibling).toHaveBeenCalledWith(selected); }); diff --git a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts index a6527b4559..53a48a636b 100644 --- a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts @@ -34,6 +34,7 @@ const importTool = memoryTools.find(t => t.name === 'memory_import')!; const exportTool = memoryTools.find(t => t.name === 'memory_export')!; const tempDir = mkdtempSync(join(tmpdir(), 'ruflo-ns-3570-')); +process.env.CLAUDE_FLOW_CWD = tempDir; // MCP export/import paths are contained to the project const writeImport = (name: string, entries: unknown[]) => { const p = join(tempDir, name); writeFileSync(p, JSON.stringify({ entries })); diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts index de02eb7c4f..863b25b101 100644 --- a/v3/@claude-flow/cli/src/commands/memory.ts +++ b/v3/@claude-flow/cli/src/commands/memory.ts @@ -9,6 +9,7 @@ import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; import { select, confirm, input } from '../prompt.js'; import { callMCPTool, MCPClientError } from '../mcp-client.js'; +import { localCliContext } from '../mcp-tools/path-containment.js'; import { distillCommand } from './memory-distill.js'; import { backupCommand } from './memory-backup.js'; import { countSiblingStoreRows } from '../memory/sibling-store.js'; @@ -1155,7 +1156,7 @@ const statsCommand: Command = { // Call MCP memory/stats tool for real statistics try { const dbPath = resolveDbPath(ctx.flags.path as string | undefined); - const statsResult = await callMCPTool('memory_stats', { dbPath }) as { + const statsResult = await callMCPTool('memory_stats', { dbPath }, localCliContext()) as { available?: boolean; error?: string; truncated?: boolean; @@ -1825,7 +1826,7 @@ const exportCommand: Command = { namespace: ctx.flags.namespace, includeVectors: ctx.flags.includeVectors ?? true, dbPath: resolveDbPath(ctx.flags.path as string | undefined), - }); + }, localCliContext()); // memory_export reports failure as { error } rather than throwing; without // this check the command printed "Exported to undefined" and then crashed @@ -1914,7 +1915,7 @@ const importCommand: Command = { merge: ctx.flags.merge ?? true, namespace: ctx.flags.namespace, dbPath: resolveDbPath(ctx.flags.path as string | undefined), - }); + }, localCliContext()); // memory_import reports a bad file as { error } rather than throwing, and // a partial write as { success: false, error, imported }. Without this the diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts index bf7247c61f..636f48cba9 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'fs'; import { homedir } from 'os'; import { basename, dirname, join, resolve } from 'path'; +import { containedReadPath, containedWritePath, dbPathError, isLocalCliCall } from './path-containment.js'; import { execFileSync } from 'node:child_process'; import { createHash } from 'crypto'; import { getProjectCwd, type MCPTool } from './types.js'; @@ -45,10 +46,19 @@ const LEGACY_MEMORY_DIR = '.claude-flow/memory'; * deliberately not an implicit `CLAUDE_FLOW_DB_PATH` override because the * native/encrypted CLI store and the AgentDB sibling are separate backends. */ -function resolveDbPathOption(inputDbPath: unknown): string | undefined { - return typeof inputDbPath === 'string' && inputDbPath.trim().length > 0 - ? resolve(inputDbPath) - : undefined; +/** + * Resolve an explicit `dbPath`. MCP callers may only name a SQLite database + * file, so the memory tools cannot be aimed at and overwrite an unrelated file; + * the local CLI (`--path`) keeps operator-chosen paths as-is. + */ +function resolveDbPathOption(inputDbPath: unknown, context?: unknown): string | undefined { + if (typeof inputDbPath !== 'string' || inputDbPath.trim().length === 0) return undefined; + const dbPath = resolve(inputDbPath); + if (!isLocalCliCall(context)) { + const error = dbPathError(dbPath); + if (error) throw new Error(error); + } + return dbPath; } const MIGRATION_MARKER = '.migrated-to-sqlite'; @@ -534,13 +544,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key', 'value'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_store'); if (missingKey) { return { success: false, key: input.key, stored: false, hasEmbedding: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { storeEntry } = await getMemoryFunctions(); @@ -626,13 +636,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_retrieve'); if (missingKey) { return { key: input.key, namespace: input.namespace, value: null, found: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { getEntry } = await getMemoryFunctions(); @@ -705,13 +715,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['query'], }, - handler: async (input) => { + handler: async (input, context) => { const missingQuery = missingRequiredString(input, 'query', 'memory_search'); if (missingQuery) { return { query: input.query, results: [], total: 0, ...missingQuery }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { searchEntries } = await getMemoryFunctions(); @@ -903,13 +913,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_delete'); if (missingKey) { return { success: false, key: input.key, namespace: input.namespace, deleted: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { deleteEntry } = await getMemoryFunctions(); @@ -958,8 +968,8 @@ export const memoryTools: MCPTool[] = [ dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' }, }, }, - handler: async (input) => { - const dbPath = resolveDbPathOption(input.dbPath); + handler: async (input, context) => { + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); @@ -1035,11 +1045,11 @@ export const memoryTools: MCPTool[] = [ dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' }, }, }, - handler: async (input) => { + handler: async (input, context) => { if (input.dbPath !== undefined && (typeof input.dbPath !== 'string' || !input.dbPath.trim())) { return memoryStatsUnavailable('dbPath must be a non-empty string'); } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); // An explicit read must not initialize or migrate the unrelated default store. if (!dbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); @@ -1715,16 +1725,16 @@ export const memoryTools: MCPTool[] = [ }, required: ['outputPath'], }, - handler: async (input) => { - const requestedDbPath = typeof input.dbPath === 'string' && input.dbPath.trim() - ? resolve(input.dbPath) - : undefined; + handler: async (input, context) => { + const requestedOutput = String(input.outputPath ?? ''); + if (!requestedOutput) return { error: 'outputPath is required' }; + const outputPath = isLocalCliCall(context) ? resolve(requestedOutput) : containedWritePath(requestedOutput, ['.json']); + if (!outputPath) return { error: 'outputPath must be a .json file inside the project directory (not a symlink, not in .git)' }; + const requestedDbPath = resolveDbPathOption(input.dbPath, context); // An explicit file selection is a single-store read. Do not initialize or // migrate the unrelated default store just to export a snapshot. if (!requestedDbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); - const outputPath = String(input.outputPath ?? ''); - if (!outputPath) return { error: 'outputPath is required' }; const namespace = input.namespace ? String(input.namespace) : undefined; if (namespace) { const v = validateIdentifier(namespace, 'namespace'); if (!v.valid) throw new Error(v.error); } // #2073: pass includeContent so the value field carries the actual @@ -1830,21 +1840,26 @@ export const memoryTools: MCPTool[] = [ }, required: ['inputPath'], }, - handler: async (input) => { - const dbPath = typeof input.dbPath === 'string' && input.dbPath.trim() - ? resolve(input.dbPath) - : undefined; + handler: async (input, context) => { + const dbPath = resolveDbPathOption(input.dbPath, context); await ensureInitialized(dbPath); const { storeEntry } = await getMemoryFunctions(); const t0 = Date.now(); // Values are re-embedded on import; count the vectors actually written // rather than reporting a constant 0 next to entries that show a vector. let vectors = 0; - const inputPath = String(input.inputPath ?? ''); - if (!inputPath || !existsSync(inputPath)) return { error: `File not found: ${inputPath || '(empty)'}` }; + const requestedInput = String(input.inputPath ?? ''); + const inputPath = !requestedInput ? null + : isLocalCliCall(context) ? (existsSync(requestedInput) ? resolve(requestedInput) : null) + : containedReadPath(requestedInput); + if (!inputPath) { + return { error: isLocalCliCall(context) || !requestedInput + ? `File not found: ${requestedInput || '(empty)'}` + : 'inputPath must be an existing regular file inside the project directory (not a symlink)' }; + } let doc: { entries?: Array<{ key: string; namespace?: string; value?: unknown; tags?: string[] | string }> }; try { doc = JSON.parse(readFileSync(inputPath, 'utf-8')); } - catch (e) { return { error: `Invalid export JSON: ${(e as Error).message}` }; } + catch { return { error: 'inputPath is not a valid memory export (JSON parse failed)' }; } const entries = Array.isArray(doc.entries) ? doc.entries : []; const nsOverride = input.namespace ? String(input.namespace) : undefined; if (nsOverride) { const v = validateIdentifier(nsOverride, 'namespace'); if (!v.valid) throw new Error(v.error); } diff --git a/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts b/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts new file mode 100644 index 0000000000..9228b58bba --- /dev/null +++ b/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts @@ -0,0 +1,119 @@ +/** + * Path checks for MCP tools that read or write a caller-named file. + * + * Paths in tool input come from whoever drives the MCP server, including a + * model following injected instructions. A tool that writes or reads such a + * path must keep it inside the project directory, and must not follow a + * symlink out of it. + */ + +import { closeSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs'; +import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { isNonProjectDir } from '@claude-flow/cli-core/mcp-tools/types'; +import { getProjectCwd } from './types.js'; +import { existingFileIsEncrypted } from '../fs-secure.js'; + +function lstatOrNull(p: string) { + try { return lstatSync(p); } catch { return null; } +} + +function projectRoot(): string | null { + const root = realpathSync(getProjectCwd()); + // A server started in a home or filesystem root has no project to contain + // writes to; "inside the root" would mean the whole home directory. + return isNonProjectDir(root) ? null : root; +} + +function insideRoot(root: string, target: string): boolean { + const rel = relative(root, target); + if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false; + return !rel.split(sep).includes('.git'); +} + +/** + * Resolve a caller-named output file inside the project. The real parent + * directory must be inside the real project root and outside `.git`, and an + * existing target must be a regular, non-executable file — not a symlink. + * `extensions`, when given, lists the allowed lower-case file extensions. + */ +export function containedWritePath(p: string, extensions?: readonly string[]): string | null { + if (!p || p.includes('\0')) return null; + try { + const root = projectRoot(); + if (!root) return null; + const abs = resolve(root, p); + if (extensions && !extensions.includes(extname(abs).toLowerCase())) return null; + const target = join(realpathSync(dirname(abs)), basename(abs)); + if (!insideRoot(root, target)) return null; + const existing = lstatOrNull(target); + if (existing && (existing.isSymbolicLink() || !existing.isFile() || (existing.mode & 0o111) !== 0)) return null; + return target; + } catch { + return null; + } +} + +/** Resolve a caller-named input file inside the project: a regular file, not a symlink. */ +export function containedReadPath(p: string): string | null { + if (!p || p.includes('\0')) return null; + try { + const root = projectRoot(); + if (!root) return null; + const abs = resolve(root, p); + const existing = lstatOrNull(abs); + if (!existing || existing.isSymbolicLink() || !existing.isFile()) return null; + const target = realpathSync(abs); + return insideRoot(root, target) ? target : null; + } catch { + return null; + } +} + +const DB_EXTENSIONS = ['.db', '.sqlite', '.sqlite3']; +const SQLITE_HEADER = 'SQLite format 3\0'; + +/** + * Check a caller-named memory database path. It may live outside the project + * (the CLI's `--path` flag passes one), so this does not contain it; instead + * it refuses anything that is not plainly a SQLite database (plaintext, or + * encrypted at rest per ADR-096), so the memory tools cannot be pointed at and + * overwrite an unrelated file. + */ +export function dbPathError(p: string): string | null { + if (p.includes('\0')) return 'dbPath contains a null byte'; + if (!DB_EXTENSIONS.includes(extname(p).toLowerCase())) { + return `dbPath must end in ${DB_EXTENSIONS.join(', ')}`; + } + const existing = lstatOrNull(p); + if (!existing) return null; + if (existing.isSymbolicLink()) return 'dbPath must not be a symlink'; + if (!existing.isFile()) return 'dbPath must be a regular file'; + if (existing.size === 0 || existingFileIsEncrypted(p) === true) return null; + const header = Buffer.alloc(SQLITE_HEADER.length); + let fd: number | undefined; + try { + fd = openSync(p, 'r'); + readSync(fd, header, 0, header.length, 0); + } catch { + return 'dbPath could not be read'; + } finally { + if (fd !== undefined) closeSync(fd); + } + return header.toString('latin1') === SQLITE_HEADER ? null : 'dbPath is not a SQLite database'; +} + +/** + * Marks a tool call made by the local CLI on the operator's behalf (for + * example `ruflo memory export --output ~/backup.json`). MCP requests arrive + * as JSON and cannot carry a symbol key, so this cannot be forged remotely. + */ +export const LOCAL_CLI_CALL: unique symbol = Symbol('ruflo.localCliCall'); + +export function localCliContext(): Record { + return { [LOCAL_CLI_CALL]: true } as unknown as Record; +} + +export function isLocalCliCall(context: unknown): boolean { + return !!context && typeof context === 'object' + && (context as Record)[LOCAL_CLI_CALL] === true; +} diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts index 95a683a2c2..bac822f7ea 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts @@ -4,11 +4,12 @@ * Tool definitions for session management with file persistence. */ -import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, unlinkSync, statSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync, unlinkSync, statSync, writeFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; import { gunzipSync } from 'node:zlib'; -import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { containedWritePath } from './path-containment.js'; import { mkdirRestricted, readFileMaybeEncrypted, @@ -406,34 +407,6 @@ function isSessionRecordLike(value: unknown): value is Partial { return 'data' in v || 'stats' in v || 'sessionId' in v || 'savedAt' in v; } -/** - * SECURITY: `outputPath` comes from MCP tool input. Resolve it against the - * project root and require the real (symlink-resolved) parent directory to stay - * inside the real project root, and refuse an existing symlink as the target, - * so session_export cannot write files elsewhere on the host. The CLI's - * `session export` writes its own file and does not pass outputPath. - */ -function containedExportPath(outputPath: string): string | null { - if (!outputPath || outputPath.includes('\0')) return null; - try { - const root = realpathSync(getProjectCwd()); - const abs = resolve(root, outputPath); - const parent = realpathSync(dirname(abs)); - const target = join(parent, basename(abs)); - const rel = relative(root, target); - if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null; - const existing = lstatOrNull(target); - if (existing && (existing.isSymbolicLink() || !existing.isFile())) return null; - return target; - } catch { - return null; - } -} - -function lstatOrNull(p: string) { - try { return lstatSync(p); } catch { return null; } -} - export const sessionTools: MCPTool[] = [ { name: 'session_save', @@ -806,7 +779,7 @@ export const sessionTools: MCPTool[] = [ let path: string | null = null; const outputPath = input.outputPath ? String(input.outputPath) : null; if (outputPath) { - const target = containedExportPath(outputPath); + const target = containedWritePath(outputPath); if (!target) return { sessionId, error: 'outputPath must be a file inside the project directory (no symlinks)' }; try { writeFileSync(target, JSON.stringify(session, null, 2), 'utf-8'); path = target; } catch (e) { return { sessionId, error: `Could not write ${outputPath}: ${(e as Error).message}` }; }