fix: 登录页访问不再记成「登录成功」——认证端点只记录 POST,登录成败以响应确认为准

现场反馈:审计列表「没有失败,全是成功,登录失败也显示成功」。在 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 升级场景联调记录见测试报告
This commit is contained in:
2026-12-05 13:24:26 +08:00
parent afda8d04fd
commit fc7984291f
35 changed files with 1307 additions and 437 deletions
+16 -11
View File
@@ -30,9 +30,11 @@ python -m http.server 8721
- **八维筛选**:操作者(精确匹配)、资源类型、动作、语义动作、结果、关键字
(资源名称 / 路径模糊匹配)、开始时间、结束时间。下拉即时生效,文本与时间用「查询」
或回车;筛选条件摘要与「清除筛选」始终可见。
- **登录失败标注**:表单登录成败在 HTTP 层都是 302,按重定向目标是否含 `error`
参数判定;失败回显页 `GET /login?error=...`(HTTP 200)同样标红「失败」,
不会把 200/302 误读为登录成功。
- **认证操作与结果**:只记录真正的认证操作——`POST /login`(登录尝试)与 `POST /logout`
(登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出确认页)
不是操作,不记录。表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定:
失败显示红色「失败」,成功显示绿色「成功」。升级前落库的登录页访问记录(GET,
HTTP 200,曾显示成绿色「登录 200」)纠正为灰色「—」的「访问登录页」,不计成败。
- **行内「历史」快捷**:有资源名称的记录可一键预填「资源类型 + 资源名关键字」,
直接回答"这篇文章被谁改过"。
- **只读详情抽屉**:操作者、尝试用户、描述、动作、资源、结果、路径、时间、IP、
@@ -58,13 +60,15 @@ python -m http.server 8721
1. **页面 / API 操作**:填写操作者、方法、路径、响应状态、重定向目标
(登录用)、尝试的用户名与请求体 JSON,演示页按真实管线判定:
- `shouldCapture`:`/apis/**` 写操作、`/login`、`/logout`;匿名 / 读操作不记录;
- `shouldCapture`:`/apis/**` 写操作、`POST /login`、`POST /logout`;匿名 / 读操作 /
登录页 GET 访问不记录;
- `resolveResource`:从路径解析资源类型与名称;
- `classifyLogin`:302 重定向目标含 `error` → 登录失败(标注 `login-failure`);
- `classifyLogin`:302 重定向跳回登录页(含 `error` 参数)→ 登录失败(标注
`login-failure`);只有响应明确确认才算成功;
- 字段级 diff:PUT / PATCH(Merge Patch 或 JSON Patch)/ POST / DELETE,
自动脱敏密码/令牌类字段,超长截断、超 30 条封顶。
预设按钮覆盖:编辑文章(含 diff)、发布文章、升级插件、修改密码(脱敏)、
登录失败(表单 302)、登录成功、失败回显、读操作不记录。
登录失败(表单 302)、登录成功、打开登录页(不记录)、读操作不记录。
2. **系统内部变更**:模拟定时发布等非页面操作,执行者记为「系统」、无 IP/UA、
状态恒 200,仅更新/删除两类事件,附字段变更。
@@ -73,7 +77,7 @@ python -m http.server 8721
| 场景 | 操作 |
|---|---|
| 排查 hello-halo 被谁改过 | 关键字输入 `hello-halo`,或点击任意该资源记录的「历史」;打开详情看字段 diff |
| 登录爆破回溯 | 语义动作选「登录失败」:20 天前同一 IP `203.0.113.66` 的 6 次撞库 + 失败回显页 |
| 登录爆破回溯 | 语义动作选「登录失败」:20 天前同一 IP `203.0.113.66` 的 6 次撞库;不带筛选时同 IP 还能看到升级前落库的「访问登录页」记录(灰色「—」,不计成败) |
| 定时发布(系统内部变更) | 操作者输入 `system`,或资源类型选 `posts` + 关键字 `weekly-2026-w46` |
| 插件生命周期 | 关键字 `plugin-link` / `plugin-search-widget`;语义动作可筛「升级」「启用」「卸载」 |
| 误操作定位 | 关键字 `weekly-2026-w45`:1 天前的删除记录,详情含被删字段快照 |
@@ -92,7 +96,7 @@ demo/
│ ├── app.js # 交互层(渲染、筛选、历史、导出、设置、告警、模拟管线)
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components)
└── test/
└── audit-core.test.mjs # 单元测试(node:test,56 个用例)
└── audit-core.test.mjs # 单元测试(node:test,61 个用例)
```
## 运行测试
@@ -101,8 +105,9 @@ demo/
node --test demo/test/audit-core.test.mjs
```
覆盖:捕获规则(HTTP / 认证端点 / 匿名 / 读操作)、资源解析(含查询串与深层子资源)、
语义动作推导与中文描述、登录结果判定(2xx / 302 / error 参数 / 401 / 失败回显)、
覆盖:捕获规则(HTTP / 认证操作 / 登录页 GET 不记录 / 匿名 / 读操作)、资源解析(含查询串与深层子资源)、
语义动作推导与中文描述(含登录页访问纠正)、登录结果判定(2xx / 302 跳回登录页 / 缺失 Location / 401)、
结果语义(登录失败 / 登录成功 / 页面访问不计成败)、
字段 diff(PUT / PATCH Merge / PATCH JSON Patch / POST / DELETE、元数据过滤、敏感字段脱敏、
截断、30 条封顶)、八维筛选(登录失败结果语义、时间闭区间、关键字)、分页与保留期、
CSV(BOM / CRLF / 列顺序 / 转义 / 公式注入防护 / 升序)、告警窗口(阈值、告警后重开、
@@ -113,7 +118,7 @@ CSV(BOM / CRLF / 列顺序 / 转义 / 公式注入防护 / 升序)、告警
| 项 | Demo | 真实插件 |
|---|---|---|
| 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 |
| 捕获 | 弹窗里手动构造请求 | 双过滤器自动捕获(`/apis/**` + 认证端点) |
| 捕获 | 弹窗里手动构造请求 | 双过滤器自动捕获(`/apis/**` + 认证操作 `POST /login`、`POST /logout`) |
| 字段 diff | 与 Java 版同规则的 JS 简化实现(对象递归、数组整体比较、脱敏/截断/封顶) | `ChangeDiffEngine`(含 Halo 服务端字段更细的降噪与 JSON Pointer 解析) |
| 查询 | 前端数组筛选 | 自有查询端点(fieldSelector + 时间区间 + 模糊匹配) |
| 导出 | 浏览器 Blob 下载 | 后端全量流式 CSV(分批 200 条) |
+5 -3
View File
@@ -423,15 +423,17 @@
if (!log) { return; }
state.detailId = id;
var changes = log.changes || [];
var badge = C.resultBadge(log);
// 结果与列表徽标、筛选、CSV 共用同一语义(AuditResult):登录失败靠标注识别,
// 页面访问不计成败——详情写结果语义文字,原始状态码另列
var outcome = C.resultOutcome(log);
var details =
detailRow('操作者', avatar(log.username) + ' ' + esc(C.displayUsername(log.username))) +
(log.attemptedUsername ? detailRow('尝试用户', '<span class="mono">' + esc(log.attemptedUsername) + '</span>') : '') +
detailRow('描述', esc(C.describeOperation(log))) +
detailRow('动作', methodBadge(log.method)) +
detailRow('资源', esc(log.resourceType) + (log.resourceName ? ' / ' + esc(log.resourceName) : ' <span class="muted">(集合级操作)</span>')) +
detailRow('结果', '<span class="status-badge ' + badge.class + '">' + esc(badge.text) + '</span>' +
detailRow('结果', '<span class="status-badge ' + C.resultBadge(log).class + '">' +
esc(C.RESULT_LABELS[outcome]) + '</span>' +
' <span class="muted">状态码 ' + esc(log.statusCode) + '</span>') +
detailRow('路径', '<code class="path-code">' + esc(log.path) + '</code>') +
detailRow('时间', esc(C.formatTime(log.timestamp))) +
+160 -57
View File
@@ -2,10 +2,13 @@
* 操作审计 · 核心纯函数(浏览器与 Node 测试共用)
*
* 与插件当前实现保持一致(单一事实来源:后端 Java 与 Console UI 的同名逻辑):
* - 捕获规则(CaptureRule / AuthEndpointAuditWebFilter)
* - 捕获规则(CaptureRule / AuthEndpointAuditWebFilter:认证端点只记录 POST,
* 登录/登出页面的 GET 访问不是操作)
* - 资源解析(ResourceResolver)
* - 语义动作标注与中文描述(OperationDescription / ui/src/utils/audit.ts)
* - 登录结果判定(LoginOutcome:表单登录成败均为 302,以重定向目标 error 参数区分)
* - 登录结果判定(LoginOutcome:表单登录成败均为 302,以重定向目标是否跳回登录页区分;
* 只有响应明确确认才算成功)
* - 结果语义(AuditResult:登录失败 / 页面访问 / 按状态码)
* - 字段级变更 diff(ChangeDiffEngine:PUT/PATCH/POST/DELETE 语义、脱敏、截断、封顶)
* - 查询筛选(AuditLogFilters:八维筛选 + 登录失败结果语义)
* - CSV 导出(AuditLogCsvExporter:BOM、列顺序、公式注入防护)
@@ -25,6 +28,9 @@
var WRITE_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
var AUTH_ENDPOINTS = ['/login', '/logout'];
var LOGIN_FAILURE_ACTION = 'login-failure';
/** 登录页 / 登出页访问(GET,仅升级前落库的历史记录会出现)。 */
var LOGIN_PAGE_ACTION = 'login-page';
var LOGOUT_PAGE_ACTION = 'logout-page';
/** 资源类型(与 AuditLogList.vue 的筛选下拉一致) */
var RESOURCE_TYPES = [
@@ -80,6 +86,8 @@
login: '登录',
'login-failure': '登录失败',
logout: '登出',
'login-page': '访问登录页',
'logout-page': '访问登出页',
auth: '认证操作',
password: '修改密码',
resetpassword: '重置密码'
@@ -204,7 +212,8 @@
/**
* 捕获规则(CaptureRule + AuthEndpointAuditWebFilter):
* - /apis/** 下已登录用户的写操作(POST/PUT/DELETE/PATCH);
* - /login、/logout 认证端点始终记录(链首过滤器捕获,含登录失败与失败回显);
* - 认证操作 POST /login(登录尝试)、POST /logout(登出)始终记录
* (链首过滤器捕获,含登录失败);登录/登出页面的 GET 访问不是操作,不记录;
* - /apis/** 下认证后仍为匿名主体的请求不记录(401/403 场景)。
*
* @param {{method: string, path: string, authenticated: boolean}} options
@@ -217,10 +226,17 @@
var authenticated = !!(options && options.authenticated);
if (AUTH_ENDPOINTS.indexOf(clean) !== -1) {
if (method === 'POST') {
return {
captured: true,
channel: 'auth',
reason: '认证操作始终记录(POST /login 登录尝试、POST /logout 登出,含登录失败)'
};
}
return {
captured: true,
channel: 'auth',
reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)'
captured: false,
channel: 'none',
reason: '登录/登出页面的 GET 访问不是操作(打开登录页、被弹回登录页、失败回显、登出确认页),不记录'
};
}
if (clean.indexOf('/apis/') !== 0) {
@@ -272,14 +288,21 @@
return { resourceType: segs[3], resourceName: segs.length >= 5 && segs[4] ? segs[4] : null };
}
/** 推导语义动作键(与 OperationDescription.actionOf / deriveAction 一致)。 */
/**
* 推导语义动作键(与 OperationDescription.actionOf / deriveAction 一致):
* 认证端点按方法区分——POST 是登录/登出操作,其余方法是页面访问,路径带 error 参数的
* 登录页是升级前落库的失败回显;子动作段优先于 HTTP 方法。
*/
function deriveAction(method, resourceType, path) {
var clean = pathWithoutQuery(path);
if (clean === '/login') {
return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login';
if (hasErrorParam(path)) {
return LOGIN_FAILURE_ACTION;
}
return normalizeMethod(method) === 'POST' ? 'login' : LOGIN_PAGE_ACTION;
}
if (clean === '/logout') {
return 'logout';
return normalizeMethod(method) === 'POST' ? 'logout' : LOGOUT_PAGE_ACTION;
}
if (resourceType === 'auth') {
return 'auth';
@@ -294,6 +317,35 @@
return METHOD_ACTIONS[normalizeMethod(method)] || null;
}
/**
* 是否为认证端点的页面访问(GET /login、GET /logout,含查询串):不是登录/登出操作,
* 结果不计成败;现已不再记录,只有升级前落库的历史记录会出现——当时它们被记成
* 「未知用户 · 登录 · 200」,看起来像登录成功。
*/
function isAuthPageVisit(log) {
log = log || {};
if (normalizeMethod(log.method) === 'POST') {
return false;
}
var clean = pathWithoutQuery(log.path);
return clean === '/login' || clean === '/logout';
}
/**
* 记录的语义动作键(展示与结果判定共用):优先落库标注;认证端点的失败回显与页面访问
* (升级前落库为 login/logout 或无标注的历史记录)按方法与路径纠正;落库标注未识别时
* 回退 method/path 现场推导。
*/
function semanticAction(log) {
log = log || {};
var derived = deriveAction(log.method, log.resourceType, log.path);
if (derived === LOGIN_FAILURE_ACTION || derived === LOGIN_PAGE_ACTION ||
derived === LOGOUT_PAGE_ACTION) {
return derived;
}
return log.action && describeFromAction(log.action, log.resourceType) ? log.action : derived;
}
/** 由语义动作键推导中文短语;未识别返回 null(调用方回退 method 推导)。 */
function describeFromAction(action, resourceType) {
if (!action) {
@@ -307,16 +359,15 @@
return verb ? verb + (RESOURCE_LABELS[resourceType] || resourceType) : null;
}
/** 操作中文描述(优先落库语义动作,历史记录现场推导)。 */
function describeOperation(spec) {
spec = spec || {};
var action = spec.action || deriveAction(spec.method, spec.resourceType, spec.path);
var fromAction = describeFromAction(action, spec.resourceType);
/** 操作中文描述(以记录的语义动作键为准,含失败回显与页面访问纠正)。 */
function describeOperation(log) {
log = log || {};
var fromAction = describeFromAction(semanticAction(log), log.resourceType);
if (fromAction) {
return fromAction;
}
var label = RESOURCE_LABELS[spec.resourceType] || spec.resourceType;
var verb = METHOD_VERBS[normalizeMethod(spec.method)] || spec.method;
var label = RESOURCE_LABELS[log.resourceType] || log.resourceType;
var verb = METHOD_VERBS[normalizeMethod(log.method)] || log.method;
return verb + label;
}
@@ -325,24 +376,53 @@
return statusCode != null && statusCode >= 200 && statusCode < 400;
}
/** 是否为登录失败记录(优先落库标注,回退路径推导)。 */
function isLoginFailure(spec) {
spec = spec || {};
var action = spec.action || deriveAction(spec.method, spec.resourceType, spec.path);
return action === LOGIN_FAILURE_ACTION;
/** 是否为登录失败记录(以记录的语义动作键为准)。 */
function isLoginFailure(log) {
return semanticAction(log) === LOGIN_FAILURE_ACTION;
}
/** 结果语义标签(与后端 AuditResult.label 一致,CSV「结果」列用)。 */
var RESULT_LABELS = {
success: '成功',
failure: '失败',
'page-visit': '页面访问'
};
/**
* 记录的结果语义(与后端 AuditResult 同一规则,筛选 / CSV / 徽标共用):
* - failure:登录失败(表单登录失败的 HTTP 状态码与成功相同、均为 302,只能靠标注识别)
* 或状态码 4xx/5xx;
* - page-visit:认证端点的页面访问(升级前落库的 GET 记录),不是操作,不计成败;
* - success:其余状态码 2xx/3xx。
*/
function resultOutcome(log) {
if (isLoginFailure(log)) {
return 'failure';
}
if (isAuthPageVisit(log)) {
return 'page-visit';
}
return isSuccessful(log && log.statusCode) ? 'success' : 'failure';
}
/**
* 结果徽标:登录失败(HTTP 可能为 200/302)显示「失败」,
* 结果徽标:登录失败显示红色「失败」(表单失败是 302、失败回显是 200,裸状态码是绿的);
* 登录成功显示绿色「成功」(表单成功同样是 302);页面访问显示灰色「—」;
* 其余按状态码(2xx/3xx 绿、其余红)。
*/
function resultBadge(spec) {
if (isLoginFailure(spec)) {
function resultBadge(log) {
if (isLoginFailure(log)) {
return { text: '失败', class: 'status-fail' };
}
if (isAuthPageVisit(log)) {
return { text: '—', class: 'status-na' };
}
if (semanticAction(log) === 'login' && isSuccessful(log && log.statusCode)) {
return { text: '成功', class: 'status-ok' };
}
return {
text: String(spec && spec.statusCode),
class: isSuccessful(spec && spec.statusCode) ? 'status-ok' : 'status-fail'
text: String(log && log.statusCode),
class: isSuccessful(log && log.statusCode) ? 'status-ok' : 'status-fail'
};
}
@@ -376,37 +456,46 @@
// ---------------------------------------------------------------- 登录结果判定
/**
* 重定向是否跳回登录页:查询串含 error 参数(Halo 2.26 的四种失败重定向),或路径
* 本身就是 /login——成功只会去 /uc、已保存的原请求或 2FA 页。缺失 Location 的重定向
* 同样无法确认成功。
*/
function returnsToLoginPage(location) {
var target = String(location || '');
if (!target.trim()) {
return true;
}
return pathWithoutQuery(target) === '/login' || hasErrorParam(target);
}
/**
* 登录结果判定(LoginOutcome):
* - POST /login:2xx 成功;3xx 看重定向目标是否含 error 参数;其余失败;
* - GET /login?error=...:登录失败回显(HTTP 200 但语义为失败);
* - 其他请求不算登录尝试。
* - POST /login:2xx 成功;3xx 看重定向目标是否跳回登录页;其余状态码失败。
* 只有响应明确确认才算成功——把失败登录记成成功,远比把异常响应记成失败更糟;
* - 其他请求不算登录尝试(登录页 GET 不是操作,不记录)。
*
* @returns {{attempt: boolean, failure: boolean, echo: boolean}}
* @returns {{attempt: boolean, failure: boolean}}
*/
function classifyLogin(input) {
input = input || {};
var method = normalizeMethod(input.method);
var fullPath = String(input.path || '');
var clean = pathWithoutQuery(fullPath);
var attempt = method === 'POST' && clean === '/login';
var echo = method === 'GET' && clean === '/login' && hasErrorParam(fullPath);
if (attempt) {
var status = input.statusCode;
var failure;
if (status == null) {
failure = true;
} else if (status >= 200 && status < 300) {
failure = false;
} else if (status >= 300 && status < 400) {
failure = hasErrorParam(input.location);
} else {
failure = true;
}
return { attempt: true, failure: failure, echo: false };
var clean = pathWithoutQuery(String(input.path || ''));
if (method !== 'POST' || clean !== '/login') {
return { attempt: false, failure: false };
}
return { attempt: false, failure: echo, echo: echo };
var status = input.statusCode;
var failure;
if (status == null) {
failure = true;
} else if (status >= 200 && status < 300) {
failure = false;
} else if (status >= 300 && status < 400) {
failure = returnsToLoginPage(input.location);
} else {
failure = true;
}
return { attempt: true, failure: failure };
}
// ---------------------------------------------------------------- 字段级变更 diff
@@ -774,8 +863,9 @@
// 认证端点由 Security 链首过滤器捕获,无认证上下文:操作者统一记「未知用户」,
// 登录尝试的账号由请求体白名单提取(attemptedUsername)。
var username = authEndpoint ? 'unknown' : (input.username || 'unknown');
var action = login.failure ? LOGIN_FAILURE_ACTION
: deriveAction(method, resolved.resourceType, fullPath);
// 登录失败(POST /login)标注 login-failure;其余按 method/path 推导
var action = login.failure ? LOGIN_FAILURE_ACTION : deriveAction(
method, resolved.resourceType, fullPath);
var changes = null;
if (!authEndpoint && input.recordChanges !== false &&
@@ -878,9 +968,13 @@
return isNaN(ms) ? null : ms;
}
/** 结果判定:success = 2xx/3xx 且非登录失败;failure = 其余。 */
/** 结果判定(与 resultOutcome 一致):页面访问记录(历史 GET)既非成功也非失败。 */
function isSuccessRecord(log) {
return !isLoginFailure(log) && isSuccessful(log && log.statusCode);
return resultOutcome(log) === 'success';
}
function isFailureRecord(log) {
return resultOutcome(log) === 'failure';
}
/**
@@ -905,13 +999,15 @@
if (method && normalizeMethod(log.method) !== method) {
return false;
}
if (filters.action && log.action !== filters.action) {
// 语义动作按记录的语义动作键比对:升级前落库的页面访问记录(GET,标注 login/logout)
// 展示为「访问登录页/登出页」,筛登录/登出操作时不混入
if (filters.action && semanticAction(log) !== filters.action) {
return false;
}
if (filters.result === 'success' && !isSuccessRecord(log)) {
return false;
}
if (filters.result === 'failure' && isSuccessRecord(log)) {
if (filters.result === 'failure' && !isFailureRecord(log)) {
return false;
}
var time = new Date(log.timestamp).getTime();
@@ -995,7 +1091,6 @@
});
var lines = [CSV_HEADER.map(csvEscape).join(',')];
sorted.forEach(function (log) {
var badge = resultBadge(log);
lines.push([
csvEscape(formatTime(log.timestamp)),
csvEscape(displayUsername(log.username)),
@@ -1006,7 +1101,8 @@
csvEscape(log.path),
csvEscape(describeOperation(log)),
csvEscape(formatChanges(log.changes)),
csvEscape(badge.text === '失败' ? '失败' : (isSuccessRecord(log) ? '成功' : '失败')),
// 结果语义与界面一致(AuditResult):登录失败靠标注识别,页面访问不计成败
csvEscape(RESULT_LABELS[resultOutcome(log)]),
csvEscape(log.statusCode == null ? null : String(log.statusCode)),
csvEscape(log.remoteIp),
csvEscape(log.userAgent)
@@ -1111,6 +1207,9 @@
WRITE_METHODS: WRITE_METHODS,
AUTH_ENDPOINTS: AUTH_ENDPOINTS,
LOGIN_FAILURE_ACTION: LOGIN_FAILURE_ACTION,
LOGIN_PAGE_ACTION: LOGIN_PAGE_ACTION,
LOGOUT_PAGE_ACTION: LOGOUT_PAGE_ACTION,
RESULT_LABELS: RESULT_LABELS,
RESOURCE_TYPES: RESOURCE_TYPES,
RESOURCE_LABELS: RESOURCE_LABELS,
SEMANTIC_ACTIONS: SEMANTIC_ACTIONS,
@@ -1122,10 +1221,14 @@
shouldCapture: shouldCapture,
resolveResource: resolveResource,
deriveAction: deriveAction,
isAuthPageVisit: isAuthPageVisit,
semanticAction: semanticAction,
describeOperation: describeOperation,
isSuccessful: isSuccessful,
isLoginFailure: isLoginFailure,
isSuccessRecord: isSuccessRecord,
isFailureRecord: isFailureRecord,
resultOutcome: resultOutcome,
resultBadge: resultBadge,
displayUsername: displayUsername,
formatTime: formatTime,
+2
View File
@@ -529,6 +529,8 @@ tr.row-new td { animation: rowFlash 2.8s ease-out; }
}
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.status-fail { color: var(--danger); background: rgba(215, 29, 29, 0.12); }
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰 */
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
/* 空状态 */
.empty-state {
+33 -11
View File
@@ -8,7 +8,7 @@
*
* 内置故事线(固定时间锚点,可直接按演示页提示复现):
* 1. 排查「hello-halo 这篇文章谁改过」(多用户多次编辑,含字段 diff)
* 2. 登录爆破回溯(同一 IP、无差别撞库,含失败回显页)
* 2. 登录爆破回溯(同一 IP、无差别撞库;另含升级前落库的登录页访问记录)
* 3. 忘记密码后登录成功(失败 → 成功清零)
* 4. 定时发布(系统内部变更,执行者「系统」、无 IP/UA)
* 5. 插件生命周期(升级 / 停用 / 卸载,含字段 diff)
@@ -492,7 +492,7 @@
body: postDoc(hello, { visible: 'PUBLIC', pinned: true })
}));
// ---- 故事线 2:登录爆破回溯(同一 IP 无差别撞库 + 失败回显) ----
// ---- 故事线 2:登录爆破回溯(同一 IP、无差别撞库 + 升级前的登录页访问记录) ----
var burstBase = now - 20 * DAY - 3 * 3600 * 1000;
var attackAccounts = ['admin', 'root', 'oracle', 'test', 'admin', 'postgres'];
attackAccounts.forEach(function (account, idx) {
@@ -507,15 +507,25 @@
timestamp: new Date(burstBase + [0, 41, 88, 135, 210, 400][idx] * 1000).toISOString()
}));
});
// 浏览器随后渲染失败回显页(GET,HTTP 200):审计标注 login-failure,红色「失败」
add(make({
method: 'GET',
path: '/login?error=invalid-credential&method=form',
statusCode: 200,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + 401 * 1000).toISOString()
}));
// 升级前落库的登录页访问记录:旧版本把登录/登出页的 GET 访问也记成「登录/登出」
// (HTTP 200,标注 login/logout),现已不再记录;历史记录展示为「访问登录页/登出页」,
// 结果不计成败。失败回显页当时标注 login-failure,仍按登录失败展示。
[
{ at: 30, path: '/login', action: 'login' },
{ at: 70, path: '/login?authentication_required', action: 'login' },
{ at: 401, path: '/login?error=invalid-credential&method=form', action: 'login-failure' }
].forEach(function (visit) {
var legacy = make({
method: 'GET',
path: visit.path,
statusCode: 200,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + visit.at * 1000).toISOString()
});
legacy.action = visit.action;
add(legacy);
});
// ---- 故事线 3:忘记密码(失败两次后成功) ----
var retryBase = now - 12 * DAY - 10 * 3600 * 1000;
@@ -557,6 +567,18 @@
userAgent: UAS.chrome,
timestamp: new Date(now - 4 * DAY - 11 * 3600 * 1000).toISOString()
}));
// 升级前落库的登出确认页访问(GET,旧版本记成「登出」,现展示为「访问登出页」)
var legacyLogoutPage = make({
username: 'guichumo',
method: 'GET',
path: '/logout',
statusCode: 200,
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 4 * DAY - 11 * 3600 * 1000 - 2000).toISOString()
});
legacyLogoutPage.action = 'logout';
add(legacyLogoutPage);
// ---- 故事线 4:定时发布(系统内部变更:无 IP/UA,执行者「系统」) ----
add(AuditCore.buildSystemRecord({
+4 -3
View File
@@ -318,8 +318,9 @@
<button class="icon-btn" id="modal-close">✕</button>
</div>
<p class="modal-sub">
演示页按真实捕获管线逐步判定:<b>捕获规则</b>(<code>/apis/**</code> 写操作、<code>/login</code>、<code>/logout</code>)
→ <b>资源解析</b> → <b>登录结果</b>(302 重定向目标判定)→ <b>语义动作标注</b> → <b>字段级 diff</b>。
演示页按真实捕获管线逐步判定:<b>捕获规则</b>(<code>/apis/**</code> 写操作、<code>POST /login</code>、<code>POST /logout</code>;
登录/登出页面的 GET 访问不是操作,不记录)
→ <b>资源解析</b> → <b>登录结果</b>(302 重定向是否跳回登录页)→ <b>语义动作标注</b> → <b>字段级 diff</b>。
</p>
<div class="seg-tabs" id="sim-tabs">
@@ -397,9 +398,9 @@
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade","status":200,"snapshot":"plugin","body":{"apiVersion":"plugin.halo.run/v1alpha1","kind":"Plugin","metadata":{"name":"plugin-search-widget"},"spec":{"displayName":"搜索组件","version":"1.4.0","enabled":true,"requires":">=2.20.0"}}}'>升级插件(含 diff)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/api.console.halo.run/v1alpha1/users/guichumo/password","status":200,"body":{"apiVersion":"v1alpha1","kind":"User","metadata":{"name":"guichumo"},"spec":{"displayName":"guichumo","email":"guichumo@example.com","roles":["role-template-author"],"password":"runtime-demo-value"}}}'>修改密码(脱敏)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"GET","path":"/login?authentication_required","status":200}'>打开登录页(GET,不记录)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/login?error=invalid-credential&method=form","attempted":"admin"}'>登录失败(表单 302)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/uc","attempted":"guichumo"}'>登录成功(302 → /uc)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"GET","path":"/login?error=invalid-credential&method=form","status":200}'>登录失败回显(GET 200)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读,不记录)</button>
</div>
</div>
+129 -29
View File
@@ -45,17 +45,27 @@ test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', ()
assert.match(r.reason, /匿名/);
});
test('shouldCapture: 认证端点始终记录(含查询串与匿名登录尝试)', () => {
test('shouldCapture: 认证操作 POST /login、POST /logout 始终记录(含匿名登录尝试)', () => {
assert.deepEqual(
C.shouldCapture({ method: 'POST', path: '/login', authenticated: false }),
{
captured: true,
channel: 'auth',
reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)'
reason: '认证操作始终记录(POST /login 登录尝试、POST /logout 登出,含登录失败)'
}
);
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: 登录/登出页面的 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/** 之外的普通路径不记录', () => {
@@ -105,11 +115,17 @@ test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
});
// ---------------- deriveAction / describeOperation ----------------
test('deriveAction: 登录/登出/失败回显', () => {
test('deriveAction: 登录/登出按方法区分,失败回显由 error 参数识别', () => {
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');
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 方法', () => {
@@ -143,32 +159,70 @@ test('describeOperation: 历史记录无 action 时现场推导;未识别回
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, echo: false });
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: 失败回显页(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('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 也显示「失败」', () => {
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(
@@ -177,11 +231,30 @@ test('resultBadge: 登录失败即使 200/302 也显示「失败」', () => {
);
});
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({ action: 'login-failure', statusCode: 200 }), false);
assert.equal(C.isSuccessRecord({ action: 'login', statusCode: 302 }), true);
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 → 系统', () => {
@@ -367,7 +440,8 @@ test('buildRecord: 登录请求操作者记「未知用户」,失败标注 log
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(success.action, 'login');
assert.equal(C.resultBadge(success).text, '302');
assert.equal(C.resultBadge(success).text, '成功');
assert.equal(C.resultBadge(failure).text, '失败');
});
test('buildRecord: 仅 2xx 且 recordChanges 开启时计算 diff', () => {
@@ -456,7 +530,10 @@ function fixture() {
{ 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' }
{ 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' }
];
}
@@ -467,7 +544,12 @@ test('applyFilters: 操作者 / 资源类型 / 动作 / 语义动作', () => {
assert.deepEqual(C.applyFilters(fixture(), { action: 'login-failure' }).map(l => l.id), ['a3']);
});
test('applyFilters: 结果语义(登录失败 200 计失败;登录成功 302 计成功)', () => {
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);
@@ -477,7 +559,7 @@ test('applyFilters: 结果语义(登录失败 200 计失败;登录成功 302
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']);
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'LOGIN' }).map(l => l.id), ['a4', 'a3', 'a6']);
});
test('applyFilters: 起止时间闭区间', () => {
@@ -493,8 +575,8 @@ test('applyFilters: 组合条件、时间倒序、不修改入参', () => {
assert.deepEqual(out.map(l => l.id), ['a2']);
const logs = fixture();
C.applyFilters(logs, {});
assert.equal(logs.length, 5);
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a5']);
assert.equal(logs.length, 7);
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a6', 'a5', 'a7']);
});
// ---------------- paginate / countExpired ----------------
@@ -511,7 +593,7 @@ test('paginate: 分页与越界收敛', () => {
});
test('countExpired: 统计超过保留期的记录', () => {
assert.equal(C.countExpired(fixture(), 5, NOW), 1);
assert.equal(C.countExpired(fixture(), 5, NOW), 2);
assert.equal(C.countExpired(fixture(), 90, NOW), 0);
});
@@ -525,13 +607,18 @@ test('toCsv: UTF-8 BOM + CRLF + 表头列顺序', () => {
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: '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, 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$/);
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: 引号/逗号/换行转义与公式注入防护', () => {
@@ -655,13 +742,26 @@ test('MockData.generateLogs: 资源解析与语义动作与捕获管线一致',
}
});
test('MockData.generateLogs: 覆盖登录失败(302 重定向与 GET 回显 200)', () => {
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-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'));
// 模拟数据不产生「登录页 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)', () => {