现场反馈:审计列表「没有失败,全是成功,登录失败也显示成功」。在 Halo 2.26.1 上 复现(afda8d0 构建):GET /login、GET /login?authentication_required 只是打开登录页 (HTTP 200),却被记成「未知用户 · 登录 200」,列表里看起来全是登录成功;POST /login 本身的成败判定是对的,但被这些记录淹没。 - 捕获:AuthEndpointAuditWebFilter 只记录 POST /login(登录尝试)与 POST /logout (登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出 确认页)原样透传不记录(CaptureRule.isAuthOperation) - 判定:LoginOutcome 只有响应明确确认才算成功——302 跳回登录页(含 error 参数或 路径即 /login)、缺失 Location、4xx/5xx 一律判失败;移除失败回显页判定 - 结果语义:新增 AuditResult(成功 / 失败 / 页面访问),结果筛选、CSV 导出与前端 resultBadge 共用同一规则;登录成功显示「成功」,与「失败」对称 - 历史数据:升级前落库的登录页访问记录(GET,标注 login/logout)展示与导出为 「访问登录页/登出页」且不计成败,结果筛选与「登录/登出」语义动作筛选均排除; 落库标注不改写 - demo 同步同一套规则;README 与设计/技术文档同步 测试:后端 286、UI 74、demo 61 全过;真实 Halo 2.26.1 升级场景联调记录见测试报告
817 lines
42 KiB
JavaScript
817 lines
42 KiB
JavaScript
/**
|
||
* 操作审计 Demo · 核心逻辑单元测试
|
||
*
|
||
* 运行:node --test demo/test/audit-core.test.mjs
|
||
* 覆盖对象(与插件当前实现一一对应):
|
||
* - 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 C = require('../assets/audit-core.js');
|
||
const MockData = require('../assets/mock-data.js');
|
||
|
||
// ---------------- 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 = 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 = C.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
|
||
assert.equal(r.captured, false);
|
||
assert.match(r.reason, /匿名/);
|
||
});
|
||
|
||
test('shouldCapture: 认证操作 POST /login、POST /logout 始终记录(含匿名登录尝试)', () => {
|
||
assert.deepEqual(
|
||
C.shouldCapture({ method: 'POST', path: '/login', authenticated: false }),
|
||
{
|
||
captured: true,
|
||
channel: 'auth',
|
||
reason: '认证操作始终记录(POST /login 登录尝试、POST /logout 登出,含登录失败)'
|
||
}
|
||
);
|
||
assert.equal(C.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).channel, 'auth');
|
||
});
|
||
|
||
test('shouldCapture: 登录/登出页面的 GET 访问不是操作,不记录', () => {
|
||
// 打开登录页、被弹回登录页、失败回显、登出确认页都只是渲染页面(HTTP 200);
|
||
// 原先一律落库成「未知用户 · 登录 · 200」,在列表里与登录成功无法区分
|
||
for (const path of ['/login', '/login?authentication_required', '/login?error=invalid-credential', '/logout']) {
|
||
const r = C.shouldCapture({ method: 'GET', path, authenticated: false });
|
||
assert.equal(r.captured, false, path);
|
||
assert.equal(r.channel, 'none', path);
|
||
assert.match(r.reason, /GET 访问不是操作/, path);
|
||
}
|
||
});
|
||
|
||
test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
|
||
const r = C.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
|
||
assert.equal(r.captured, false);
|
||
assert.match(r.reason, /捕获范围/);
|
||
});
|
||
|
||
test('shouldCapture: 匿名规则优先于读操作规则(与后端一致)', () => {
|
||
const r = C.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
|
||
assert.equal(r.captured, false);
|
||
assert.match(r.reason, /匿名/);
|
||
});
|
||
|
||
// ---------------- resolveResource(资源解析) ----------------
|
||
test('resolveResource: 单资源 / 集合 / 深层子资源', () => {
|
||
assert.deepEqual(
|
||
C.resolveResource('/apis/content.halo.run/v1alpha1/posts/xyz'),
|
||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||
);
|
||
assert.deepEqual(
|
||
C.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
|
||
{ resourceType: 'posts', resourceName: null }
|
||
);
|
||
assert.deepEqual(
|
||
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?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(C.resolveResource('/console').resourceType, 'other');
|
||
assert.equal(C.resolveResource('/apis/only-group').resourceType, 'other');
|
||
assert.equal(C.resolveResource('').resourceType, 'other');
|
||
});
|
||
|
||
// ---------------- deriveAction / describeOperation ----------------
|
||
test('deriveAction: 登录/登出按方法区分,失败回显由 error 参数识别', () => {
|
||
assert.equal(C.deriveAction('POST', 'auth', '/login'), 'login');
|
||
assert.equal(C.deriveAction('POST', 'auth', '/login?continue=/uc'), 'login');
|
||
assert.equal(C.deriveAction('POST', 'auth', '/logout'), 'logout');
|
||
// GET 是页面访问(打开登录页、被弹回登录页、登出确认页)
|
||
assert.equal(C.deriveAction('GET', 'auth', '/login'), 'login-page');
|
||
assert.equal(C.deriveAction('GET', 'auth', '/login?authentication_required'), 'login-page');
|
||
assert.equal(C.deriveAction('GET', 'auth', '/logout'), 'logout-page');
|
||
// 升级前落库的失败回显(GET /login?error=...)无标注时现场推导
|
||
assert.equal(C.deriveAction('GET', 'auth', '/login?error=invalid-credential'), 'login-failure');
|
||
assert.equal(C.deriveAction('GET', 'auth', '/login?errors=1'), 'login-page');
|
||
});
|
||
|
||
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');
|
||
});
|
||
|
||
test('describeOperation: 升级前落库的登录页访问记录(GET + login 标注)纠正为页面访问', () => {
|
||
// 旧版本把登录页的 GET 访问记成「未知用户 · 登录 · 200」,看起来像登录成功
|
||
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login?authentication_required', action: 'login' }), '访问登录页');
|
||
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login', action: 'login' }), '访问登录页');
|
||
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login' }), '访问登录页');
|
||
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/logout', action: 'logout' }), '访问登出页');
|
||
// POST 才是登录/登出操作,落库标注照常生效
|
||
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login' }), '登录');
|
||
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/logout', action: 'logout' }), '登出');
|
||
});
|
||
|
||
// ---------------- classifyLogin(登录结果判定) ----------------
|
||
test('classifyLogin: POST /login 的 2xx/302/401 判定', () => {
|
||
assert.deepEqual(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 200 }), { attempt: true, failure: 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: 302, location: '/login?error=rate-limit-exceeded&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: 403 }).failure, true);
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: null }).failure, true);
|
||
});
|
||
|
||
test('classifyLogin: 只有响应明确确认才算成功——跳回登录页或缺失 Location 均判失败', () => {
|
||
// 不依赖 error 参数:宿主换了失败重定向格式也不会把失败记成成功
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login' }).failure, true);
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?authentication_required' }).failure, true);
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302 }).failure, true, '缺失 Location 无法确认成功');
|
||
// 含 error 字样的其他参数、路径前缀相同都不算跳回登录页
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/uc?errors=1' }).failure, false);
|
||
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login-callback' }).failure, false);
|
||
});
|
||
|
||
test('classifyLogin: 登录页 GET 与登出不是登录尝试', () => {
|
||
for (const input of [
|
||
{ method: 'GET', path: '/login', statusCode: 200 },
|
||
{ method: 'GET', path: '/login?error=invalid-credential', statusCode: 200 },
|
||
{ method: 'GET', path: '/login?authentication_required', statusCode: 200 },
|
||
{ method: 'POST', path: '/logout', statusCode: 302 }
|
||
]) {
|
||
assert.deepEqual(C.classifyLogin(input), { attempt: false, failure: false }, JSON.stringify(input));
|
||
}
|
||
});
|
||
|
||
// ---------------- 结果徽标 / 登录失败标注 ----------------
|
||
test('resultBadge: 登录失败即使 200/302 也显示「失败」,登录成功显示「成功」', () => {
|
||
assert.deepEqual(
|
||
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login-failure', statusCode: 302 }),
|
||
{ text: '失败', class: 'status-fail' }
|
||
);
|
||
// 升级前落库的失败回显页(GET,HTTP 200)
|
||
assert.deepEqual(
|
||
C.resultBadge({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure', statusCode: 200 }),
|
||
{ text: '失败', class: 'status-fail' }
|
||
);
|
||
// 表单登录成功同样是 302:裸状态码读不出成败,写「成功」与「失败」对称
|
||
assert.deepEqual(
|
||
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }),
|
||
{ text: '成功', class: 'status-ok' }
|
||
);
|
||
// 其余记录保持数字状态码徽标
|
||
assert.deepEqual(
|
||
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/logout', action: 'logout', 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('resultBadge / resultOutcome: 登录页访问记录显示灰色「—」,既不算成功也不算失败', () => {
|
||
// 升级前落库的 GET /login(HTTP 200、带 login 标注)原先显示绿色「200」,
|
||
// 看起来像未知用户登录成功
|
||
const visit = { method: 'GET', resourceType: 'auth', path: '/login?authentication_required', action: 'login', statusCode: 200 };
|
||
assert.equal(C.isAuthPageVisit(visit), true);
|
||
assert.equal(C.isLoginFailure(visit), false);
|
||
assert.deepEqual(C.resultBadge(visit), { text: '—', class: 'status-na' });
|
||
assert.equal(C.resultOutcome(visit), 'page-visit');
|
||
assert.equal(C.isSuccessRecord(visit), false);
|
||
assert.equal(C.isFailureRecord(visit), false);
|
||
assert.equal(C.resultOutcome({ method: 'GET', resourceType: 'auth', path: '/logout', action: 'logout', statusCode: 200 }), 'page-visit');
|
||
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
|
||
assert.equal(C.resultOutcome({ method: 'GET', resourceType: 'auth', path: '/login', statusCode: 500 }), 'page-visit');
|
||
// POST 是认证操作
|
||
assert.equal(C.isAuthPageVisit({ method: 'POST', resourceType: 'auth', path: '/login' }), false);
|
||
assert.equal(C.isAuthPageVisit({ method: 'GET', resourceType: 'posts', path: '/apis/x/v1alpha1/login' }), false);
|
||
});
|
||
|
||
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({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login-failure', statusCode: 200 }), false);
|
||
assert.equal(C.isSuccessRecord({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }), true);
|
||
assert.equal(C.isFailureRecord({ method: 'POST', resourceType: 'posts', path: '/apis/x/v1alpha1/posts', statusCode: 403 }), 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, '成功');
|
||
assert.equal(C.resultBadge(failure).text, '失败');
|
||
});
|
||
|
||
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, 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' },
|
||
// 升级前落库的登录页访问记录(GET、HTTP 200,带旧版本的 login 标注)
|
||
{ id: 'a6', timestamp: '2026-11-20T07:00:00Z', username: 'unknown', method: 'GET', path: '/login?authentication_required', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login' },
|
||
{ id: 'a7', timestamp: '2026-11-09T08:00:00Z', username: 'unknown', method: 'GET', path: '/logout', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'logout' }
|
||
];
|
||
}
|
||
|
||
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: 语义动作筛「登录/登出」不混入登录页访问记录(它们展示为「访问登录页/登出页」)', () => {
|
||
assert.deepEqual(C.applyFilters(fixture(), { action: 'login' }).map(l => l.id), ['a4']);
|
||
assert.deepEqual(C.applyFilters(fixture(), { action: 'logout' }).map(l => l.id), []);
|
||
});
|
||
|
||
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: 关键字匹配资源名称与路径', () => {
|
||
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', 'a6']);
|
||
});
|
||
|
||
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']);
|
||
const logs = fixture();
|
||
C.applyFilters(logs, {});
|
||
assert.equal(logs.length, 7);
|
||
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a6', 'a5', 'a7']);
|
||
});
|
||
|
||
// ---------------- paginate / countExpired ----------------
|
||
test('paginate: 分页与越界收敛', () => {
|
||
const items = Array.from({ length: 25 }, (_, i) => i);
|
||
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('countExpired: 统计超过保留期的记录', () => {
|
||
assert.equal(C.countExpired(fixture(), 5, NOW), 2);
|
||
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' },
|
||
{ id: 'c', timestamp: '2026-11-22T10:00:00Z', username: 'unknown', method: 'POST', path: '/login', resourceType: 'auth', resourceName: null, statusCode: 302, action: 'login', attemptedUsername: 'guichumo', remoteIp: '3.3.3.3', userAgent: 'chrome' },
|
||
// 升级前落库的登录页访问记录:原先导出为「登录,成功」,看起来像未知用户登录成功
|
||
{ id: 'd', timestamp: '2026-11-19T10:00:00Z', username: 'unknown', method: 'GET', path: '/login?authentication_required', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login', attemptedUsername: null, remoteIp: '43.228.157.244', userAgent: 'bot' }
|
||
];
|
||
const lines = C.toCsv(logs).split('\r\n');
|
||
assert.equal(lines.length, 6, '表头 + 4 行 + 末尾空行');
|
||
assert.match(lines[1], /^2026-11-19 18:00:00,未知用户,,GET,auth,,\/login\?authentication_required,访问登录页,,页面访问,200,43\.228\.157\.244,bot$/);
|
||
assert.match(lines[2], /^2026-11-20 18:00:00,未知用户,admin,GET,auth,,/);
|
||
assert.match(lines[2], /登录失败,.*失败,200,2\.2\.2\.2,bot$/);
|
||
assert.match(lines[3], /发布文章,.*成功,200,1\.1\.1\.1,UA$/);
|
||
assert.match(lines[4], /登录,,成功,302,3\.3\.3\.3,chrome$/);
|
||
});
|
||
|
||
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', 'attemptedUsername', 'method', 'action',
|
||
'resourceType', 'resourceName', 'path', 'statusCode', 'remoteIp', 'userAgent', 'changes'
|
||
];
|
||
|
||
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(Object.prototype.hasOwnProperty.call(log, field), `记录 ${log.id} 缺少字段 ${field}`);
|
||
}
|
||
}
|
||
});
|
||
|
||
test('MockData.generateLogs: 按时间倒序且 id 唯一', () => {
|
||
const logs = MockData.generateLogs(FIXED_NOW);
|
||
assert.equal(new Set(logs.map(l => l.id)).size, logs.length, 'id 应唯一');
|
||
for (let i = 1; i < logs.length; i++) {
|
||
assert.ok(new Date(logs[i - 1].timestamp).getTime() >= new Date(logs[i].timestamp).getTime());
|
||
}
|
||
});
|
||
|
||
test('MockData.generateLogs: 资源解析与语义动作与捕获管线一致', () => {
|
||
const logs = MockData.generateLogs(FIXED_NOW);
|
||
for (const log of logs) {
|
||
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: 覆盖登录失败(302)、登录成功与升级前的登录页访问记录', () => {
|
||
const logs = MockData.generateLogs(FIXED_NOW);
|
||
assert.ok(logs.some(l => l.action === 'login-failure' && l.method === 'POST' && l.statusCode === 302));
|
||
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'));
|
||
// 模拟数据不产生「登录页 GET 访问」的新记录:除升级前落库的历史记录外,
|
||
// 认证端点只有 POST
|
||
const visits = logs.filter(l => l.method !== 'POST' && ['/login', '/logout'].includes(C.pathWithoutQuery(l.path)));
|
||
assert.ok(visits.length >= 2, '应含升级前的登录页/登出页访问记录');
|
||
for (const visit of visits) {
|
||
if (C.isLoginFailure(visit)) {
|
||
// 升级前落库的失败回显页:当时标注 login-failure,仍按登录失败展示
|
||
assert.equal(C.resultOutcome(visit), 'failure');
|
||
assert.equal(C.describeOperation(visit), '登录失败');
|
||
} else {
|
||
assert.equal(C.resultOutcome(visit), 'page-visit');
|
||
assert.match(C.describeOperation(visit), /^访问(登录|登出)页$/);
|
||
}
|
||
}
|
||
});
|
||
|
||
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);
|
||
}
|
||
});
|
||
|
||
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);
|
||
}
|
||
}
|
||
});
|