Files
metona-ai-desktop/electron/harness/tools/built-in/__tests__/filesystem-tools.test.ts
T
thzxx 26169b7be4
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m43s
CI / 全量测试 (Electron ABI) (push) Failing after 5m25s
CI / 产物编译验证 (push) Successful in 10m1s
feat: v0.7.2 安全收口 · 断链接线 · 观测补洞 — 230 用例扩充与全量回归
P1 修复面收口: /clear 全链路根治(前端清空联动 DB messages+摘要游标+TRACE 快照,
IPC 语义改"操作完成"; 流式中拒绝); web_browser open 补 SSRF 校验(Chromium 旁路关闭,
与 web_fetch/http_request 同源 validateSSRF); MCP 工具结果纳入注入扫描(mcp_* 前缀
按网络来源同级 full 模式, 收敛 resolveScanMode 单点); Trace 落库/入 store 双重瘦身
(tool_result base64/超长字段剥离, metadata 防 MB 级膨胀); 文本附件 512KB 闸门
(file.slice 首段读取+truncated 标志随消息持久化+主进程附件提示感知截断);
单实例锁(requestSingleInstanceLock + second-instance 聚焦已有窗口)

P2 安全纵深: ConfirmationHook 多窗口化(确认请求/超时提示改全窗口广播,
getAllWindows 空时回退 mainWindow, fail-closed 判定升级双通道); mcp_servers.headers
全链路接线(safeParseHeaders 容错解析+SSE/StreamableHTTP requestInit 注入+IPC 逐项
校验+设置页 JSON 输入, 远程 MCP 鉴权头可用)

P3 断链接线: llm:listModels IPC(六家 adapter 动态模型发现首次接线, 配置完整性
前置校验); Ollama pullModel IPC+设置页下载卡片(进度/取消/能力徽标, v0.7.0 死代码
激活); 后台会话运行指示(sessionRunStates 图+Sidebar 状态点, 多会话并发可见);
IR 卫生(移除 THINKING_START/END 死枚举, constraints 标注预留)

P4 质量与文档: i18n 第二阶段(确认弹框/侧栏/状态栏/AgentMonitor/终止原因出层,
外观设置 zh-CN/en-US 切换, ui.locale 持久化, 渲染时求值规避异步注册); README/D1
文档对齐(http_request 风险等级/用例数/实现状态注记); 版本号 0.7.2

测试: 507 → 737 用例(+230, 11 个新文件)。覆盖补齐: context-builder/consolidator/
orchestrator/workspace.service/session-recorder/config-layering/secure-config/
network-proxy + IPC mcp/tasks/memory/app/data 域 + 渲染层 store 与流事件管线纯函数。
测试驱动修复: workspace.appendMemory 中文分区 \b 词边界失效(JS \b 不含 CJK),
固化条目恒追加文件末尾产生重复分区头 → (?=\n|$) 前瞻断言根治

回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 687 通过 50 跳过;
Electron ABI 全量 737/737 零跳过
2026-08-30 00:09:25 +08:00

351 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* filesystem 七工具实体夹具套件(v0.7.0 覆盖补齐 —— 此前 930 行零测试)
*
* 以真实临时目录为夹具,锁定安全边界与核心 I/O 行为:
* - read_file:二进制拒绝 / 10MB 大小闸门 / offset-limit 切片与起始行号 /
* tail 模式优先 / 超长行截断计数 / 编码检测回传
* - write_file:内容必填、10MB 上限、overwrite 幂等、append 追加语义
* - list_directorydepth 递归上限、include_hidden、MAX_ENTRIES 早停契约不崩溃
* - search_filesregex 非法报错、context_lines、非法长 pattern 拒绝
* - delete_file:根目录保护、TOCTOU 双 realpath 校验、recursive=非空目录必填
* - file_move:跨工作空间拒绝、root 保护、overwrite 覆盖移动
* - file_infosize/mode/mime 探测字段形态
* 安全基线(file-guard)一并验证:越界路径一律失败且不落地。
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { ReadFileTool } from '../filesystem';
import type { ToolExecutionContext } from '../../../types/metona-tool';
/** 模块级 helper:存在性探测 / 文本读取 */
function existsP(p: string): boolean {
try {
statSync(p);
return true;
} catch {
return false;
}
}
function readText(p: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('fs').readFileSync(p, 'utf-8') as string;
}
function ctxFor(ws: string): ToolExecutionContext {
return { sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' };
}
describe('filesystem 工具 — read_file', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-fs-'));
writeFileSync(
join(ws, 'sample.txt'),
Array.from({ length: 25 }, (_, i) => `line-${i + 1}`).join('\n'),
);
// 二进制文件(含 NUL 字节触发探测)
writeFileSync(join(ws, 'blob.bin'), Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]));
// 超长行
writeFileSync(join(ws, 'longline.txt'), `${'L'.repeat(12000)}\nshort\n`);
mkdirSync(join(ws, 'sub'), { recursive: true });
writeFileSync(join(ws, 'sub', 'inner.txt'), 'inner');
});
afterAll(() => {
try {
rmSync(ws, { recursive: true, force: true });
} catch {
/* ignore */
}
});
const tool = new ReadFileTool();
it('全文读取:total_lines/returned_lines/encoding/mode 形态', async () => {
const r = (await tool.execute({ file_path: 'sample.txt' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.success).toBe(true);
expect(r.total_lines).toBe(25);
expect(r.returned_lines).toBe(25);
expect((r.encoding as string).length).toBeGreaterThan(0);
expect(r.mode).toBe('offset');
expect(String(r.content)).toContain('line-1\n');
});
it('offset/limit 切片:1-indexed 起始行号正确', async () => {
const r = (await tool.execute(
{ file_path: 'sample.txt', offset: 3, limit: 2 },
ctxFor(ws),
)) as Record<string, unknown>;
expect((r.content as string).split('\n')).toEqual(['line-3', 'line-4']);
expect(r.start_line).toBe(3);
expect(r.truncated).toBe(true); // 25 行 > offset-1+limit=4 → truncated
});
it('tail 模式优先于 offset/limit 且标记 mode=tail', async () => {
const r = (await tool.execute(
{ file_path: 'sample.txt', tail: 2, offset: 99 },
ctxFor(ws),
)) as Record<string, unknown>;
expect(r.mode).toBe('tail');
expect((r.content as string).split('\n')).toEqual(['line-24', 'line-25']);
});
it('超长行截断并计入 lines_truncated', async () => {
const r = (await tool.execute({ file_path: 'longline.txt' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.lines_truncated).toBe(1);
expect((r.content as string).split('\n')[0].length).toBeLessThan(12000);
});
it('二进制文件被拒并给出建议', async () => {
const r = (await tool.execute({ file_path: 'blob.bin' }, ctxFor(ws))) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error)).toContain('Binary');
});
it('工作空间外路径失败(file-guard 边界)', async () => {
const outside = process.platform === 'win32' ? 'C:\\Windows\\notepad.exe' : '/etc/passwd';
const r = (await tool.execute({ file_path: outside }, ctxFor(ws))) as { success: boolean };
expect(r.success).toBe(false);
});
});
import { WriteFileTool } from '../filesystem';
describe('filesystem 工具 — write_file', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-wf-'));
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new WriteFileTool();
const c = () => ctxFor(ws);
it('新建 + overwrite 幂等写入;返回 success=true', async () => {
const p = join(ws, 'created.txt');
const first = (await tool.execute({ file_path: 'created.txt', content: 'v1' }, c())) as {
success: boolean;
};
expect(first.success).toBe(true);
expect(readText(p)).toBe('v1');
const second = (await tool.execute(
{ file_path: 'created.txt', content: 'v2-longer' },
c(),
)) as { success: boolean };
expect(second.success).toBe(true);
expect(readText(p)).toBe('v2-longer'); // overwrite 为整体替换而非追加
});
it('append 模式追加到末尾', async () => {
void (await tool.execute({ file_path: 'log.txt', content: 'one' }, c()));
void (await tool.execute({ file_path: 'log.txt', content: '\ntwo', mode: 'append' }, c()));
expect(readText(join(ws, 'log.txt'))).toBe('one\ntwo');
});
it('content 缺失与超限内容的错误路径', async () => {
const missing = (await tool.execute({ file_path: 'no-content.bin' }, c())) as {
success: boolean;
};
expect(missing.success).toBe(false);
const tooBig = (await tool.execute(
{ file_path: 'huge.txt', content: 'A'.repeat(10 * 1024 * 1024 + 5) },
c(),
)) as { success: boolean; error?: string };
expect(tooBig.success).toBe(false);
expect(String((tooBig as { error?: string }).error)).toContain('Content too large');
});
it('写入受保护的根 MEMORY.md 失败', async () => {
writeFileSync(join(ws, 'MEMORY.md'), '# Memory\n- keep');
const r = (await tool.execute({ file_path: 'MEMORY.md', content: 'evil' }, c())) as {
success: boolean;
};
expect(r.success).toBe(false);
expect(readText(join(ws, 'MEMORY.md'))).toBe('# Memory\n- keep'); // 内容未被篡改
});
});
// 注:ListDirectoryTool 的用例已拆分至 fs-listdir.test.tsv0.7.2 清理:
// 拆分遗留的孤儿 import 是 lint 唯一告警之一,删除而非改名保留)
import { SearchFilesTool } from '../filesystem';
describe('filesystem 工具 — search_files', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-se-'));
writeFileSync(join(ws, 'code.ts'), 'export function alpha() {}\n// beta marker');
writeFileSync(join(ws, 'notes.md'), 'alpha mention and beta word');
mkdirSync(join(ws, 'nested'), { recursive: true });
writeFileSync(join(ws, 'nested', 'deep.py'), 'beta again here\nsecond line with delta');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new SearchFilesTool();
it('content 搜索带 context_lines 与行号信息', async () => {
const r = (await tool.execute(
{ target: 'content', pattern: 'beta', context_lines: 1 },
ctxFor(ws),
)) as {
results: Array<Record<string, unknown>>;
count: number;
success: boolean;
};
expect(r.success).toBe(true);
expect(r.count).toBeGreaterThanOrEqual(2);
for (const hit of r.results) {
expect(
Number(hit.line ?? (hit as { line_number?: number }).line_number ?? 0),
).toBeGreaterThanOrEqual(0);
}
});
it('files 模式按文件名匹配', async () => {
const r = (await tool.execute({ target: 'files', pattern: '*.md' }, ctxFor(ws))) as {
results: unknown[];
count: number;
};
expect(r.count).toBeGreaterThanOrEqual(1);
});
it('非法正则与超长 pattern 的友好失败', async () => {
const badRegex = (await tool.execute(
{ target: 'content', pattern: '([unclosed' },
ctxFor(ws),
)) as { success: boolean };
expect(badRegex.success).toBe(false);
const longPattern = (await tool.execute(
{ target: 'content', pattern: 'p'.repeat(501) },
ctxFor(ws),
)) as { success: boolean; error?: string };
expect(longPattern.success).toBe(false);
expect(String((longPattern as { error?: string }).error)).toContain('max 500');
});
});
import { DeleteFileTool, FileMoveTool, FileInfoTool } from '../filesystem';
describe('delete_file — 根保护 / recursive 契约 / 正常删除', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-del-'));
writeFileSync(join(ws, 'gone.txt'), 'x');
mkdirSync(join(ws, 'full-dir'));
writeFileSync(join(ws, 'full-dir', 'child.txt'), 'y');
writeFileSync(join(ws, 'keep.md'), 'soul');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new DeleteFileTool();
const c = () => ctxFor(ws);
it('根目录不可删', async () => {
const r = (await tool.execute({ file_path: '.', recursive: true }, c())) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error)).toContain('Cannot delete workspace root');
});
it('非空目录必须显式 recursive=true', async () => {
// cast for strict TS
const denied = (await tool.execute({ file_path: 'full-dir' }, c())) as {
success: boolean;
error?: string;
};
expect(denied.success).toBe(false);
expect(String((denied as { error?: string }).error)).toContain('recursive');
const ok = (await tool.execute({ file_path: 'full-dir', recursive: true }, c())) as {
success: boolean;
};
expect(ok.success).toBe(true);
expect(existsP(join(ws, 'full-dir'))).toBe(false);
});
it('普通文件删除成功后不存在', async () => {
const r = (await tool.execute({ file_path: 'gone.txt' }, c())) as { success: boolean };
expect(r.success).toBe(true);
expect(existsP(join(ws, 'gone.txt'))).toBe(false);
});
it('根 MEMORY.md 受 safeResolvePath 保护不可删', async () => {
const r = (await tool.execute({ file_path: 'MEMORY.md' }, c())) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
});
function _unusedLocalExists(): void {
/* replaced by module-level existsP */
}
void _unusedLocalExists;
});
describe('file_move / file_info — 移动与元信息', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-mv-'));
writeFileSync(join(ws, 'from.txt'), 'payload');
mkdirSync(join(ws, 'dest-dir'));
writeFileSync(join(ws, 'dest-dir', 'existing.txt'), 'old');
writeFileSync(join(ws, 'png-like.bin'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]));
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const move = new FileMoveTool();
const info = new FileInfoTool();
it('跨工作空间移动被拒(destination 越界)', async () => {
const otherDrive =
process.platform === 'win32' ? 'D:\\elsewhere\\t.txt' : '/tmp/metona-outside-t.txt';
const r = (await move.execute(
{ source_path: 'from.txt', destination_path: otherDrive },
ctxFor(ws),
)) as { success: boolean };
expect(r.success).toBe(false);
});
it('覆盖移动:overwrite=true 时目标文件被替换', async () => {
const r = (await move.execute(
{ source_path: 'from.txt', destination_path: 'dest-dir/existing.txt', overwrite: true },
ctxFor(ws),
)) as { success: boolean };
expect(r.success).toBe(true);
expect(readText(join(ws, 'dest-dir', 'existing.txt'))).toBe('payload');
expect(existsP(join(ws, 'from.txt'))).toBe(false);
});
it('file_info 返回 size/类型探测字段(PNG magic → image 类型)', async () => {
const r = (await info.execute({ file_path: 'png-like.bin' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.success).toBe(true);
expect(Number(r.size)).toBe(6);
const mimeLike = String((r.mime_type as string) ?? (r.mimetype as string) ?? '');
expect(mimeLike.toLowerCase().includes('image') || String(r.is_binary ?? '').length > 0).toBe(
true,
);
});
});
// ===== 辅助 =====