feat(demo): 按插件当前实现重写演示页
- 列表/筛选对齐真实 Console:八维筛选、语义动作中文描述、登录失败结果语义 - 详情抽屉展示字段级 diff(脱敏/截断/封顶)与 AuditLog Extension 原始 JSON - 新增行内「历史」快捷、按筛选条件导出 UTF-8 BOM CSV - 设置页覆盖审计开关/字段变更/系统变更/保留期与登录失败告警(含测试与模拟触发) - 模拟器支持 HTTP 捕获管线与系统内部变更两条通道 - 核心纯函数重写并扩充至 56 个单元用例
This commit is contained in:
+605
-139
@@ -2,199 +2,616 @@
|
||||
* 操作审计 Demo · 核心逻辑单元测试
|
||||
*
|
||||
* 运行:node --test demo/test/audit-core.test.mjs
|
||||
* 覆盖对象(与技术方案第 7 节测试策略对应):
|
||||
* - shouldCapture 捕获规则(D1)
|
||||
* - resolveResource 资源解析(5.2)
|
||||
* - applyFilters 筛选(产品设计 4.2)
|
||||
* - paginate 分页
|
||||
* - countExpired 保留期清理(D5)
|
||||
* - MockData 模拟数据生成器(确定性、字段完整性)
|
||||
* 覆盖对象(与插件当前实现一一对应):
|
||||
* - shouldCapture 捕获规则(CaptureRule / 认证端点链首捕获)
|
||||
* - resolveResource 资源解析(ResourceResolver)
|
||||
* - deriveAction 语义动作标注 + describeOperation 中文描述
|
||||
* - classifyLogin 登录结果判定(LoginOutcome:302 重定向目标判定)
|
||||
* - diffObjects 字段级变更 diff(PUT/PATCH/POST/DELETE、脱敏、截断、封顶)
|
||||
* - applyFilters 八维筛选(含登录失败结果语义)
|
||||
* - toCsv CSV 导出(BOM/CRLF/转义/公式注入防护)
|
||||
* - 告警窗口 登录失败告警(阈值、告警后重开、成功清零)
|
||||
* - 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 C = 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);
|
||||
// ---------------- shouldCapture(捕获规则) ----------------
|
||||
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录(http 通道)', () => {
|
||||
for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) {
|
||||
const r = C.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
|
||||
assert.equal(r.captured, true, method);
|
||||
assert.equal(r.channel, 'http');
|
||||
assert.match(r.reason, /写操作/);
|
||||
}
|
||||
});
|
||||
|
||||
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 + ' 不应被记录');
|
||||
const r = C.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 });
|
||||
const r = C.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: 认证端点始终记录(含查询串与匿名登录尝试)', () => {
|
||||
assert.deepEqual(
|
||||
C.shouldCapture({ method: 'POST', path: '/login', authenticated: false }),
|
||||
{
|
||||
captured: true,
|
||||
channel: 'auth',
|
||||
reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)'
|
||||
}
|
||||
);
|
||||
assert.equal(C.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).channel, 'auth');
|
||||
assert.equal(C.shouldCapture({ method: 'GET', path: '/login?error=invalid-credential', authenticated: false }).captured, true);
|
||||
});
|
||||
|
||||
test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
|
||||
const r = AuditCore.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
|
||||
const r = C.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 });
|
||||
test('shouldCapture: 匿名规则优先于读操作规则(与后端一致)', () => {
|
||||
const r = C.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', () => {
|
||||
// ---------------- resolveResource(资源解析) ----------------
|
||||
test('resolveResource: 单资源 / 集合 / 深层子资源', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz'),
|
||||
C.resolveResource('/apis/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: '' }
|
||||
C.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
|
||||
{ resourceType: 'posts', resourceName: null }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: 更深层子资源取前两段,完整路径由 path 兜底', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
|
||||
C.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
|
||||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||||
);
|
||||
assert.deepEqual(
|
||||
C.resolveResource('/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade'),
|
||||
{ resourceType: 'plugins', resourceName: 'plugin-search-widget' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: /login、/logout → auth', () => {
|
||||
assert.deepEqual(AuditCore.resolveResource('/login'), { resourceType: 'auth', resourceName: '' });
|
||||
assert.deepEqual(AuditCore.resolveResource('/logout'), { resourceType: 'auth', resourceName: '' });
|
||||
test('resolveResource: 查询串不影响解析(/login?error=... → auth)', () => {
|
||||
assert.deepEqual(
|
||||
C.resolveResource('/login?error=invalid-credential&method=form'),
|
||||
{ resourceType: 'auth', resourceName: null }
|
||||
);
|
||||
assert.deepEqual(C.resolveResource('/logout'), { resourceType: 'auth', resourceName: null });
|
||||
});
|
||||
|
||||
test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
|
||||
assert.equal(AuditCore.resolveResource('/console').resourceType, 'other');
|
||||
assert.equal(AuditCore.resolveResource('/apis/only-group').resourceType, 'other');
|
||||
assert.equal(C.resolveResource('/console').resourceType, 'other');
|
||||
assert.equal(C.resolveResource('/apis/only-group').resourceType, 'other');
|
||||
assert.equal(C.resolveResource('').resourceType, 'other');
|
||||
});
|
||||
|
||||
// ---------------- isSuccess / applyFilters(4.2 筛选) ----------------
|
||||
// ---------------- deriveAction / describeOperation ----------------
|
||||
test('deriveAction: 登录/登出/失败回显', () => {
|
||||
assert.equal(C.deriveAction('POST', 'auth', '/login'), 'login');
|
||||
assert.equal(C.deriveAction('GET', 'auth', '/login?error=invalid-credential'), 'login-failure');
|
||||
assert.equal(C.deriveAction('POST', 'auth', '/logout'), 'logout');
|
||||
assert.equal(C.deriveAction('POST', 'auth', '/login?continue=/uc'), 'login');
|
||||
});
|
||||
|
||||
test('deriveAction: 子动作段优先于 HTTP 方法', () => {
|
||||
assert.equal(C.deriveAction('PUT', 'posts', '/apis/api.content.halo.run/v1alpha1/posts/x/publish'), 'publish');
|
||||
assert.equal(C.deriveAction('PUT', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/restore'), 'restore');
|
||||
assert.equal(C.deriveAction('DELETE', 'comments', '/apis/content.halo.run/v1alpha1/comments/x/recycle'), 'recycle');
|
||||
assert.equal(C.deriveAction('POST', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/activation'), 'enable');
|
||||
assert.equal(C.deriveAction('PUT', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/upgrade'), 'upgrade');
|
||||
assert.equal(C.deriveAction('DELETE', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/uninstall'), 'uninstall');
|
||||
assert.equal(C.deriveAction('POST', 'users', '/apis/api.console.halo.run/v1alpha1/users/x/resetpassword'), 'resetpassword');
|
||||
});
|
||||
|
||||
test('deriveAction: 未识别子动作回退 method 映射,未知方法返回 null', () => {
|
||||
assert.equal(C.deriveAction('POST', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/unknown'), 'create');
|
||||
assert.equal(C.deriveAction('GET', 'posts', '/apis/content.halo.run/v1alpha1/posts'), 'view');
|
||||
assert.equal(C.deriveAction('TRACE', 'posts', '/apis/content.halo.run/v1alpha1/posts'), null);
|
||||
});
|
||||
|
||||
test('describeOperation: 语义动作 → 中文短语(列表/详情/导出共用)', () => {
|
||||
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login' }), '登录');
|
||||
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure' }), '登录失败');
|
||||
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish', action: 'publish' }), '发布文章');
|
||||
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'plugins', path: '/apis/plugin.halo.run/v1alpha1/plugins/x/activation', action: 'enable' }), '启用插件');
|
||||
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'themes', path: '/apis/theme.halo.run/v1alpha1/themes/x/activation', action: 'enable' }), '启用主题');
|
||||
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'users', path: '/apis/v1alpha1/users/x/password', action: 'password' }), '修改密码');
|
||||
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'comments', path: '/apis/x/v1alpha1/comments/x/reply', action: 'reply' }), '回复评论');
|
||||
});
|
||||
|
||||
test('describeOperation: 历史记录无 action 时现场推导;未识别回退 method 动词', () => {
|
||||
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/content.halo.run/v1alpha1/posts/x' }), '修改文章');
|
||||
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'unknowns', path: '/apis/x/v1alpha1/unknowns' }), '新建unknowns');
|
||||
});
|
||||
|
||||
// ---------------- classifyLogin(登录结果判定) ----------------
|
||||
test('classifyLogin: POST /login 的 2xx/302/401 判定', () => {
|
||||
assert.deepEqual(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 200 }), { attempt: true, failure: false, echo: false });
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/uc' }).failure, false);
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/challenges/two-factor/totp' }).failure, false);
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error=invalid-credential&method=form' }).failure, true);
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error&method=form' }).failure, true);
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 401 }).failure, true);
|
||||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: null }).failure, true);
|
||||
});
|
||||
|
||||
test('classifyLogin: 失败回显页(GET /login?error=...,HTTP 200)判为失败', () => {
|
||||
const echo = C.classifyLogin({ method: 'GET', path: '/login?error=invalid-credential&method=form', statusCode: 200 });
|
||||
assert.deepEqual(echo, { attempt: false, failure: true, echo: true });
|
||||
const page = C.classifyLogin({ method: 'GET', path: '/login', statusCode: 200 });
|
||||
assert.deepEqual(page, { attempt: false, failure: false, echo: false });
|
||||
});
|
||||
|
||||
// ---------------- 结果徽标 / 登录失败标注 ----------------
|
||||
test('resultBadge: 登录失败即使 200/302 也显示「失败」', () => {
|
||||
assert.deepEqual(
|
||||
C.resultBadge({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure', statusCode: 200 }),
|
||||
{ text: '失败', class: 'status-fail' }
|
||||
);
|
||||
assert.deepEqual(
|
||||
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }),
|
||||
{ text: '302', class: 'status-ok' }
|
||||
);
|
||||
assert.deepEqual(
|
||||
C.resultBadge({ method: 'DELETE', resourceType: 'posts', path: '/apis/x/v1alpha1/posts/x', action: 'delete', statusCode: 403 }),
|
||||
{ text: '403', class: 'status-fail' }
|
||||
);
|
||||
});
|
||||
|
||||
test('isLoginFailure / isSuccessRecord: 兼容历史记录(无 action 时按路径推导)', () => {
|
||||
assert.equal(C.isLoginFailure({ method: 'GET', resourceType: 'auth', path: '/login?error=x', statusCode: 200 }), true);
|
||||
assert.equal(C.isLoginFailure({ method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302 }), false);
|
||||
assert.equal(C.isSuccessRecord({ action: 'login-failure', statusCode: 200 }), false);
|
||||
assert.equal(C.isSuccessRecord({ action: 'login', statusCode: 302 }), true);
|
||||
});
|
||||
|
||||
test('displayUsername: unknown → 未知用户,system → 系统', () => {
|
||||
assert.equal(C.displayUsername('unknown'), '未知用户');
|
||||
assert.equal(C.displayUsername('system'), '系统');
|
||||
assert.equal(C.displayUsername(''), '未知用户');
|
||||
assert.equal(C.displayUsername('guichumo'), 'guichumo');
|
||||
});
|
||||
|
||||
// ---------------- diffObjects(字段级变更) ----------------
|
||||
test('diffObjects: POST 全量新增,跳过 apiVersion/kind/status,metadata 仅保留可写键', () => {
|
||||
const changes = C.diffObjects('POST', null, {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Post',
|
||||
metadata: { name: 'hello', version: 3, labels: { a: 'b' }, annotations: { c: 'd' } },
|
||||
spec: { title: '标题', publish: false },
|
||||
status: { phase: 'DRAFT' }
|
||||
});
|
||||
const fields = changes.map(c => c.field);
|
||||
assert.ok(fields.includes('metadata.name'));
|
||||
assert.ok(fields.includes('metadata.labels.a'));
|
||||
assert.ok(!fields.includes('apiVersion'));
|
||||
assert.ok(!fields.includes('kind'));
|
||||
assert.ok(!fields.includes('status.phase'));
|
||||
assert.ok(!fields.some(f => f.includes('metadata.version')));
|
||||
assert.ok(changes.every(c => c.changeType === 'ADDED'));
|
||||
});
|
||||
|
||||
test('diffObjects: PUT 计算新增/修改/删除', () => {
|
||||
const changes = C.diffObjects('PUT',
|
||||
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png', pinned: false } },
|
||||
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '新', pinned: false, summary: '新增' } }
|
||||
);
|
||||
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
|
||||
assert.equal(byField['spec.title'].changeType, 'UPDATED');
|
||||
assert.equal(byField['spec.title'].oldValue, '旧');
|
||||
assert.equal(byField['spec.title'].newValue, '新');
|
||||
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
|
||||
assert.equal(byField['spec.summary'].changeType, 'ADDED');
|
||||
assert.equal(byField['spec.summary'].oldValue, null);
|
||||
});
|
||||
|
||||
test('diffObjects: DELETE 全量移除', () => {
|
||||
const changes = C.diffObjects('DELETE', {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Post',
|
||||
metadata: { name: 'weekly' },
|
||||
spec: { title: '每周摘要' },
|
||||
status: { phase: 'PUBLISHED' }
|
||||
}, null);
|
||||
assert.ok(changes.length > 0);
|
||||
assert.ok(changes.every(c => c.changeType === 'REMOVED'));
|
||||
assert.ok(changes.some(c => c.field === 'spec.title' && c.oldValue === '每周摘要'));
|
||||
assert.ok(!changes.some(c => c.field.startsWith('status')));
|
||||
});
|
||||
|
||||
test('diffObjects: PATCH Merge Patch 仅比较 body 中字段,显式 null 视为删除', () => {
|
||||
const changes = C.diffObjects('PATCH',
|
||||
{ metadata: { name: 'x' }, spec: { title: '旧', summary: '保留', cover: 'a.png' } },
|
||||
{ spec: { title: '新', cover: null } }
|
||||
);
|
||||
const fields = changes.map(c => c.field);
|
||||
assert.deepEqual(fields, ['spec.title', 'spec.cover']);
|
||||
const cover = changes.find(c => c.field === 'spec.cover');
|
||||
assert.equal(cover.changeType, 'REMOVED');
|
||||
assert.ok(!fields.includes('spec.summary'), 'body 未携带的字段视为未变更');
|
||||
});
|
||||
|
||||
test('diffObjects: PATCH JSON Patch(RFC 6902)', () => {
|
||||
const changes = C.diffObjects('PATCH',
|
||||
{ metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png' } },
|
||||
[
|
||||
{ op: 'replace', path: '/spec/title', value: '新' },
|
||||
{ op: 'remove', path: '/spec/cover' },
|
||||
{ op: 'add', path: '/spec/summary', value: '摘要' }
|
||||
]
|
||||
);
|
||||
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
|
||||
assert.equal(byField['spec.title'].changeType, 'UPDATED');
|
||||
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
|
||||
assert.equal(byField['spec.summary'].changeType, 'ADDED');
|
||||
});
|
||||
|
||||
test('diffObjects: 敏感字段脱敏(password / token / secret / credential)', () => {
|
||||
const changes = C.diffObjects('POST', null, {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'User',
|
||||
metadata: { name: 'alice' },
|
||||
spec: { displayName: 'Alice', password: 'plain-text-value' },
|
||||
annotations: { 'x-token': 'token-value' }
|
||||
});
|
||||
const password = changes.find(c => c.field === 'spec.password');
|
||||
const displayName = changes.find(c => c.field === 'spec.displayName');
|
||||
assert.equal(password.newValue, '******');
|
||||
assert.equal(displayName.newValue, 'Alice');
|
||||
|
||||
const updated = C.diffObjects('PUT',
|
||||
{ spec: { password: 'old-value' } },
|
||||
{ spec: { password: 'new-value' } }
|
||||
);
|
||||
assert.equal(updated[0].oldValue, '******');
|
||||
assert.equal(updated[0].newValue, '******');
|
||||
assert.equal(C.isSensitiveField('metadata.annotations.x-credential'), true);
|
||||
assert.equal(C.isSensitiveField('spec.title'), false);
|
||||
});
|
||||
|
||||
test('diffObjects: 超长值截断、变更条数封顶 30 + 汇总条', () => {
|
||||
const long = 'x'.repeat(260);
|
||||
const changes = C.diffObjects('PUT', { spec: { text: 'old' } }, { spec: { text: long } });
|
||||
assert.ok(changes[0].newValue.endsWith('…(截断)'));
|
||||
assert.ok(changes[0].newValue.length <= 210);
|
||||
|
||||
const before = { spec: {} };
|
||||
const after = { spec: {} };
|
||||
for (let i = 0; i < 40; i++) {
|
||||
before.spec['k' + i] = 'a';
|
||||
after.spec['k' + i] = 'b';
|
||||
}
|
||||
const capped = C.diffObjects('PUT', before, after);
|
||||
assert.equal(capped.length, 31);
|
||||
assert.equal(capped[30].field, '…');
|
||||
assert.match(capped[30].newValue, /仅记录前 30 处(共 40 处)/);
|
||||
});
|
||||
|
||||
test('diffObjects: 无变更 / 无法计算返回 null', () => {
|
||||
assert.equal(C.diffObjects('PUT', { spec: { a: 1 } }, { spec: { a: 1 } }), null);
|
||||
assert.equal(C.diffObjects('POST', null, null), null);
|
||||
assert.equal(C.diffObjects('PUT', null, { spec: {} }), null);
|
||||
assert.equal(C.diffObjects('GET', { a: 1 }, { a: 2 }), null);
|
||||
});
|
||||
|
||||
test('formatChanges: 紧凑中文摘要供 CSV「变更」列使用', () => {
|
||||
const text = C.formatChanges([
|
||||
{ field: 'spec.title', changeType: 'UPDATED', oldValue: '旧', newValue: '新' },
|
||||
{ field: 'spec.cover', changeType: 'ADDED', oldValue: null, newValue: 'a.png' },
|
||||
{ field: 'spec.slug', changeType: 'REMOVED', oldValue: 'old', newValue: null }
|
||||
]);
|
||||
assert.equal(text, '修改 spec.title:旧 → 新;新增 spec.cover:a.png;删除 spec.slug:old');
|
||||
assert.equal(C.formatChanges(null), '');
|
||||
assert.equal(C.changeTypeLabel('ADDED'), '新增');
|
||||
assert.equal(C.changeValueDisplay(null), '∅');
|
||||
});
|
||||
|
||||
// ---------------- buildRecord / buildSystemRecord ----------------
|
||||
test('buildRecord: HTTP 写操作推导资源、语义动作与操作者', () => {
|
||||
const record = C.buildRecord({
|
||||
method: 'put',
|
||||
path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish',
|
||||
username: 'editor.zhang',
|
||||
statusCode: 200,
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(record.username, 'editor.zhang');
|
||||
assert.equal(record.method, 'PUT');
|
||||
assert.equal(record.action, 'publish');
|
||||
assert.equal(record.resourceType, 'posts');
|
||||
assert.equal(record.resourceName, 'x');
|
||||
assert.equal(C.describeOperation(record), '发布文章');
|
||||
assert.equal(record.changes, null, '未提供请求体时不计算 diff');
|
||||
});
|
||||
|
||||
test('buildRecord: 登录请求操作者记「未知用户」,失败标注 login-failure', () => {
|
||||
const failure = C.buildRecord({
|
||||
method: 'POST',
|
||||
path: '/login',
|
||||
username: 'guichumo',
|
||||
statusCode: 302,
|
||||
location: '/login?error=invalid-credential&method=form',
|
||||
attemptedUsername: 'admin',
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(failure.username, 'unknown');
|
||||
assert.equal(failure.attemptedUsername, 'admin');
|
||||
assert.equal(failure.action, 'login-failure');
|
||||
assert.equal(C.resultBadge(failure).text, '失败');
|
||||
|
||||
const success = C.buildRecord({
|
||||
method: 'POST',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
location: '/uc',
|
||||
attemptedUsername: 'guichumo',
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(success.action, 'login');
|
||||
assert.equal(C.resultBadge(success).text, '302');
|
||||
});
|
||||
|
||||
test('buildRecord: 仅 2xx 且 recordChanges 开启时计算 diff', () => {
|
||||
const body = { spec: { title: '新' } };
|
||||
const previous = { spec: { title: '旧' } };
|
||||
const ok = C.buildRecord({
|
||||
method: 'PUT',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/x',
|
||||
username: 'guichumo',
|
||||
statusCode: 200,
|
||||
previous,
|
||||
body,
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(ok.changes.length, 1);
|
||||
|
||||
const failed = C.buildRecord({
|
||||
method: 'PUT',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/x',
|
||||
username: 'guichumo',
|
||||
statusCode: 403,
|
||||
previous,
|
||||
body,
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(failed.changes, null);
|
||||
|
||||
const disabled = C.buildRecord({
|
||||
method: 'PUT',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/x',
|
||||
username: 'guichumo',
|
||||
statusCode: 200,
|
||||
previous,
|
||||
body,
|
||||
recordChanges: false,
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(disabled.changes, null);
|
||||
});
|
||||
|
||||
test('buildSystemRecord: 执行者 system、无 IP/UA、状态恒 200', () => {
|
||||
const record = C.buildSystemRecord({
|
||||
method: 'PUT',
|
||||
resourceType: 'posts',
|
||||
resourceName: 'weekly',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/weekly',
|
||||
changes: [{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' }],
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
assert.equal(record.username, 'system');
|
||||
assert.equal(C.displayUsername(record.username), '系统');
|
||||
assert.equal(record.statusCode, 200);
|
||||
assert.equal(record.remoteIp, null);
|
||||
assert.equal(record.userAgent, null);
|
||||
assert.equal(record.action, 'update');
|
||||
assert.equal(C.describeOperation(record), '修改文章');
|
||||
assert.equal(record.changes.length, 1);
|
||||
});
|
||||
|
||||
test('toWire: 扁平记录 → AuditLog Extension JSON', () => {
|
||||
const record = C.buildRecord({
|
||||
method: 'POST',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts',
|
||||
username: 'guichumo',
|
||||
statusCode: 201,
|
||||
body: { spec: { title: '新文章' } },
|
||||
timestamp: '2026-11-21T10:00:00Z'
|
||||
});
|
||||
record.id = 'auditlog-0001';
|
||||
const wire = C.toWire(record);
|
||||
assert.equal(wire.apiVersion, 'audit.guichumo.com/v1alpha1');
|
||||
assert.equal(wire.kind, 'AuditLog');
|
||||
assert.equal(wire.metadata.name, 'auditlog-0001');
|
||||
assert.equal(wire.metadata.creationTimestamp, '2026-11-21T10:00:00Z');
|
||||
assert.equal(wire.spec.method, 'POST');
|
||||
assert.equal(wire.spec.action, 'create');
|
||||
assert.ok(Array.isArray(wire.spec.changes));
|
||||
});
|
||||
|
||||
// ---------------- applyFilters(八维筛选) ----------------
|
||||
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 }
|
||||
{ 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, action: 'update' },
|
||||
{ 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, action: 'publish' },
|
||||
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure' },
|
||||
{ id: 'a4', timestamp: '2026-11-21T11:30:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: null, statusCode: 302, action: 'login' },
|
||||
{ id: 'a5', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 403, action: 'update' }
|
||||
];
|
||||
}
|
||||
|
||||
test('applyFilters: 按操作者筛选', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { operator: 'guichumo', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a3']);
|
||||
test('applyFilters: 操作者 / 资源类型 / 动作 / 语义动作', () => {
|
||||
assert.deepEqual(C.applyFilters(fixture(), { operator: 'guichumo' }).map(l => l.id), ['a4', 'a1']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { resourceType: 'posts' }).map(l => l.id), ['a1', 'a2']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { method: 'post' }).map(l => l.id), ['a4', 'a2']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { action: 'login-failure' }).map(l => l.id), ['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: 结果语义(登录失败 200 计失败;登录成功 302 计成功)', () => {
|
||||
const success = C.applyFilters(fixture(), { result: 'success' }).map(l => l.id);
|
||||
assert.deepEqual(success, ['a4', 'a1']);
|
||||
const failure = C.applyFilters(fixture(), { result: 'failure' }).map(l => l.id);
|
||||
assert.deepEqual(failure, ['a2', 'a3', 'a5']);
|
||||
});
|
||||
|
||||
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']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'hello' }).map(l => l.id), ['a1', 'a2']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'configmaps' }).map(l => l.id), ['a5']);
|
||||
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'LOGIN' }).map(l => l.id), ['a4', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 组合条件', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', result: 'failure', now: NOW });
|
||||
test('applyFilters: 起止时间闭区间', () => {
|
||||
const out = C.applyFilters(fixture(), {
|
||||
startTime: '2026-11-21T10:00:00Z',
|
||||
endTime: '2026-11-21T11:30:00Z'
|
||||
});
|
||||
assert.deepEqual(out.map(l => l.id), ['a4', 'a1']);
|
||||
});
|
||||
|
||||
test('applyFilters: 组合条件、时间倒序、不修改入参', () => {
|
||||
const out = C.applyFilters(fixture(), { resourceType: 'posts', result: 'failure' });
|
||||
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);
|
||||
C.applyFilters(logs, {});
|
||||
assert.equal(logs.length, 5);
|
||||
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a5']);
|
||||
});
|
||||
|
||||
// ---------------- paginate ----------------
|
||||
test('paginate: 基础分页与元信息', () => {
|
||||
// ---------------- paginate / countExpired ----------------
|
||||
test('paginate: 分页与越界收敛', () => {
|
||||
const items = Array.from({ length: 25 }, (_, i) => i);
|
||||
const p = AuditCore.paginate(items, 2, 10);
|
||||
const p = C.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]);
|
||||
assert.equal(C.paginate(items, 99, 10).page, 3);
|
||||
assert.equal(C.paginate(items, 0, 10).page, 1);
|
||||
assert.deepEqual(C.paginate([], 1, 20), { items: [], total: 0, pages: 1, page: 1 });
|
||||
});
|
||||
|
||||
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); // 全部在保留期内
|
||||
assert.equal(C.countExpired(fixture(), 5, NOW), 1);
|
||||
assert.equal(C.countExpired(fixture(), 90, NOW), 0);
|
||||
});
|
||||
|
||||
// ---------------- CSV 导出 ----------------
|
||||
test('toCsv: UTF-8 BOM + CRLF + 表头列顺序', () => {
|
||||
const csv = C.toCsv([fixture()[0]]);
|
||||
assert.ok(csv.startsWith('\uFEFF操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent\r\n'));
|
||||
assert.ok(csv.endsWith('\r\n'));
|
||||
});
|
||||
|
||||
test('toCsv: 记录按时间升序输出,结果/描述/变更列与界面一致', () => {
|
||||
const logs = [
|
||||
{ id: 'b', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/x/v1alpha1/posts/b', resourceType: 'posts', resourceName: 'b', statusCode: 200, action: 'publish', attemptedUsername: null, remoteIp: '1.1.1.1', userAgent: 'UA' },
|
||||
{ id: 'a', timestamp: '2026-11-20T10:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure', attemptedUsername: 'admin', remoteIp: '2.2.2.2', userAgent: 'bot' }
|
||||
];
|
||||
const lines = C.toCsv(logs).split('\r\n');
|
||||
assert.equal(lines.length, 4, '表头 + 2 行 + 末尾空行');
|
||||
assert.match(lines[1], /^2026-11-20 18:00:00,未知用户,admin,GET,auth,,/);
|
||||
assert.match(lines[1], /登录失败,.*失败,200,2\.2\.2\.2,bot$/);
|
||||
assert.match(lines[2], /发布文章,.*成功,200,1\.1\.1\.1,UA$/);
|
||||
});
|
||||
|
||||
test('toCsv: 引号/逗号/换行转义与公式注入防护', () => {
|
||||
assert.equal(C.csvEscape('a,b'), '"a,b"');
|
||||
assert.equal(C.csvEscape('say "hi"'), '"say ""hi"""');
|
||||
assert.equal(C.csvEscape('line1\nline2'), '"line1\nline2"');
|
||||
assert.equal(C.csvEscape('=SUM(A1)'), "'=SUM(A1)");
|
||||
assert.equal(C.csvEscape('+1'), "'+1");
|
||||
assert.equal(C.csvEscape('@cmd'), "'@cmd");
|
||||
assert.equal(C.csvEscape(null), '');
|
||||
});
|
||||
|
||||
// ---------------- 登录失败告警窗口 ----------------
|
||||
test('createLoginFailureTracker: 未开启时只维护清零语义,不产生负载', () => {
|
||||
const tracker = C.createLoginFailureTracker({ enabled: false, thresholdCount: 2, windowMinutes: 5 });
|
||||
assert.equal(tracker.record({ success: false, time: NOW }), null);
|
||||
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
|
||||
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
|
||||
});
|
||||
|
||||
test('createLoginFailureTracker: 达到阈值触发一次告警,之后窗口重开', () => {
|
||||
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
|
||||
assert.equal(tracker.record({ success: false, time: NOW, remoteIp: '1.2.3.4', attemptedUsername: 'admin' }), null);
|
||||
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
|
||||
const alert = tracker.record({ success: false, time: NOW + 2000, remoteIp: '1.2.3.4', userAgent: 'bot', attemptedUsername: 'admin' });
|
||||
assert.ok(alert);
|
||||
assert.equal(alert.failures, 3);
|
||||
assert.equal(alert.windowMinutes, 5);
|
||||
assert.equal(alert.remoteIp, '1.2.3.4');
|
||||
assert.equal(alert.attemptedUsername, 'admin');
|
||||
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: NOW + 2000 });
|
||||
// 告警后需重新累计到阈值
|
||||
assert.equal(tracker.record({ success: false, time: NOW + 3000 }), null);
|
||||
});
|
||||
|
||||
test('createLoginFailureTracker: 登录成功清零、窗口过期重新计数', () => {
|
||||
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
|
||||
tracker.record({ success: false, time: NOW });
|
||||
tracker.record({ success: false, time: NOW + 1000 });
|
||||
assert.equal(tracker.record({ success: true, time: NOW + 2000 }), null);
|
||||
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
|
||||
tracker.record({ success: false, time: NOW + 3000 });
|
||||
tracker.record({ success: false, time: NOW + 4000 });
|
||||
assert.equal(tracker.record({ success: false, time: NOW + 5 * 60000 + 4000 }), null, '超过窗口后重新计数,不应触发');
|
||||
assert.equal(tracker.snapshot().count, 1);
|
||||
});
|
||||
|
||||
test('alertPayload: 通用 JSON 结构与测试消息', () => {
|
||||
const real = C.alertPayload({
|
||||
failures: 5,
|
||||
windowMinutes: 5,
|
||||
remoteIp: '1.2.3.4',
|
||||
userAgent: 'Mozilla/5.0',
|
||||
attemptedUsername: 'admin',
|
||||
timestamp: '2026-11-21T12:34:56Z'
|
||||
});
|
||||
assert.equal(real.type, 'login-failure');
|
||||
assert.match(real.title, /登录失败/);
|
||||
assert.match(real.content, /5 分钟内出现 5 次登录失败/);
|
||||
assert.match(real.content, /admin/);
|
||||
assert.deepEqual(real.data, {
|
||||
failures: 5,
|
||||
windowMinutes: 5,
|
||||
remoteIp: '1.2.3.4',
|
||||
userAgent: 'Mozilla/5.0',
|
||||
attemptedUsername: 'admin'
|
||||
});
|
||||
|
||||
const testPayload = C.alertPayload({ timestamp: '2026-11-21T12:34:56Z' }, 'test');
|
||||
assert.equal(testPayload.type, 'test');
|
||||
assert.match(testPayload.title, /测试/);
|
||||
assert.match(testPayload.content, /测试告警/);
|
||||
});
|
||||
|
||||
// ---------------- 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'];
|
||||
const REQUIRED_FIELDS = [
|
||||
'id', 'timestamp', 'username', 'attemptedUsername', 'method', 'action',
|
||||
'resourceType', 'resourceName', 'path', 'statusCode', 'remoteIp', 'userAgent', 'changes'
|
||||
];
|
||||
|
||||
test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => {
|
||||
const a = MockData.generateLogs(FIXED_NOW);
|
||||
@@ -207,44 +624,93 @@ test('MockData.generateLogs: 记录数量充足且字段完整', () => {
|
||||
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}`);
|
||||
assert.ok(Object.prototype.hasOwnProperty.call(log, field), `记录 ${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 应唯一');
|
||||
assert.equal(new Set(logs.map(l => l.id)).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} 条时间应不晚于下一条`);
|
||||
assert.ok(new Date(logs[i - 1].timestamp).getTime() >= new Date(logs[i].timestamp).getTime());
|
||||
}
|
||||
});
|
||||
|
||||
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 规则一致(模拟真实管线)', () => {
|
||||
test('MockData.generateLogs: 资源解析与语义动作与捕获管线一致', () => {
|
||||
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);
|
||||
const resolved = C.resolveResource(log.path);
|
||||
assert.equal(log.resourceType, resolved.resourceType, log.path);
|
||||
assert.equal(log.resourceName, resolved.resourceName, log.path);
|
||||
if (log.action) {
|
||||
assert.equal(typeof log.action, 'string');
|
||||
}
|
||||
if (log.changes) {
|
||||
for (const change of log.changes) {
|
||||
assert.ok(change.field, '变更条目应含 field');
|
||||
assert.ok(['ADDED', 'UPDATED', 'REMOVED'].includes(change.changeType));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 覆盖全部捕获方法与失败场景', () => {
|
||||
test('MockData.generateLogs: 覆盖登录失败(302 重定向与 GET 回显 200)', () => {
|
||||
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 => l.action === 'login-failure' && l.method === 'POST' && l.statusCode === 302));
|
||||
assert.ok(logs.some(l => l.action === 'login-failure' && l.method === 'GET' && l.statusCode === 200));
|
||||
assert.ok(logs.some(l => l.action === 'login' && l.method === 'POST' && l.statusCode === 302));
|
||||
assert.ok(logs.some(l => l.method === 'POST' && l.path === '/login' && l.username === 'unknown'));
|
||||
assert.ok(logs.some(l => l.attemptedUsername === 'admin'));
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 覆盖系统内部变更(执行者「系统」、无 IP/UA)', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const systemLogs = logs.filter(l => l.username === 'system');
|
||||
assert.ok(systemLogs.length >= 2);
|
||||
for (const log of systemLogs) {
|
||||
assert.equal(log.statusCode, 200);
|
||||
assert.equal(log.remoteIp, null);
|
||||
assert.equal(log.userAgent, null);
|
||||
assert.ok(['update', 'delete'].includes(log.action));
|
||||
assert.ok(log.changes && log.changes.length > 0);
|
||||
}
|
||||
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 记录');
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 故事线「hello-halo 谁改过」可回溯', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const helloEdits = logs.filter(l => l.resourceType === 'posts' && l.resourceName === 'hello-halo' && l.method === 'PUT');
|
||||
assert.ok(helloEdits.length >= 3);
|
||||
assert.ok(helloEdits.some(l => l.username === 'editor.zhang'));
|
||||
assert.ok(helloEdits.some(l => l.username === 'guichumo'));
|
||||
assert.ok(helloEdits.some(l => l.changes && l.changes.some(c => c.field === 'spec.title')));
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 覆盖插件生命周期、越权与误删', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const actions = new Set(logs.map(l => l.action));
|
||||
assert.ok(actions.has('upgrade'));
|
||||
assert.ok(actions.has('enable'));
|
||||
assert.ok(actions.has('uninstall'));
|
||||
assert.ok(logs.some(l => l.statusCode === 403));
|
||||
assert.ok(logs.some(l => l.statusCode === 404));
|
||||
assert.ok(logs.some(l => l.statusCode === 500));
|
||||
const deleted = logs.find(l => l.method === 'DELETE' && l.resourceName === 'weekly-2026-w45');
|
||||
assert.ok(deleted);
|
||||
assert.ok(deleted.changes && deleted.changes.length > 0, '误删文章应带字段快照');
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 字段变更覆盖新增/修改/删除且敏感字段已脱敏', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const allChanges = logs.flatMap(l => l.changes || []);
|
||||
const types = new Set(allChanges.map(c => c.changeType));
|
||||
assert.ok(types.has('ADDED'));
|
||||
assert.ok(types.has('UPDATED'));
|
||||
assert.ok(types.has('REMOVED'));
|
||||
for (const change of allChanges) {
|
||||
if (C.isSensitiveField(change.field)) {
|
||||
assert.ok([change.oldValue, change.newValue].every(v => v == null || v === '******'),
|
||||
'敏感字段不得落库明文:' + change.field);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user