Files
metona-ai-desktop/electron/harness/tools/built-in/__tests__/file-guard.test.ts
T
thzxx 2230bcec3f feat: v0.4.0 四阶段迭代 — 安全加固 + 工程基线 + 架构重构 + 双 Provider 扩展
P0 安全修复:
- API Key 加密存储(safeStorage 密钥链,版本化前缀,历史明文平滑兼容)
- 间接提示注入防护(SecurityScanHook 工具结果深扫描,网络工具脱敏/本地工具警示分级)
- error:report IPC 断链修复(渲染进程错误上报落 electron-log + 审计)
- abort 信号贯通工具层(run_command/dev-tools 子进程随会话中断终止)
- run_command 沙箱加固(cd 系统目录/敏感文件读取拦截 + chcp 前缀剥离防解析退化)
- .env 真实生效(dotenv 回退加载,应用内配置优先)

P1 工程基础:
- ESLint 9 flat config + 全部 34 条存量 warnings 清零(零容忍基线)
- 测试基线 118 用例 11 文件(token/文件防护/权限/沙箱/注入/命令/引擎/注册表/审计链/摘要分层)
- test:electron 双模式(ELECTRON_RUN_AS_NODE 跑 Electron ABI,SQLite 套件全执行)
- SessionRecorder 多会话隔离 + 9 种 TRACE 事件补全(含最终轮 iteration_end)
- Provider 故障转移(重试耗尽/不可重试一次性切换 fallback + 前端通知)
- MCP 真就绪(等待全部连接完成再广播 tools:ready)
- SLO/HealthChecker 真实接入(60s 巡检 + 托盘状态)
- CONFIG_DEFAULTS 单一来源(消除 SEED 双源漂移)

P2 架构升级:
- handlers.ts 1940 行拆分为 13 个 IPC 域模块(防重入注册 + 多窗口广播)
- AgentEngineManager 每会话独立引擎(LRU 30 + adapter 工厂隔离 abort 信号)
- TaskOrchestrator EngineProvider 改造 + abortByParent 联动中断 SubAgent
- 会话摘要分层上下文(session_summaries 滚动摘要 + 截断游标清理防因果污染)
- 消息编辑重发/重新生成(truncateAfter IPC + store 动作 + UI)
- Markdown 导出 / WebSearch 并行抓取(并发 3)/ 记忆 TF 缓存 / 版本构建期注入

P3 能力扩展:
- OpenAI Adapter(o 系列推理模型 reasoning_effort/max_completion_tokens)
- Anthropic Adapter(原生 Messages API:tool_use 块/角色合并/thinking budget/图片 base64/SSE 事件机)
- 设置页/Onboarding 六 Provider 全链路接入
2026-08-20 23:17:02 +08:00

187 lines
5.9 KiB
TypeScript

/**
* File Guard 单元测试(P1-14 测试基线)
* 覆盖:路径遍历防护、前缀碰撞、MEMORY.md 保护、glob 匹配、编码检测
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
isPathWithinWorkspace,
isProtectedWorkspaceFile,
safeResolvePath,
matchGlob,
matchAnyGlob,
commandTouchesProtectedFile,
decodeBufferWithDetection,
} from '../file-guard';
describe('isPathWithinWorkspace', () => {
const ws = join(tmpdir(), 'metona-test-ws');
beforeAll(() => {
mkdirSync(ws, { recursive: true });
});
it('工作空间内的相对路径通过', () => {
expect(isPathWithinWorkspace('src/main.ts', ws)).toBe(true);
});
it('工作空间内的绝对路径通过', () => {
expect(isPathWithinWorkspace(join(ws, 'src/main.ts'), ws)).toBe(true);
});
it('工作空间根目录本身通过', () => {
expect(isPathWithinWorkspace('.', ws)).toBe(true);
});
it('路径遍历(../)被拒绝', () => {
expect(isPathWithinWorkspace('../etc/passwd', ws)).toBe(false);
});
it('多层遍历(../../..)被拒绝', () => {
expect(isPathWithinWorkspace('../../../etc/passwd', ws)).toBe(false);
});
it('前缀碰撞不误判(/app-evil 不在 /app 内)', () => {
const parent = join(tmpdir(), 'metona-prefix-app');
mkdirSync(parent, { recursive: true });
expect(isPathWithinWorkspace(join(tmpdir(), 'metona-prefix-app-evil/x'), parent)).toBe(false);
});
it('绝对路径指向工作空间外被拒绝', () => {
expect(isPathWithinWorkspace('C:\\Windows\\System32\\cmd.exe', ws)).toBe(false);
});
});
describe('isProtectedWorkspaceFile / safeResolvePath', () => {
const ws = join(tmpdir(), 'metona-test-protect');
beforeAll(() => {
mkdirSync(join(ws, 'sub'), { recursive: true });
});
it('工作空间根目录的 MEMORY.md 受保护', () => {
expect(isProtectedWorkspaceFile('MEMORY.md', ws)).toBe(true);
});
it('子目录的 MEMORY.md 不受保护', () => {
expect(isProtectedWorkspaceFile(join('sub', 'MEMORY.md'), ws)).toBe(false);
});
it('safeResolvePath 拒绝越界路径并抛错', () => {
expect(() => safeResolvePath('../outside.txt', ws)).toThrow(/Path traversal/);
});
it('safeResolvePath 拒绝根目录 MEMORY.md 并抛错', () => {
expect(() => safeResolvePath('MEMORY.md', ws)).toThrow(/MEMORY.md/);
});
it('safeResolvePath 正常解析工作空间内路径', () => {
const resolved = safeResolvePath('src/a.ts', ws);
expect(resolved).toBe(join(ws, 'src/a.ts'));
});
});
describe('commandTouchesProtectedFile', () => {
it('裸引用 MEMORY.md 被拦截', () => {
expect(commandTouchesProtectedFile('cat MEMORY.md')).toBe(true);
});
it('子目录 MEMORY.md 不被拦截', () => {
expect(commandTouchesProtectedFile('cat sub/MEMORY.md')).toBe(false);
expect(commandTouchesProtectedFile('cat sub\\MEMORY.md')).toBe(false);
});
it('管道/分号后的 MEMORY.md 被拦截', () => {
expect(commandTouchesProtectedFile('echo x | cat MEMORY.md; rm file')).toBe(true);
});
it('无关命令不误判', () => {
expect(commandTouchesProtectedFile('npm run test')).toBe(false);
expect(commandTouchesProtectedFile('git status')).toBe(false);
});
});
describe('matchGlob / matchAnyGlob', () => {
it('单 glob 匹配', () => {
expect(matchGlob('main.ts', '*.ts')).toBe(true);
expect(matchGlob('main.js', '*.ts')).toBe(false);
});
it('? 单字符匹配', () => {
expect(matchGlob('test1.js', 'test?.js')).toBe(true);
expect(matchGlob('test12.js', 'test?.js')).toBe(false);
});
it('逗号分隔多 glob 任一匹配', () => {
expect(matchAnyGlob('a.ts', '*.ts,*.js,*.tsx')).toBe(true);
expect(matchAnyGlob('a.jsx', '*.ts,*.js,*.tsx')).toBe(false);
});
it('空 glob 字符串匹配所有', () => {
expect(matchAnyGlob('anything.txt', '')).toBe(true);
});
});
describe('decodeBufferWithDetection', () => {
it('UTF-8 无 BOM 正确解码', () => {
const buf = Buffer.from('你好 world', 'utf-8');
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe('你好 world');
expect(encoding).toBe('utf-8');
});
it('UTF-8 BOM 被剥离并识别', () => {
const body = Buffer.from('hello', 'utf-8');
const buf = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe('hello');
expect(encoding).toBe('utf-8-bom');
});
it('UTF-16 LE BOM 正确解码', () => {
const body = '你好';
const buf = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(body, 'utf16le')]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe(body);
expect(encoding).toBe('utf-16le');
});
it('UTF-16 BE BOM 正确解码(字节交换)', () => {
const body = '你好';
const le = Buffer.from(body, 'utf16le');
const be = Buffer.from(le);
be.swap16();
const buf = Buffer.concat([Buffer.from([0xfe, 0xff]), be]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe(body);
expect(encoding).toBe('utf-16be');
});
it('空 Buffer 返回空内容', () => {
const { content, encoding } = decodeBufferWithDetection(Buffer.alloc(0));
expect(content).toBe('');
expect(encoding).toBe('utf-8');
});
});
describe('workspace 文件读取场景(临时目录)', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-guard-'));
writeFileSync(join(ws, 'file.txt'), 'content', 'utf-8');
});
afterAll(() => {
rmSync(ws, { recursive: true, force: true });
});
it('工作空间内文件路径通过校验', () => {
expect(isPathWithinWorkspace('file.txt', ws)).toBe(true);
expect(isPathWithinWorkspace(join(ws, 'file.txt'), ws)).toBe(true);
});
});