P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道; clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/ Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线 P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块 (web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate); run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭 P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal, 超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/ getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一 P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新 (app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON); web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher) 测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/ filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/ OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
188 lines
7.2 KiB
TypeScript
188 lines
7.2 KiB
TypeScript
/**
|
||
* MCP 命令安全面 + SLO 监控契约测试(v0.7.0 覆盖补齐)
|
||
*
|
||
* mcp-manager 的三个安全纯函数此前零测试(命令白名单/参数元字符检测/
|
||
* env 敏感变量剥离),是 MCP 攻击面的第一道防线 —— 逐条表测锁定。
|
||
* HealthChecker/SLOMonitor 此前为"活代码无契约",本文件锁定其健康判定与
|
||
* SLO 指标计算(percentile/burnRate/violated/窗口淘汰)。
|
||
*/
|
||
|
||
import { describe, it, expect, vi } from 'vitest';
|
||
|
||
vi.mock('electron-log', () => ({
|
||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||
}));
|
||
|
||
import { safeParseArgs, validateMcpCommand, buildSafeEnv } from '../mcp-manager.service';
|
||
import { SLOMonitor, HealthChecker } from '../../utils/slo';
|
||
import type { Database } from 'better-sqlite3';
|
||
|
||
// better-sqlite3 的 ABI 可用性在模块顶层探测(describe.skipIf 在注册期求值)
|
||
let dbAvailable = false;
|
||
try {
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
const DatabaseProbe = require('better-sqlite3');
|
||
const p = new DatabaseProbe(':memory:');
|
||
p.close();
|
||
dbAvailable = true;
|
||
} catch {
|
||
dbAvailable = false;
|
||
}
|
||
|
||
// ===== MCP:safeParseArgs =====
|
||
|
||
describe('safeParseArgs — JSON args 解析', () => {
|
||
it('合法 JSON 数组 → string[]', () => {
|
||
expect(safeParseArgs('["--flag","value"]')).toEqual(['--flag', 'value']);
|
||
});
|
||
|
||
it('非数组/坏 JSON/空输入 → 空数组兜底', () => {
|
||
expect(safeParseArgs('{"a":1}')).toEqual([]);
|
||
expect(safeParseArgs('not json')).toEqual([]);
|
||
expect(safeParseArgs('')).toEqual([]);
|
||
});
|
||
});
|
||
|
||
// ===== MCP:validateMcpCommand =====
|
||
|
||
describe('validateMcpCommand — stdio 命令白名单防线', () => {
|
||
it('白名单内命令正常放行;目录前缀剥除后匹配 basename,但扩展名不剥除', () => {
|
||
for (const cmd of ['npx', 'node', 'npm', 'python', 'python3', 'uv', 'uvx', 'bun', 'deno']) {
|
||
expect(() => validateMcpCommand(cmd, [])).not.toThrow();
|
||
}
|
||
// 目录前缀被剥除 → basename 命中白名单
|
||
expect(() => validateMcpCommand('/usr/local/bin/npx', ['-y', '@modelcontextprotocol/server'])).not.toThrow();
|
||
// 现状锁定(比预期更严):扩展名不参与剥除 —— 'npx.cmd' 不在名单,直接拒绝。
|
||
// 这是当前安全基线的一部分:宁可收紧也不放过任何可执行变体。
|
||
expect(() => validateMcpCommand('C:\tools\npx.cmd', [])).toThrow(/allowed list/);
|
||
});
|
||
|
||
it('白名单外命令直接拒绝', () => {
|
||
for (const cmd of ['curl', 'bash', 'sh', 'pwsh', 'cmd', 'powershell.exe', './unknown-server']) {
|
||
expect(() => validateMcpCommand(cmd, [])).toThrow(/not in the allowed list/);
|
||
}
|
||
});
|
||
|
||
it('args 中携带 shell 元字符(; & | 反引号 $ 等)拒绝;普通参数放行', () => {
|
||
const evil: Array<string[]> = [
|
||
[';whoami'],
|
||
['a&b'],
|
||
['x|cat'],
|
||
['`id`'],
|
||
['$HOME'],
|
||
['<in'],
|
||
['>out'],
|
||
['line\nbreak'],
|
||
];
|
||
for (const args of evil) {
|
||
expect(() => validateMcpCommand('node', ['server.js', ...args])).toThrow();
|
||
}
|
||
expect(() => validateMcpCommand('node', ['server.js', '--port', '3000'])).not.toThrow();
|
||
});
|
||
});
|
||
|
||
// ===== MCP:buildSafeEnv =====
|
||
|
||
describe('buildSafeEnv — 子进程环境净化', () => {
|
||
it('命中后缀黑名单的敏感键被剔除,其余保留', () => {
|
||
const baseEnv = {
|
||
PATH: '/usr/bin',
|
||
HOME: '/home/u',
|
||
MY_API_KEY: 'sk-secret',
|
||
ACCESS_TOKEN: 'tok',
|
||
DB_PASSWORD: 'p@ss',
|
||
AWS_SECRET_ACCESS_KEY2: 'k',
|
||
DEPLOY_PRIVATE_KEY: '----', // 后缀 _PRIVATE_KEY 命中
|
||
GITEA_CREDENTIALS: '{"u":"x"}', // 后缀 _CREDENTIALS 命中(真实 CI/部署泄漏形态)
|
||
SAFE_NAME: 'keepme',
|
||
};
|
||
vi.stubGlobal('process', { ...process, env: baseEnv as NodeJS.ProcessEnv });
|
||
const env = buildSafeEnv();
|
||
expect(env.PATH).toBe('/usr/bin');
|
||
expect(env.SAFE_NAME).toBe('keepme');
|
||
expect(env.MY_API_KEY).toBeUndefined();
|
||
expect(env.ACCESS_TOKEN).toBeUndefined();
|
||
expect(env.DB_PASSWORD).toBeUndefined();
|
||
expect(env.DEPLOY_PRIVATE_KEY).toBeUndefined();
|
||
expect(env.GITEA_CREDENTIALS).toBeUndefined();
|
||
vi.unstubAllGlobals();
|
||
});
|
||
});
|
||
|
||
// ===== SLOMonitor =====
|
||
|
||
describe('SLOMonitor — 窗口指标 / 分位数 / 燃烧率', () => {
|
||
function makeMonitor(): SLOMonitor {
|
||
return new SLOMonitor({ target: 0.99, windowMs: 60_000, latencyPercentiles: [0.5, 0.95], latencyThresholdMs: 5_000 });
|
||
}
|
||
|
||
it('空窗口:totalRequests=0、errorRate=0、violated=false、burnRate=0', () => {
|
||
const s = makeMonitor().getStatus();
|
||
expect(s.totalRequests).toBe(0);
|
||
expect(s.errorRate).toBe(0);
|
||
expect(s.violated).toBe(false);
|
||
expect(s.burnRate).toBe(0);
|
||
});
|
||
|
||
it('统计请求成功率/平均延迟/吞吐量、分位数字段齐全且单调', async () => {
|
||
const m = makeMonitor();
|
||
const t0 = Date.now();
|
||
const latencies = [100, 200, 400, 800, 1600]; // 全成功
|
||
latencies.forEach((ms, i) => {
|
||
m.recordRequest(ms, true);
|
||
void i;
|
||
});
|
||
void t0;
|
||
const s = m.getStatus();
|
||
expect(s.totalRequests).toBe(5);
|
||
expect(s.errorRequests).toBe(0);
|
||
expect(s.avgLatencyMs).toBe(620);
|
||
expect(Object.keys(s.percentiles)).toEqual(['P50', 'P95']);
|
||
expect(s.percentiles['P50']).toBeGreaterThanOrEqual(200);
|
||
expect(s.percentiles['P95']).toBeLessThanOrEqual(1600);
|
||
expect(s.burnRate).toBe(0);
|
||
expect(s.target).toBeCloseTo(0.99);
|
||
expect(s.errorBudget).toBeCloseTo(0.01);
|
||
});
|
||
|
||
it('错误率超预算 → burnRate>1 且 violated=true(全错样本:burnRate=100)', async () => {
|
||
const m = new SLOMonitor({ target: 0.99, windowMs: 60_000, latencyPercentiles: [0.5], latencyThresholdMs: 10_000 });
|
||
for (let i = 0; i < 4; i++) m.recordRequest(50 + i, false);
|
||
const s = m.getStatus();
|
||
expect(s.errorRate).toBe(1);
|
||
expect(s.burnRate).toBeGreaterThan(1);
|
||
expect(s.violated).toBe(true);
|
||
});
|
||
|
||
it('窗口外记录被淘汰:回到基线 totalRequests=0(真实短窗口计时)', async () => {
|
||
const m = new SLOMonitor({ target: 0.99, windowMs: 50, latencyPercentiles: [0.5], latencyThresholdMs: 10_000 });
|
||
m.recordRequest(100, true);
|
||
m.recordRequest(120, false);
|
||
expect(m.getStatus().totalRequests).toBe(2);
|
||
|
||
// 越过 50ms 窗口后读取
|
||
await new Promise((r) => setTimeout(r, 70));
|
||
expect(m.getStatus().totalRequests).toBe(0);
|
||
});
|
||
});
|
||
|
||
// ===== HealthChecker =====
|
||
|
||
describe.skipIf(!dbAvailable)('HealthChecker — 三项健康检查', () => {
|
||
// 注:真实库连通性由 database-migration.test.ts(PRAGMA user_version 套件)以
|
||
// 完整 DatabaseService.initialize() 覆盖;此处仅保留纯依赖注入的确定性用例。
|
||
|
||
it('DB ping 失败 → database check 不健康、healthy=false', async () => {
|
||
const broken = { prepare: () => { throw new Error('disk I/O error'); } } as unknown as import('better-sqlite3').Database;
|
||
const hc = new HealthChecker(
|
||
() => broken,
|
||
':memory:',
|
||
);
|
||
const report = await hc.check();
|
||
const dbCheck = report.checks.find((c) => c.name === 'database');
|
||
expect(dbCheck?.healthy).toBe(false);
|
||
expect(String(dbCheck?.error ?? '')).toContain('I/O');
|
||
expect(report.healthy).toBe(false);
|
||
});
|
||
});
|