import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import path from 'node:path'; import { AUDIT_ARRAY_LIMIT, AUDIT_DEPTH_LIMIT, REDACTED, SECRET_VALUE_PATTERNS, SENSITIVE_KEY, containsSecretLikeContent, isSensitiveKey, redactAuditValue, safeAuditJson, scrubAuditText, scrubSecretContent, } from '../src/services/auditRedaction'; /** * 审计脱敏加固(H1,2026-09-24)。 * * 覆盖报告里的 4 类绕过探针(深度嵌套 / 非标准键名 / 数组截断 / 字符串内嵌) * + 我实测出的 16 型键名矩阵 + fail-closed 自检 + "不得误伤业务字段"。 * 设计:docs/design/20260924-audit-redaction-hardening.md */ const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); const FAKE_KEY = 'sk-REALKEY0123456789abcdef'; describe('① 深度嵌套探针(旧实现 depth>4 原样返回 → 整棵子树明文)', () => { it('超过深度上限的位置被丢弃,不再原样返回', () => { // 造一条深度 9 的链路,密钥放在最深处 let payload: Record = { apiKeys: FAKE_KEY }; for (let i = 0; i < 8; i += 1) payload = { [`level${i}`]: payload }; const out = JSON.stringify(redactAuditValue(payload)); expect(out).not.toContain('sk-REALKEY'); expect(out).toContain('[DEPTH_LIMIT]'); }); it('深度上限内的密钥照常被键名脱敏', () => { expect(redactAuditValue({ a: { b: { apiKeys: FAKE_KEY } } })).toEqual({ a: { b: { apiKeys: REDACTED } }, }); }); it('深度上限常量为正且不小于旧值(旧 4,新 6)', () => { expect(AUDIT_DEPTH_LIMIT).toBeGreaterThanOrEqual(4); }); }); describe('② 非标准键名探针(旧正则漏判 → 值明文)', () => { const sensitive = [ 'apiKey', 'apiKeys', 'api_key', 'api-keys', 'x-api-key', 'X-Api-Key', 'privateKey', 'private_key', 'accessKeyId', 'access_key', 'credential', 'credentials', 'appSecret', 'client_secret', 'secretKey', 'llmApiKey', 'sessionToken', 'refresh_token', 'idToken', 'authToken', 'cookie', 'signature', 'Authorization', 'signed_url', 'password', 'passwd', ]; it('全部命中(旧正则漏 api-key / x-api-key / privateKey / accessKeyId / credential / cookie / signature / signed_url)', () => { for (const key of sensitive) expect(isSensitiveKey(key), key).toBe(true); }); it('值一律写成 ***(不保留任何明文碎片)', () => { for (const key of sensitive) { const out = redactAuditValue({ [key]: FAKE_KEY }) as Record; expect(out[key], key).toBe(REDACTED); } }); it('不误伤业务字段(含 order_keys 这类带 key 的业务名)', () => { const business = [ 'sku_code', 'pack_factors', 'quantity', 'customer_code', 'unit_cost', 'order_keys', 'item_keys', 'stock_mode', 'pricing_unit', 'batch_no', 'delivery_date', ]; for (const key of business) { expect(isSensitiveKey(key), key).toBe(false); const out = redactAuditValue({ [key]: 'normal-value' }) as Record; expect(out[key], key).toBe('normal-value'); } }); it('SENSITIVE_KEY 仍与既有契约兼容(旧测试依赖它)', () => { expect(SENSITIVE_KEY.test('apiKeys')).toBe(true); expect(SENSITIVE_KEY.test('password')).toBe(true); expect(SENSITIVE_KEY.test('sku_code')).toBe(false); }); }); describe('③ 数组截断探针(旧实现静默丢尾部,无标记)', () => { it('超长数组保留前 N 项并给出折叠标记', () => { const arr = Array.from({ length: AUDIT_ARRAY_LIMIT + 5 }, (_, i) => ({ n: i, apiKeys: FAKE_KEY })); const out = redactAuditValue({ providers: arr }) as { providers: unknown[] }; expect(out.providers.length).toBe(AUDIT_ARRAY_LIMIT + 1); expect(out.providers[AUDIT_ARRAY_LIMIT]).toBe('[+5 more]'); // 前 N 项内的密钥仍被脱敏 expect(JSON.stringify(out)).not.toContain('sk-REALKEY'); }); it('数组里的对象按深度递归脱敏', () => { const out = redactAuditValue([{ api_key: FAKE_KEY, name: 'tokenhub' }]) as Array>; expect(out[0].api_key).toBe(REDACTED); expect(out[0].name).toBe('tokenhub'); }); }); describe('④ 字符串内嵌探针(旧实现只按长度截断 → 值里的密钥明文保留)', () => { it('键名不敏感、但值里含密钥 → 内容级替换', () => { const out = redactAuditValue({ note: `上游返回 Authorization: Bearer ${FAKE_KEY}`, command: `curl -H "X-Api-Key: ${FAKE_KEY}" https://x`, }) as Record; expect(out.note).not.toContain('sk-REALKEY'); expect(out.note).toContain('[REDACTED]'); expect(out.command).not.toContain('sk-REALKEY'); }); it('密钥出现在超长字符串的前 500 字符之外?仍要替换(先识别再截断)', () => { const long = `${'x'.repeat(600)} ${FAKE_KEY}`; const out = String((redactAuditValue({ note: long }) as Record).note); expect(out).not.toContain('sk-REALKEY'); expect(out.length).toBeLessThanOrEqual(501); }); it('6 类密钥形态都能识别(sk- / apikey- / Bearer / AKIA / JWT / PEM / 连接串 / 签名)', () => { const samples = [ `key=sk-abcdefghijklmnop1234`, `key=apikey-abcdefghijklmnop1234`, `key=ark-b3261234567890abcdef`, `Authorization: Bearer abcdefghijklmnopqrstuvwx`, `AKIAIOSFODNN7EXAMPLE`, `eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U`, `-----BEGIN RSA PRIVATE KEY-----`, `postgresql://hermes:SuperSecret123@1.13.62.2:20538/ai_fresh_delivery`, `https://cos.example.com/x?q-signature=abcdef0123456789abcdef`, ]; for (const sample of samples) { expect(containsSecretLikeContent(sample), sample).toBe(true); const scrubbed = scrubSecretContent(sample); expect(scrubbed).toContain('[REDACTED]'); expect(containsSecretLikeContent(scrubbed), sample).toBe(false); } // 形态清单本身有覆盖(防止有人删规则) expect(SECRET_VALUE_PATTERNS.length).toBeGreaterThanOrEqual(8); }); it('普通文本不受影响(不误伤 URL/编码/普通长文本)', () => { for (const text of [ 'https://example.com/orders?date=2026-09-21', '已灌入 2 行到录单页,尚未下单', 'x'.repeat(600), ]) { expect(containsSecretLikeContent(text), text).toBe(false); } expect(String((redactAuditValue({ note: 'x'.repeat(600) }) as Record).note)).toHaveLength(501); }); }); describe('⑤ fail-closed 自检(safeAuditJson)', () => { it('正常载荷:脱敏后 JSON 可入库', () => { const json = safeAuditJson({ order_code: 'ORD_1', apiKeys: FAKE_KEY }, 'test'); expect(json).not.toContain('sk-REALKEY'); expect(JSON.parse(String(json)).apiKeys).toBe(REDACTED); }); it('空值返回 null(与旧行为一致,保持"无值即 NULL")', () => { expect(safeAuditJson(null, 'test')).toBeNull(); expect(safeAuditJson(undefined, 'test')).toBeNull(); }); it('属性测试:密钥种到每个深度/数组位置/字符串中间,序列化结果 0 命中', () => { const payload: Record = {}; let cursor: Record = payload; for (let i = 0; i < AUDIT_DEPTH_LIMIT + 3; i += 1) { cursor[`nested${i}`] = { apiKeys: FAKE_KEY, note: `Bearer ${FAKE_KEY}`, arr: [FAKE_KEY, { k: FAKE_KEY }] }; cursor = cursor[`nested${i}`] as Record; } const serialized = String(safeAuditJson(payload, 'property-test')); expect(containsSecretLikeContent(serialized)).toBe(false); expect(serialized).not.toContain('sk-REALKEY'); }); }); describe('⑥ 非 JSON 原生类型:保持旧 JSON.stringify 语义(自查发现的回归)', () => { it('Date → ISO 串(旧实现如此;早期版本会变成 {} 导致审计丢时间)', () => { const out = redactAuditValue({ created_at: new Date('2026-09-24T01:02:03.000Z') }) as Record; expect(out.created_at).toBe('2026-09-24T01:02:03.000Z'); }); it('Buffer → {type,data}(与 JSON.stringify(Buffer) 一致)', () => { const out = redactAuditValue({ b: Buffer.from('abc') }) as Record; expect(out.b).toEqual({ type: 'Buffer', data: [97, 98, 99] }); }); it('BigInt → 字符串(旧实现会抛,审计写入失败)', () => { expect((redactAuditValue({ big: 10n }) as Record).big).toBe('10'); }); it('原始值直传不被改写(含 null/boolean/number)', () => { expect(redactAuditValue('plain')).toBe('plain'); expect(redactAuditValue(5)).toBe(5); expect(redactAuditValue(true)).toBe(true); expect(redactAuditValue(null)).toBeNull(); }); it('真实业务形态:Date + 明细 + 含签名 URL 的照片路径 —— 不整包替换,其它字段保留', () => { const realistic = { created_at: new Date('2026-09-24T01:02:03.000Z'), order_code: 'ORD_WEB_20260921_BR002_0001', photo_path: 'https://b.cos.ap-nanjing.tencentcos.cn/a.jpg?q-signature=abcdef0123456789abcdef', items: [{ sku_code: 'SKU1', qty: 2 }], }; const json = String(safeAuditJson(realistic, 'realistic')); expect(json).not.toContain('secret_pattern_detected'); // 不是整包替换 expect(json).toContain('ORD_WEB_20260921_BR002_0001'); expect(json).toContain('2026-09-24T01:02:03.000Z'); expect(json).toContain('SKU1'); expect(json).not.toContain('abcdef0123456789abcdef'); // 签名已替换 expect(containsSecretLikeContent(json)).toBe(false); }); }); describe('⑥b scrubAuditText(短字段清洗)', () => { it('命中密钥形态即替换;空值返回 null;超长截断', () => { expect(scrubAuditText(`/api/x?key=sk-${'a'.repeat(20)}`)).not.toContain('sk-aaaaaaaa'); expect(scrubAuditText(`/api/x?key=sk-${'a'.repeat(20)}`)).toContain('[REDACTED]'); expect(scrubAuditText('')).toBeNull(); expect(scrubAuditText(null)).toBeNull(); expect(String(scrubAuditText('z'.repeat(300))).length).toBeLessThanOrEqual(201); expect(scrubAuditText('ORD_WEB_20260921_BR002_0001')).toBe('ORD_WEB_20260921_BR002_0001'); }); }); describe('⑦ 收口棘轮:脱敏必须发生在 writeAuditLog 之内', () => { it('auditService 落库前走 safeAuditJson(而不是直接 JSON.stringify)', () => { const service = read('src/services/auditService.ts'); expect(service).toContain("import { safeAuditJson, scrubAuditText } from './auditRedaction';"); expect(service).toContain("safeAuditJson(input.oldValue, 'operation_logs.old_value')"); expect(service).toContain("safeAuditJson(input.newValue, 'operation_logs.new_value')"); expect(service).not.toContain('JSON.stringify(input.newValue)'); expect(service).not.toContain('JSON.stringify(input.oldValue)'); // 短字段(target_id / 表名 / 操作人…)也要清洗:防"密钥写进 URL/表名"这类夹带 expect(service).toContain('scrubAuditText(input.targetId)'); expect(service).toContain('scrubAuditText(input.targetTable)'); expect(service).toContain('scrubAuditText(input.operationType)'); }); it('中间件复用同一实现(不再各自维护一份脱敏)', () => { const mw = read('src/middleware/operationAuditMiddleware.ts'); expect(mw).toContain("from '../services/auditRedaction'"); expect(mw).toContain('redactAuditValue(body)'); // 旧的内联实现必须消失(它正是 4 个洞的来源) expect(mw).not.toContain('if (depth > 4 || value == null) return value;'); }); });