chore: 恢复 demo 演示与设计文档入库
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* 操作审计 Demo · 核心逻辑单元测试
|
||||
*
|
||||
* 运行:node --test demo/test/audit-core.test.mjs
|
||||
* 覆盖对象(与技术方案第 7 节测试策略对应):
|
||||
* - shouldCapture 捕获规则(D1)
|
||||
* - resolveResource 资源解析(5.2)
|
||||
* - applyFilters 筛选(产品设计 4.2)
|
||||
* - paginate 分页
|
||||
* - countExpired 保留期清理(D5)
|
||||
* - MockData 模拟数据生成器(确定性、字段完整性)
|
||||
*/
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const AuditCore = require('../assets/audit-core.js');
|
||||
const MockData = require('../assets/mock-data.js');
|
||||
|
||||
// ---------------- shouldCapture(D1 捕获规则) ----------------
|
||||
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true }),
|
||||
{ captured: true, reason: '已登录用户对 /apis/** 的写操作,予以记录' }
|
||||
);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'put', path: '/apis/v1alpha1/configmaps/system', authenticated: true }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'DELETE', path: '/apis/content.halo.run/v1alpha1/posts/x', authenticated: true }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'PATCH', path: '/apis/v1alpha1/users/x', authenticated: true }).captured, true);
|
||||
});
|
||||
|
||||
test('shouldCapture: 读操作不记录', () => {
|
||||
for (const method of ['GET', 'HEAD', 'OPTIONS']) {
|
||||
const r = AuditCore.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
|
||||
assert.equal(r.captured, false, method + ' 不应被记录');
|
||||
assert.match(r.reason, /写操作/);
|
||||
}
|
||||
});
|
||||
|
||||
test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', () => {
|
||||
const r = AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /匿名/);
|
||||
});
|
||||
|
||||
test('shouldCapture: 登录/登出端点始终记录(含匿名登录尝试)', () => {
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/login', authenticated: false }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).captured, true);
|
||||
});
|
||||
|
||||
test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
|
||||
const r = AuditCore.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /捕获范围/);
|
||||
});
|
||||
|
||||
test('shouldCapture: 路径匹配 /apis/ 前缀但匿名时,匿名规则优先于方法规则(与 D1 描述一致)', () => {
|
||||
// GET + 匿名:期望原因是"匿名",而非"读操作"
|
||||
const r = AuditCore.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /匿名/);
|
||||
});
|
||||
|
||||
// ---------------- resolveResource(5.2 资源解析) ----------------
|
||||
test('resolveResource: 单资源路径 → plural + name', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz'),
|
||||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: 集合路径 → 仅 plural', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
|
||||
{ resourceType: 'posts', resourceName: '' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: 更深层子资源取前两段,完整路径由 path 兜底', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
|
||||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: /login、/logout → auth', () => {
|
||||
assert.deepEqual(AuditCore.resolveResource('/login'), { resourceType: 'auth', resourceName: '' });
|
||||
assert.deepEqual(AuditCore.resolveResource('/logout'), { resourceType: 'auth', resourceName: '' });
|
||||
});
|
||||
|
||||
test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
|
||||
assert.equal(AuditCore.resolveResource('/console').resourceType, 'other');
|
||||
assert.equal(AuditCore.resolveResource('/apis/only-group').resourceType, 'other');
|
||||
});
|
||||
|
||||
// ---------------- isSuccess / applyFilters(4.2 筛选) ----------------
|
||||
const NOW = new Date('2026-11-21T12:00:00Z').getTime();
|
||||
|
||||
function fixture() {
|
||||
return [
|
||||
{ id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200 },
|
||||
{ id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500 },
|
||||
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: '', statusCode: 401 },
|
||||
{ id: 'a4', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 200 }
|
||||
];
|
||||
}
|
||||
|
||||
test('applyFilters: 按操作者筛选', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { operator: 'guichumo', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按资源类型筛选', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按动作筛选(方法名大小写不敏感)', () => {
|
||||
const post = AuditCore.applyFilters(fixture(), { method: 'POST', now: NOW });
|
||||
assert.deepEqual(post.map(l => l.id), ['a2', 'a3']);
|
||||
const put = AuditCore.applyFilters(fixture(), { method: 'put', now: NOW });
|
||||
assert.deepEqual(put.map(l => l.id), ['a1', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 动作 + 结果组合', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { method: 'POST', result: 'failure', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a2', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按结果筛选(成功/失败)', () => {
|
||||
const ok = AuditCore.applyFilters(fixture(), { result: 'success', now: NOW });
|
||||
assert.deepEqual(ok.map(l => l.id), ['a1', 'a4']);
|
||||
const bad = AuditCore.applyFilters(fixture(), { result: 'failure', now: NOW });
|
||||
assert.deepEqual(bad.map(l => l.id), ['a2', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 时间范围(24h 只含今天、30d 含上周)', () => {
|
||||
const day = AuditCore.applyFilters(fixture(), { timeRange: '24h', now: NOW });
|
||||
assert.deepEqual(day.map(l => l.id), ['a1', 'a2']);
|
||||
const month = AuditCore.applyFilters(fixture(), { timeRange: '30d', now: NOW });
|
||||
assert.deepEqual(month.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 关键字匹配资源名称与路径', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { keyword: 'hello', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
|
||||
const byPath = AuditCore.applyFilters(fixture(), { keyword: 'configmaps', now: NOW });
|
||||
assert.deepEqual(byPath.map(l => l.id), ['a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 组合条件', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', result: 'failure', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a2']);
|
||||
});
|
||||
|
||||
test('applyFilters: 结果按时间倒序排列', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 不修改入参数组', () => {
|
||||
const logs = fixture();
|
||||
AuditCore.applyFilters(logs, { now: NOW });
|
||||
assert.equal(logs.length, 4);
|
||||
});
|
||||
|
||||
// ---------------- paginate ----------------
|
||||
test('paginate: 基础分页与元信息', () => {
|
||||
const items = Array.from({ length: 25 }, (_, i) => i);
|
||||
const p = AuditCore.paginate(items, 2, 10);
|
||||
assert.equal(p.total, 25);
|
||||
assert.equal(p.pages, 3);
|
||||
assert.equal(p.page, 2);
|
||||
assert.deepEqual(p.items, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
|
||||
});
|
||||
|
||||
test('paginate: 页码越界自动收敛', () => {
|
||||
const items = Array.from({ length: 15 }, (_, i) => i);
|
||||
assert.equal(AuditCore.paginate(items, 99, 10).page, 2);
|
||||
assert.equal(AuditCore.paginate(items, 0, 10).page, 1);
|
||||
});
|
||||
|
||||
test('paginate: 空结果时仍返回 1 页', () => {
|
||||
const p = AuditCore.paginate([], 1, 10);
|
||||
assert.deepEqual({ total: p.total, pages: p.pages, items: p.items }, { total: 0, pages: 1, items: [] });
|
||||
});
|
||||
|
||||
// ---------------- countExpired(D5 保留期清理) ----------------
|
||||
test('countExpired: 统计超过保留期的记录', () => {
|
||||
const logs = fixture(); // NOW 为 2026-11-21,a4 是 11-10
|
||||
assert.equal(AuditCore.countExpired(logs, 5, NOW), 1); // a4 过期
|
||||
assert.equal(AuditCore.countExpired(logs, 90, NOW), 0); // 全部在保留期内
|
||||
});
|
||||
|
||||
// ---------------- MockData 模拟数据 ----------------
|
||||
const FIXED_NOW = new Date('2026-11-21T12:00:00Z').getTime();
|
||||
const REQUIRED_FIELDS = ['id', 'timestamp', 'username', 'method', 'path', 'resourceType', 'resourceName', 'statusCode', 'remoteIp', 'userAgent'];
|
||||
|
||||
test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => {
|
||||
const a = MockData.generateLogs(FIXED_NOW);
|
||||
const b = MockData.generateLogs(FIXED_NOW);
|
||||
assert.equal(JSON.stringify(a), JSON.stringify(b));
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 记录数量充足且字段完整', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
assert.ok(logs.length >= 120, '应有 120+ 条记录,实际 ' + logs.length);
|
||||
for (const log of logs) {
|
||||
for (const field of REQUIRED_FIELDS) {
|
||||
assert.ok(log[field] !== undefined && log[field] !== null, `记录 ${log.id} 缺少字段 ${field}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 按时间倒序且 id 唯一', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const ids = new Set(logs.map(l => l.id));
|
||||
assert.equal(ids.size, logs.length, 'id 应唯一');
|
||||
for (let i = 1; i < logs.length; i++) {
|
||||
const prev = new Date(logs[i - 1].timestamp).getTime();
|
||||
const curr = new Date(logs[i].timestamp).getTime();
|
||||
assert.ok(prev >= curr, `第 ${i} 条时间应不晚于下一条`);
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 包含登录审计与"未知用户"记录(产品设计 4.1)', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
assert.ok(logs.some(l => l.resourceType === 'auth' && l.statusCode === 200), '应有登录成功记录');
|
||||
assert.ok(logs.some(l => l.resourceType === 'auth' && l.username === '未知用户'), '应有登录失败记"未知用户"的记录');
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 资源解析结果与 resolveResource 规则一致(模拟真实管线)', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
for (const log of logs) {
|
||||
const expect = AuditCore.resolveResource(log.path);
|
||||
assert.equal(log.resourceType, expect.resourceType, log.path);
|
||||
assert.equal(log.resourceName, expect.resourceName, log.path);
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 覆盖全部捕获方法与失败场景', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const methods = new Set(logs.map(l => l.method));
|
||||
for (const m of ['POST', 'PUT', 'DELETE']) {
|
||||
assert.ok(methods.has(m), '应包含 ' + m + ' 操作');
|
||||
}
|
||||
assert.ok(logs.some(l => !AuditCore.isSuccess(l.statusCode)), '应包含失败操作记录');
|
||||
assert.ok(logs.some(l => l.statusCode === 403), '应包含越权 403 记录');
|
||||
assert.ok(logs.some(l => l.statusCode === 500), '应包含服务端 500 记录');
|
||||
});
|
||||
Reference in New Issue
Block a user