import { describe, expect, it } from 'vitest'; import { SENSITIVE_KEY, redactValue } from '../src/middleware/operationAuditMiddleware'; /** * 审计日志脱敏(P0-4 关联): * 平台/分公司 LLM 配置保存时请求体里的 `apiKeys` 会被写进 operation_logs, * 而原先的 SENSITIVE_KEY 正则**不含 api_?keys?** —— 生产实测有 3 行明文密钥 * (2026-09-09 18:28/18:32 保存 platform-llm-config / branch-llm-config)。 * 见 docs/design/20260915-audit-redact-api-keys.md */ describe('SENSITIVE_KEY', () => { it('覆盖 LLM 密钥相关字段名', () => { for (const key of ['apiKeys', 'api_keys', 'apiKey', 'llmApiKey', 'llm_api_key']) { expect(SENSITIVE_KEY.test(key), key).toBe(true); } }); it('仍覆盖凭证类字段名', () => { for (const key of ['password', 'passwd', 'secret', 'token', 'authorization', 'private_key', 'access_key']) { expect(SENSITIVE_KEY.test(key), key).toBe(true); } }); it('不误伤业务字段', () => { for (const key of ['sku_code', 'pack_factors', 'quantity', 'customer_code', 'unit_cost']) { expect(SENSITIVE_KEY.test(key), key).toBe(false); } }); }); describe('redactValue', () => { it('把 LLM 配置请求体里的 apiKeys 置为 ***,其余字段保留', () => { const body = { model: 'deepseek/deepseek-v4-flash-vision-exp', apiKeys: 'sk-REALKEY0123456789', baseUrl: 'https://tokenhub.tencentmaas.com/v1', }; expect(redactValue(body)).toEqual({ model: 'deepseek/deepseek-v4-flash-vision-exp', apiKeys: '***', baseUrl: 'https://tokenhub.tencentmaas.com/v1', }); }); it('嵌套对象与数组同样脱敏', () => { const out = redactValue({ providers: [{ api_key: 'sk-x', name: 'tokenhub' }] }) as any; expect(out.providers[0].api_key).toBe('***'); expect(out.providers[0].name).toBe('tokenhub'); }); it('Authorization 头一类也脱敏', () => { const out = redactValue({ headers: { Authorization: 'Bearer abc' } }) as any; expect(out.headers.Authorization).toBe('***'); }); it('超长字符串截断(防止日志爆量)', () => { const long = 'x'.repeat(600); expect(String(redactValue({ note: long }).note).length).toBe(501); }); });