Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00c8d3f1df | ||
|
|
fc7984291f | ||
|
|
afda8d04fd | ||
|
|
602744debd | ||
|
|
9329f313f4 | ||
|
|
fd43c069ae |
@@ -0,0 +1,21 @@
|
||||
# 统一换行:仓库内文本一律 LF,避免跨平台提交产生无意义 diff
|
||||
* text=auto eol=lf
|
||||
|
||||
# 脚本与 Windows 批处理
|
||||
*.sh text eol=lf
|
||||
gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
|
||||
# 二进制文件不做文本转换与 diff
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.jar binary
|
||||
*.zip binary
|
||||
*.pdf binary
|
||||
|
||||
# 锁文件按生成物处理,减少 diff 噪音
|
||||
package-lock.json linguist-generated=true
|
||||
@@ -9,10 +9,10 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
||||
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获认证操作 `POST /login`、`POST /logout`(含登录失败);登录/登出页面的 GET 访问不是操作,不记录 |
|
||||
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
|
||||
| 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标 `error` 参数区分):失败尝试与失败回显页(`GET /login?error=...`)在列表/详情/CSV 中显示红色「失败」,而非被页面渲染的绿色 HTTP 200 掩盖 |
|
||||
| 登录成败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标是否跳回登录页区分,只有响应明确确认才算成功):失败尝试在列表/详情/CSV 中显示红色「失败」,成功显示「成功」;升级前落库的登录页访问记录(`GET /login`,曾被显示成绿色「登录 200」)纠正为灰色「—」的「访问登录页」,不计成败 |
|
||||
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
||||
@@ -28,7 +28,12 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
||||
│ ├── src/ # 捕获过滤器、审计模型、查询端点、保留期清理
|
||||
│ └── ui/ # Console 前端(Vue 3 + vitest)
|
||||
├── demo/ # Console UI 静态演示页(纯前端、模拟数据、零构建依赖)
|
||||
├── docs/ # 设计文档:产品设计 · 技术方案
|
||||
├── docs/ # 设计 / 验收 / 测试文档
|
||||
│ └── assets/gui-test-screenshots/ # 浏览器级 UI 验收截图证据
|
||||
├── .github/workflows/ # CI/CD(复用 halo-sigs 官方可复用工作流)
|
||||
├── .agents/skills/ # 项目级 AI 技能(halo-plugin-dev)
|
||||
├── gradlew / gradlew.bat # 仓库根转发脚本:CI 在根目录执行,转发到 plugin-operation-audit/
|
||||
├── skills-lock.json # 技能安装锁文件
|
||||
└── AGENTS.md # AI 协作约定(每次改动需 commit、测试全绿后交付)
|
||||
```
|
||||
|
||||
@@ -58,14 +63,15 @@ cd demo
|
||||
python -m http.server 8721 # 访问 http://127.0.0.1:8721/
|
||||
```
|
||||
|
||||
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页内置若干故事线,
|
||||
可体验"排查这篇文章谁改过""登录爆破回溯""误操作定位"等典型场景,
|
||||
并通过"模拟一次操作"按钮验证捕获规则的边界。
|
||||
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页已按当前插件实现重写,
|
||||
包含八维筛选、语义动作与中文描述、字段级变更 diff、登录失败标注与告警、CSV 导出、
|
||||
系统内部变更,以及复现捕获管线的「模拟一次操作」。内置故事线可直接体验
|
||||
"排查这篇文章谁改过""登录爆破回溯""定时发布归属""误操作定位"等场景。
|
||||
|
||||
### 运行演示测试
|
||||
|
||||
```bash
|
||||
node --test demo/test/audit-core.test.mjs
|
||||
node --test demo/test/audit-core.test.mjs # 61 个用例
|
||||
```
|
||||
|
||||
## 相关文档
|
||||
@@ -73,6 +79,15 @@ node --test demo/test/audit-core.test.mjs
|
||||
| 文档 | 内容 |
|
||||
|---|---|
|
||||
| [plugin-operation-audit/README.md](plugin-operation-audit/README.md) | 插件详情:功能、安装、设置、模型 group 与已知局限 |
|
||||
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、与真实实现的差异 |
|
||||
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、故事线复现方式、与真实实现的差异 |
|
||||
| [docs/operation-audit-design.md](docs/operation-audit-design.md) | 产品设计:MVP 范围、设计原则 |
|
||||
| [docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md) | 技术方案:架构、数据模型、风险预案 |
|
||||
| [docs/operation-audit-roadmap.md](docs/operation-audit-roadmap.md) | 功能增量评估(MVP 之后的候选能力) |
|
||||
| [docs/operation-audit-halo-compliance.md](docs/operation-audit-halo-compliance.md) | Halo 官方开发规范符合性评审 |
|
||||
| [docs/plugin-release-checklist.md](docs/plugin-release-checklist.md) | 插件发布验收清单(官方流程存档) |
|
||||
| [docs/operation-audit-release-checklist-review.md](docs/operation-audit-release-checklist-review.md) | 发布验收逐项确认报告 |
|
||||
| [docs/operation-audit-release-todos-completion.md](docs/operation-audit-release-todos-completion.md) | 发布验收待办完成记录 |
|
||||
| [docs/plugin-testing.md](docs/plugin-testing.md) | Halo 官方测试流程文档存档 |
|
||||
| [docs/operation-audit-test-report.md](docs/operation-audit-test-report.md) | 分层测试报告(源码级 + 联调 + UI 验收) |
|
||||
| [docs/ai-assisted.md](docs/ai-assisted.md) | AI 辅助开发说明与文档上下文 |
|
||||
| [docs/assets/gui-test-screenshots/](docs/assets/gui-test-screenshots/) | 浏览器级 UI 验收截图证据 |
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
# 操作审计插件 · Console UI Demo
|
||||
|
||||
> 对应文档:[operation-audit-design.md](../docs/operation-audit-design.md)(产品设计)· [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)(技术方案)
|
||||
> 已按**当前已实现的插件**(Halo 2.26.1)重写:不再是最初的界面原型,而是把插件的
|
||||
> 查询/筛选、字段级 diff、登录结果判定、CSV 导出、登录失败告警与系统内部变更等能力
|
||||
> 用纯前端方式完整复现,便于在没有 Halo 实例时体验与验收。
|
||||
>
|
||||
> **纯前端静态 Demo,无任何后端与构建依赖**,用于在开发真实插件前验证界面布局与操作流程是否合理。
|
||||
> 对应实现:[plugin-operation-audit](../plugin-operation-audit/) · 设计文档:
|
||||
> [operation-audit-design.md](../docs/operation-audit-design.md) ·
|
||||
> [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -18,46 +22,81 @@ python -m http.server 8721
|
||||
|
||||
## 演示了什么
|
||||
|
||||
模拟 Halo Console 外壳(左侧菜单新增"操作审计"插件入口),包含两个页面:
|
||||
### 审计日志(与真实 Console 页面一致)
|
||||
|
||||
### 审计日志(产品设计 4.2)
|
||||
- **列表列**:操作者 / 时间、动作(HTTP 方法徽标)、资源 / 路径、描述、结果、IP。
|
||||
描述列展示语义动作的中文短语(登录、登录失败、发布文章、启用插件、修改密码……),
|
||||
不是裸的 HTTP 方法。
|
||||
- **八维筛选**:操作者(精确匹配)、资源类型、动作、语义动作、结果、关键字
|
||||
(资源名称 / 路径模糊匹配)、开始时间、结束时间。下拉即时生效,文本与时间用「查询」
|
||||
或回车;筛选条件摘要与「清除筛选」始终可见。
|
||||
- **认证操作与结果**:只记录真正的认证操作——`POST /login`(登录尝试)与 `POST /logout`
|
||||
(登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出确认页)
|
||||
不是操作,不记录。表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定:
|
||||
失败显示红色「失败」,成功显示绿色「成功」。升级前落库的登录页访问记录(GET,
|
||||
HTTP 200,曾显示成绿色「登录 200」)纠正为灰色「—」的「访问登录页」,不计成败。
|
||||
- **行内「历史」快捷**:有资源名称的记录可一键预填「资源类型 + 资源名关键字」,
|
||||
直接回答"这篇文章被谁改过"。
|
||||
- **只读详情抽屉**:操作者、尝试用户、描述、动作、资源、结果、路径、时间、IP、
|
||||
User-Agent、记录标识,以及**字段变更**(新增 / 修改 / 删除,旧值删除线 → 新值)
|
||||
与原始 `AuditLog` Extension JSON;不提供任何删除/修改入口。
|
||||
- **CSV 导出**:按当前筛选条件导出全部记录,UTF-8 BOM + CRLF,列与界面一致
|
||||
(含「尝试用户」「操作描述」「变更」),带引号转义与公式注入防护,Excel/WPS 直开不乱码。
|
||||
- **分页**:10 / 20 / 50 条每页。
|
||||
|
||||
- 列表:时间、操作者、动作(HTTP 方法徽标)、资源(类型 + 名称)、结果(状态码)、来源 IP
|
||||
- 筛选:操作者 / 资源类型 / 动作 / 结果 / 时间范围 / 关键字(资源名称与路径模糊匹配)
|
||||
- 分页:10 / 20 / 50 条每页
|
||||
- 详情:点击任意行打开右侧抽屉,展示全部字段(含完整路径、User-Agent、原始 JSON),**只读,无任何修改/删除入口**(设计原则 3)
|
||||
- 数据内置若干"故事线",可直接体验典型场景:
|
||||
- **排查"这篇文章谁改过"**:关键字输入 `hello-halo`
|
||||
- **安全回溯**:资源类型选 `auth` + 结果选"失败"(可见 20 天前同一攻击 IP `203.0.113.66` 的 6 次登录爆破)
|
||||
- **误操作定位**:关键字输入 `weekly-2026-w45`(1 天前被删除的文章)
|
||||
### 插件设置
|
||||
|
||||
### 插件设置(产品设计 4.3 / 技术方案 D5、D6)
|
||||
- **审计设置**:启用审计、记录字段变更、记录系统内部变更、保留天数(最小 7 天);
|
||||
关闭审计后日志页出现横幅,新操作不再记录。
|
||||
- **告警通知**:启用登录失败告警、Webhook Secret 引用、触发阈值、统计窗口、
|
||||
「发送测试告警」与「模拟 5 次登录失败」。达阈值后页面顶部出现红色告警横幅,
|
||||
并可一键筛选"只看失败记录";告警 JSON 负载在设置页展示。
|
||||
演示页不发起真实网络请求(真实插件由后端推送并带 SSRF 防护)。
|
||||
- **清理预览**:按保留期实时统计待清理条数,可模拟一次定时清理。
|
||||
|
||||
- 审计开关:关闭后日志页出现横幅,新操作不再记录
|
||||
- 保留天数:修改后"清理预览"实时计算待清理条数,可点击"模拟一次清理"体验定时清理效果
|
||||
### 模拟一次操作(复现捕获管线)
|
||||
|
||||
### 模拟一次操作(技术方案 D1 / 5.1 / 5.2)
|
||||
右上角「模拟一次操作」有两个通道:
|
||||
|
||||
右上角"模拟一次操作"按钮可模拟任意后台请求,Demo 按真实捕获管线逐步判定:
|
||||
1. **页面 / API 操作**:填写操作者、方法、路径、响应状态、重定向目标
|
||||
(登录用)、尝试的用户名与请求体 JSON,演示页按真实管线判定:
|
||||
- `shouldCapture`:`/apis/**` 写操作、`POST /login`、`POST /logout`;匿名 / 读操作 /
|
||||
登录页 GET 访问不记录;
|
||||
- `resolveResource`:从路径解析资源类型与名称;
|
||||
- `classifyLogin`:302 重定向跳回登录页(含 `error` 参数)→ 登录失败(标注
|
||||
`login-failure`);只有响应明确确认才算成功;
|
||||
- 字段级 diff:PUT / PATCH(Merge Patch 或 JSON Patch)/ POST / DELETE,
|
||||
自动脱敏密码/令牌类字段,超长截断、超 30 条封顶。
|
||||
预设按钮覆盖:编辑文章(含 diff)、发布文章、升级插件、修改密码(脱敏)、
|
||||
登录失败(表单 302)、登录成功、打开登录页(不记录)、读操作不记录。
|
||||
2. **系统内部变更**:模拟定时发布等非页面操作,执行者记为「系统」、无 IP/UA、
|
||||
状态恒 200,仅更新/删除两类事件,附字段变更。
|
||||
|
||||
1. `shouldCapture`:是否命中捕获规则(`/apis/**` 写操作 + `/login`、`/logout`;匿名请求不记录)
|
||||
2. `resolveResource`:从路径解析资源类型与名称
|
||||
3. 命中则生成审计记录置顶高亮;未命中则用 toast 解释原因(读操作 / 匿名 / 路径不匹配)
|
||||
## 故事线(可直接复现)
|
||||
|
||||
预设按钮包含"登录失败""查询文章列表(读)"等例子,可直观验证规则边界(登录失败记"未知用户")。
|
||||
| 场景 | 操作 |
|
||||
|---|---|
|
||||
| 排查 hello-halo 被谁改过 | 关键字输入 `hello-halo`,或点击任意该资源记录的「历史」;打开详情看字段 diff |
|
||||
| 登录爆破回溯 | 语义动作选「登录失败」:20 天前同一 IP `203.0.113.66` 的 6 次撞库;不带筛选时同 IP 还能看到升级前落库的「访问登录页」记录(灰色「—」,不计成败) |
|
||||
| 定时发布(系统内部变更) | 操作者输入 `system`,或资源类型选 `posts` + 关键字 `weekly-2026-w46` |
|
||||
| 插件生命周期 | 关键字 `plugin-link` / `plugin-search-widget`;语义动作可筛「升级」「启用」「卸载」 |
|
||||
| 误操作定位 | 关键字 `weekly-2026-w45`:1 天前的删除记录,详情含被删字段快照 |
|
||||
| 越权与异常 | 结果选「失败」:403 越权、404 资源不存在、500 发布异常 |
|
||||
| 登录失败告警 | 插件设置 → 填写 Webhook Secret 引用 → 启用并保存 → 「模拟 5 次登录失败」 |
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
demo/
|
||||
├── index.html # 页面骨架(Console 外壳 + 列表/设置/抽屉/弹窗)
|
||||
├── index.html # Console 外壳 + 列表/设置/详情抽屉/模拟器
|
||||
├── assets/
|
||||
│ ├── audit-core.js # 核心纯函数:捕获规则、资源解析、筛选、分页、保留期(UMD,浏览器/Node 共用)
|
||||
│ ├── mock-data.js # 模拟数据生成器(种子随机、确定性输出,约 142 条 + 故事线)
|
||||
│ ├── app.js # 交互层(渲染、事件、模拟管线)
|
||||
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components:#4ccba0 / #0e1731 / #d71d1d)
|
||||
│ ├── audit-core.js # 纯函数核心(UMD,浏览器/Node 共用):捕获、解析、语义动作、
|
||||
│ │ # 登录判定、字段 diff、八维筛选、CSV、告警窗口
|
||||
│ ├── mock-data.js # 种子随机模拟数据(约 141 条 + 7 条故事线,确定性输出)
|
||||
│ ├── app.js # 交互层(渲染、筛选、历史、导出、设置、告警、模拟管线)
|
||||
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components)
|
||||
└── test/
|
||||
└── audit-core.test.mjs # 单元测试(node:test,29 个用例)
|
||||
└── audit-core.test.mjs # 单元测试(node:test,61 个用例)
|
||||
```
|
||||
|
||||
## 运行测试
|
||||
@@ -66,18 +105,29 @@ demo/
|
||||
node --test demo/test/audit-core.test.mjs
|
||||
```
|
||||
|
||||
覆盖:捕获规则各分支(方法/路径/匿名/登录端点)、资源解析(集合/单资源/深层子资源/auth)、
|
||||
筛选(操作者/资源类型/动作/结果/时间范围/关键字)、分页越界收敛、保留期统计、模拟数据确定性与字段完整性。
|
||||
覆盖:捕获规则(HTTP / 认证操作 / 登录页 GET 不记录 / 匿名 / 读操作)、资源解析(含查询串与深层子资源)、
|
||||
语义动作推导与中文描述(含登录页访问纠正)、登录结果判定(2xx / 302 跳回登录页 / 缺失 Location / 401)、
|
||||
结果语义(登录失败 / 登录成功 / 页面访问不计成败)、
|
||||
字段 diff(PUT / PATCH Merge / PATCH JSON Patch / POST / DELETE、元数据过滤、敏感字段脱敏、
|
||||
截断、30 条封顶)、八维筛选(登录失败结果语义、时间闭区间、关键字)、分页与保留期、
|
||||
CSV(BOM / CRLF / 列顺序 / 转义 / 公式注入防护 / 升序)、告警窗口(阈值、告警后重开、
|
||||
成功清零、窗口过期)、模拟数据确定性与故事线完整性。
|
||||
|
||||
## 与真实实现的差异
|
||||
|
||||
| 项 | Demo | 真实插件 |
|
||||
|---|---|---|
|
||||
| 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 |
|
||||
| 捕获 | 手动在弹窗里"发送请求"模拟 | `AfterSecurityWebFilter` 自动捕获 |
|
||||
| 写入 | 直接 unshift 到数组 | `ReactiveExtensionClient` 异步直写、失败降级 |
|
||||
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL 缓存) |
|
||||
| 清理 | 点击按钮模拟 | 每日定时任务自动执行 |
|
||||
| 捕获 | 弹窗里手动构造请求 | 双过滤器自动捕获(`/apis/**` + 认证操作 `POST /login`、`POST /logout`) |
|
||||
| 字段 diff | 与 Java 版同规则的 JS 简化实现(对象递归、数组整体比较、脱敏/截断/封顶) | `ChangeDiffEngine`(含 Halo 服务端字段更细的降噪与 JSON Pointer 解析) |
|
||||
| 查询 | 前端数组筛选 | 自有查询端点(fieldSelector + 时间区间 + 模糊匹配) |
|
||||
| 导出 | 浏览器 Blob 下载 | 后端全量流式 CSV(分批 200 条) |
|
||||
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL) |
|
||||
| 告警 | 本地阈值窗口 + JSON 预览 | Webhook JSON POST + SSRF 防护 + Secret 存储地址 |
|
||||
| 系统变更 | 手动模拟 | `ReactiveExtensionClient.watch` 全局 Watcher |
|
||||
| 权限 | 未演示(本地即超管视角) | 角色模板 `role-template-audit-view`,仅 `get/list` |
|
||||
|
||||
UI 结构(筛选维度、列定义、详情字段、设置项)与真实插件将保持一致,确认交互合理后即可按技术方案里程碑 4 实现 Console 页面。
|
||||
静态演示页与真实 Console 页面(Vue 3)共享同一套展示语义(列定义、筛选维度、
|
||||
描述推导、结果徽标、字段变更展示),但真实页面源码在
|
||||
[`plugin-operation-audit/ui/src/views/`](../plugin-operation-audit/ui/src/views/),由 Halo
|
||||
Console 宿主渲染。
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
--warn-tint: rgba(217, 119, 6, 0.1);
|
||||
--info: #2563eb;
|
||||
--info-tint: rgba(37, 99, 235, 0.1);
|
||||
--purple: #7c3aed;
|
||||
--purple-tint: rgba(124, 58, 237, 0.1);
|
||||
--gray-50: #f9fafb;
|
||||
--gray-100: #f3f4f6;
|
||||
--gray-200: #e5e7eb;
|
||||
@@ -30,12 +32,16 @@
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body { height: 100%; }
|
||||
/* hidden 属性优先于组件的 display 声明(如 .alert-banner{display:flex}) */
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
html { height: 100%; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
min-width: 1080px;
|
||||
min-width: 1100px;
|
||||
font-size: 14px;
|
||||
color: var(--gray-900);
|
||||
background: var(--gray-100);
|
||||
@@ -165,6 +171,8 @@ body {
|
||||
|
||||
.readonly-hint { color: var(--primary-dark); }
|
||||
|
||||
.header-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
@@ -207,6 +215,13 @@ body {
|
||||
padding: 14px 18px 0;
|
||||
}
|
||||
|
||||
.card-sub {
|
||||
font-size: 12.5px;
|
||||
color: var(--gray-500);
|
||||
line-height: 1.6;
|
||||
padding: 6px 18px 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
appearance: none;
|
||||
border: none;
|
||||
@@ -219,12 +234,17 @@ body {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
transition: filter 0.15s, background 0.15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn svg {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
fill: currentColor;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.8;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
@@ -237,6 +257,8 @@ body {
|
||||
}
|
||||
.btn-outline:hover { border-color: var(--primary); color: var(--primary-dark); }
|
||||
|
||||
.btn-sm { padding: 6px 12px; font-size: 12.5px; }
|
||||
|
||||
.btn-link {
|
||||
appearance: none;
|
||||
border: none;
|
||||
@@ -244,10 +266,8 @@ body {
|
||||
color: var(--primary-dark);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
padding: 8px 4px;
|
||||
align-self: flex-end;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
|
||||
.btn-link:hover { text-decoration: underline; }
|
||||
|
||||
.icon-btn {
|
||||
@@ -262,8 +282,8 @@ body {
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.icon-btn:hover { background: var(--gray-100); color: var(--gray-900); }
|
||||
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; }
|
||||
|
||||
.input {
|
||||
border: 1px solid var(--gray-300);
|
||||
@@ -277,12 +297,13 @@ body {
|
||||
}
|
||||
|
||||
.input:focus,
|
||||
select:focus {
|
||||
select:focus,
|
||||
textarea:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 2px var(--primary-tint);
|
||||
}
|
||||
|
||||
select, .input { min-width: 0; }
|
||||
select, .input, textarea { min-width: 0; }
|
||||
|
||||
select {
|
||||
appearance: none;
|
||||
@@ -296,8 +317,21 @@ select {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
textarea {
|
||||
border: 1px solid var(--gray-300);
|
||||
border-radius: 6px;
|
||||
padding: 8px 10px;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
resize: vertical;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.hint { font-size: 12px; color: var(--gray-400); }
|
||||
.muted { color: var(--gray-400); font-size: 12px; }
|
||||
.mono { font-family: ui-monospace, Consolas, monospace; }
|
||||
.break-all { word-break: break-all; }
|
||||
|
||||
/* ============ 横幅 ============ */
|
||||
.banner {
|
||||
@@ -305,31 +339,64 @@ select {
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
margin-bottom: 14px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.banner-warn { background: var(--warn-tint); color: var(--warn); border: 1px solid rgba(217, 119, 6, 0.25); }
|
||||
.banner-danger { background: var(--danger-tint); color: var(--danger); border: 1px solid rgba(215, 29, 29, 0.25); }
|
||||
|
||||
.alert-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
.alert-banner-body { flex: 1; }
|
||||
.alert-banner-actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
.alert-banner-actions .btn-link { color: var(--danger); }
|
||||
|
||||
/* ============ 筛选栏 ============ */
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
.filter-card {
|
||||
padding: 12px 16px;
|
||||
margin-bottom: 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filter-item { display: flex; flex-direction: column; gap: 4px; }
|
||||
.filter-item.grow { flex: 1; min-width: 180px; }
|
||||
.filter-item label { font-size: 11px; color: var(--gray-500); font-weight: 600; }
|
||||
.filter-item select, .filter-item .input { min-width: 120px; width: 100%; }
|
||||
.filter-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, minmax(0, 1fr)) auto;
|
||||
gap: 10px 12px;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
/* ============ 表格 ============ */
|
||||
.filter-item { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.filter-item > span { font-size: 11px; color: var(--gray-500); font-weight: 600; white-space: nowrap; }
|
||||
.filter-item input,
|
||||
.filter-item select { width: 100%; height: 32px; font-size: 12.5px; }
|
||||
|
||||
.filter-actions { display: flex; gap: 8px; }
|
||||
|
||||
.filter-note {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px dashed var(--gray-200);
|
||||
font-size: 12px;
|
||||
color: var(--gray-500);
|
||||
}
|
||||
|
||||
/* ============ 列表 ============ */
|
||||
.table-card { overflow: hidden; }
|
||||
|
||||
.audit-list-wrap { overflow-x: auto; }
|
||||
|
||||
.audit-table {
|
||||
width: 100%;
|
||||
min-width: 900px;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
.audit-table th {
|
||||
@@ -337,17 +404,18 @@ select {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--gray-500);
|
||||
padding: 10px 16px;
|
||||
padding: 10px 14px;
|
||||
background: var(--gray-50);
|
||||
border-bottom: 1px solid var(--gray-200);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.audit-table td {
|
||||
padding: 10px 16px;
|
||||
padding: 9px 14px;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
font-size: 13px;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.audit-table tbody tr {
|
||||
@@ -356,20 +424,20 @@ select {
|
||||
}
|
||||
|
||||
.audit-table tbody tr:hover { background: var(--gray-50); }
|
||||
|
||||
.audit-table tbody tr.selected td { background: var(--primary-tint); }
|
||||
|
||||
@keyframes rowFlash {
|
||||
0% { background: var(--primary-tint); }
|
||||
100% { background: transparent; }
|
||||
}
|
||||
tr.row-new td { animation: rowFlash 2.8s ease-out; }
|
||||
|
||||
tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
.td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
|
||||
.td-time { color: var(--gray-700); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.cell-user { display: flex; align-items: center; gap: 8px; }
|
||||
.cell-user { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.user-lines { min-width: 0; }
|
||||
.u-name { font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.u-time { font-size: 11.5px; color: var(--gray-400); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
|
||||
/* 动作徽标 */
|
||||
.method {
|
||||
@@ -384,10 +452,17 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
.m-post { background: var(--info-tint); color: var(--info); }
|
||||
.m-put { background: var(--warn-tint); color: var(--warn); }
|
||||
.m-delete { background: var(--danger-tint); color: var(--danger); }
|
||||
.m-patch { background: rgba(124, 58, 237, 0.1); color: #6d28d9; }
|
||||
.m-patch { background: var(--purple-tint); color: var(--purple); }
|
||||
.m-get { background: var(--gray-100); color: var(--gray-500); }
|
||||
|
||||
/* 资源列 */
|
||||
.res-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rt {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
@@ -396,29 +471,66 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
background: var(--gray-100);
|
||||
border-radius: 4px;
|
||||
padding: 2px 7px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
.rn { color: var(--gray-500); font-size: 12.5px; word-break: break-all; }
|
||||
|
||||
/* 结果徽标 */
|
||||
.result {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.result i {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.result.ok { color: #16a34a; }
|
||||
.result.ok i { background: #16a34a; }
|
||||
.result.fail { color: var(--danger); }
|
||||
.result.fail i { background: var(--danger); }
|
||||
.rn {
|
||||
color: var(--gray-700);
|
||||
font-size: 12.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.history-link {
|
||||
flex-shrink: 0;
|
||||
font-size: 11.5px;
|
||||
color: var(--primary-dark);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.history-link:hover { text-decoration: underline; }
|
||||
.path-line {
|
||||
margin-top: 2px;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
font-size: 11px;
|
||||
color: var(--gray-400);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 描述列 */
|
||||
.action-desc {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
font-size: 12.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.changes-hint {
|
||||
display: inline-block;
|
||||
margin-left: 4px;
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
font-size: 10.5px;
|
||||
color: var(--warn);
|
||||
background: var(--warn-tint);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* 结果徽标 */
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 7px;
|
||||
border-radius: 4px;
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
}
|
||||
.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 {
|
||||
@@ -444,11 +556,11 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
|
||||
.pg-right { display: flex; align-items: center; gap: 8px; }
|
||||
.pg-right select { padding: 5px 24px 5px 8px; font-size: 12.5px; }
|
||||
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; }
|
||||
.pg-page { font-size: 12.5px; color: var(--gray-500); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* ============ 设置页 ============ */
|
||||
#panel-settings .settings-card { max-width: 780px; }
|
||||
.settings-card { margin-bottom: 16px; padding-bottom: 6px; }
|
||||
#panel-settings .settings-card { max-width: 820px; }
|
||||
.settings-card { margin-bottom: 16px; padding-bottom: 4px; }
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
@@ -459,11 +571,18 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
}
|
||||
|
||||
.setting-text { max-width: 640px; }
|
||||
.setting-text { max-width: 620px; }
|
||||
.s-name { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
|
||||
.s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.5; }
|
||||
.s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.55; }
|
||||
.s-desc code {
|
||||
background: var(--gray-100);
|
||||
border-radius: 4px;
|
||||
padding: 1px 5px;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.input.num { width: 90px; text-align: center; }
|
||||
.input.num { width: 96px; text-align: center; flex-shrink: 0; }
|
||||
.input.secret-input { width: 280px; flex-shrink: 0; }
|
||||
|
||||
.settings-actions {
|
||||
display: flex;
|
||||
@@ -480,7 +599,16 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
}
|
||||
.clean-stats .num-warn { color: var(--danger); font-weight: 600; }
|
||||
|
||||
.settings-card .btn { margin: 0 18px 16px; }
|
||||
.alert-preview {
|
||||
margin: 0 18px 16px;
|
||||
padding: 12px;
|
||||
background: var(--secondary);
|
||||
color: #d1fae5;
|
||||
border-radius: 6px;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.55;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* 开关 */
|
||||
.switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; }
|
||||
@@ -525,7 +653,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.avatar.sm { width: 22px; height: 22px; font-size: 10px; }
|
||||
.avatar.sm { width: 24px; height: 24px; font-size: 11px; }
|
||||
|
||||
.c-a { background: #4ccba0; }
|
||||
.c-b { background: #6366f1; }
|
||||
@@ -545,8 +673,8 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 440px;
|
||||
max-width: 92vw;
|
||||
width: 480px;
|
||||
max-width: 94vw;
|
||||
height: 100vh;
|
||||
background: #fff;
|
||||
z-index: 50;
|
||||
@@ -571,7 +699,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
}
|
||||
|
||||
.drawer-title { font-size: 16px; font-weight: 700; }
|
||||
.drawer-sub { font-size: 12px; color: var(--gray-400); margin-top: 3px; font-family: ui-monospace, Consolas, monospace; }
|
||||
.drawer-sub {
|
||||
font-size: 11.5px;
|
||||
color: var(--gray-400);
|
||||
margin-top: 3px;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.readonly-banner {
|
||||
background: var(--primary-tint);
|
||||
@@ -586,24 +720,26 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
.detail-list { margin: 0; }
|
||||
|
||||
.detail-list .d-row {
|
||||
padding: 9px 0;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px dashed var(--gray-200);
|
||||
}
|
||||
|
||||
.detail-list dt {
|
||||
font-size: 11.5px;
|
||||
flex: 0 0 5.5rem;
|
||||
font-size: 12px;
|
||||
color: var(--gray-500);
|
||||
font-weight: 600;
|
||||
margin-bottom: 5px;
|
||||
padding-top: 1px;
|
||||
}
|
||||
|
||||
.detail-list dd {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-size: 12.5px;
|
||||
word-break: break-all;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.path-code {
|
||||
@@ -617,9 +753,48 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.ua { font-size: 12px; color: var(--gray-500); line-height: 1.6; }
|
||||
.ua { font-size: 11.5px; color: var(--gray-500); line-height: 1.6; }
|
||||
|
||||
.raw-json { margin-top: 16px; }
|
||||
.changes { margin-top: 18px; }
|
||||
.changes-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--gray-900);
|
||||
margin: 0 0 6px;
|
||||
}
|
||||
.change-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px dashed var(--gray-200);
|
||||
}
|
||||
.change-badge {
|
||||
flex: 0 0 auto;
|
||||
align-self: flex-start;
|
||||
margin-top: 1px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.change-added { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
|
||||
.change-updated { color: var(--warn); background: var(--warn-tint); }
|
||||
.change-removed { color: var(--danger); background: var(--danger-tint); }
|
||||
.change-body { flex: 1; min-width: 0; }
|
||||
.change-field { font-size: 12px; color: var(--gray-900); word-break: break-all; }
|
||||
.change-values {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--gray-700);
|
||||
}
|
||||
.change-old { color: var(--danger); text-decoration: line-through; }
|
||||
.change-arrow { color: var(--gray-400); flex-shrink: 0; }
|
||||
|
||||
.raw-json { margin-top: 18px; }
|
||||
.raw-json summary {
|
||||
font-size: 12.5px;
|
||||
color: var(--gray-500);
|
||||
@@ -631,11 +806,12 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
.raw-json pre {
|
||||
background: var(--secondary);
|
||||
color: #d1fae5;
|
||||
font-size: 11.5px;
|
||||
font-size: 11px;
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
overflow-x: auto;
|
||||
line-height: 1.6;
|
||||
max-height: 320px;
|
||||
}
|
||||
|
||||
/* ============ 模拟操作弹窗 ============ */
|
||||
@@ -644,8 +820,10 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 520px;
|
||||
max-width: 92vw;
|
||||
width: 680px;
|
||||
max-width: 94vw;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border-radius: 10px;
|
||||
z-index: 50;
|
||||
@@ -656,7 +834,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
.modal[hidden] { display: none; }
|
||||
|
||||
@keyframes popIn {
|
||||
from { transform: translate(-50%, -50%) scale(0.96); opacity: 0; }
|
||||
from { transform: translate(-50%, -50%) scale(0.97); opacity: 0; }
|
||||
to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
|
||||
}
|
||||
|
||||
@@ -674,7 +852,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
font-size: 12.5px;
|
||||
color: var(--gray-500);
|
||||
line-height: 1.6;
|
||||
margin: 8px 0 14px;
|
||||
margin: 8px 0 12px;
|
||||
}
|
||||
|
||||
.modal-sub code {
|
||||
@@ -684,9 +862,35 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; }
|
||||
.seg-tabs {
|
||||
display: inline-flex;
|
||||
background: var(--gray-100);
|
||||
border-radius: 7px;
|
||||
padding: 3px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.seg-tab {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 6px 14px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
color: var(--gray-500);
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.seg-tab.active {
|
||||
background: #fff;
|
||||
color: var(--gray-900);
|
||||
font-weight: 600;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; min-width: 0; }
|
||||
.field label { font-size: 12px; color: var(--gray-500); font-weight: 600; }
|
||||
.field select, .field .input { width: 100%; }
|
||||
.field textarea { width: 100%; }
|
||||
|
||||
.field-row { display: flex; gap: 12px; }
|
||||
|
||||
@@ -710,7 +914,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
/* 弹窗内容超高时操作按钮始终可见 */
|
||||
position: sticky;
|
||||
bottom: -20px;
|
||||
margin: 6px -22px -20px;
|
||||
padding: 12px 22px 20px;
|
||||
border-top: 1px solid var(--gray-100);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ============ Toast ============ */
|
||||
@@ -729,9 +939,30 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
|
||||
pointer-events: none;
|
||||
transition: opacity 0.25s, transform 0.25s;
|
||||
z-index: 100;
|
||||
max-width: 60vw;
|
||||
max-width: 70vw;
|
||||
}
|
||||
|
||||
.toast.show { opacity: 1; transform: translate(-50%, 0); }
|
||||
.toast.ok { background: var(--primary-dark); }
|
||||
.toast.warn { background: #92400e; }
|
||||
|
||||
/* ============ 响应式(演示页以桌面为主,窄屏保证可用) ============ */
|
||||
@media (max-width: 1400px) {
|
||||
.filter-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.filter-actions { grid-column: 1 / -1; }
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
body { min-width: 900px; }
|
||||
.page-header { flex-direction: column; }
|
||||
.header-actions { align-self: flex-end; }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
body { min-width: 0; }
|
||||
.sidebar { display: none; }
|
||||
.main { padding: 16px 14px 32px; }
|
||||
.filter-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.field-row { flex-direction: column; gap: 0; }
|
||||
.modal { width: 94vw; }
|
||||
}
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
/**
|
||||
* 操作审计 · 模拟数据生成器(种子随机,确定性输出)
|
||||
*
|
||||
* 记录字段与产品设计 4.1 表格一一对应;resourceType/resourceName 通过
|
||||
* AuditCore.resolveResource 从路径解析得出(模拟真实捕获管线)。
|
||||
* 内置若干"故事线"数据:登录爆破、越权 403、服务端 500 等,便于验证筛选场景。
|
||||
* 记录字段与插件 spec 一致:username / attemptedUsername / method / action /
|
||||
* resourceType / resourceName / path / statusCode / remoteIp / userAgent / changes。
|
||||
* 资源解析、语义动作、登录结果与字段 diff 全部经 AuditCore 按真实捕获管线推导,
|
||||
* 便于在演示页复现「谁改了什么」而不仅是「谁点了什么」。
|
||||
*
|
||||
* 内置故事线(固定时间锚点,可直接按演示页提示复现):
|
||||
* 1. 排查「hello-halo 这篇文章谁改过」(多用户多次编辑,含字段 diff)
|
||||
* 2. 登录爆破回溯(同一 IP、无差别撞库;另含升级前落库的登录页访问记录)
|
||||
* 3. 忘记密码后登录成功(失败 → 成功清零)
|
||||
* 4. 定时发布(系统内部变更,执行者「系统」、无 IP/UA)
|
||||
* 5. 插件生命周期(升级 / 停用 / 卸载,含字段 diff)
|
||||
* 6. 越权与异常(403 / 404 / 500)
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) {
|
||||
@@ -16,7 +25,7 @@
|
||||
|
||||
var DAY = 86400000;
|
||||
var MIN = 60000;
|
||||
var BASE_COUNT = 128; // 随机生成的基础记录条数
|
||||
var BASE_COUNT = 116;
|
||||
|
||||
// ---------- 种子随机 ----------
|
||||
function mulberry32(seed) {
|
||||
@@ -38,10 +47,17 @@
|
||||
function hex(r, n) {
|
||||
var s = '';
|
||||
var chars = '0123456789abcdef';
|
||||
for (var i = 0; i < n; i++) s += chars[rint(r, 0, 15)];
|
||||
for (var i = 0; i < n; i++) {
|
||||
s += chars[rint(r, 0, 15)];
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** 演示用的一次性假口令(运行时生成,非真实凭据;仅用于验证敏感字段脱敏)。 */
|
||||
function demoSecret(r) {
|
||||
return 'demo-only-' + hex(r, 12);
|
||||
}
|
||||
|
||||
// ---------- 基础素材 ----------
|
||||
var UAS = {
|
||||
chrome: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.2151.97 Safari/537.36',
|
||||
@@ -52,156 +68,637 @@
|
||||
};
|
||||
|
||||
var USERS = {
|
||||
'guichumo': { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] },
|
||||
guichumo: { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] },
|
||||
'editor.zhang': { ips: ['116.24.65.201'], uas: ['edge', 'firefox'] },
|
||||
'writer.li': { ips: ['120.79.10.45'], uas: ['safari', 'chrome'] }
|
||||
};
|
||||
|
||||
var SLUGS = ['hello-halo', 'self-host-guide', 'weekly-2026-w46', 'reading-notes-11', 'plugin-dev-diary', 'spring-festival-2026'];
|
||||
var PLUGINS = ['plugin-search-widget', 'plugin-comment-widget', 'plugin-sitemap', 'plugin-links'];
|
||||
|
||||
function postPath(r) { return '/apis/content.halo.run/v1alpha1/posts/' + pick(r, SLUGS); }
|
||||
function publishPath(r) { return '/apis/api.content.halo.run/v1alpha1/posts/' + pick(r, SLUGS) + '/publish'; }
|
||||
function commentPath(r) { return '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6); }
|
||||
function approvePath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'; }
|
||||
function replyPath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply'; }
|
||||
function attachPath(r) { return '/apis/storage.halo.run/v1alpha1/attachments/attachment-' + hex(r, 6); }
|
||||
|
||||
// [权重, 操作者, 方法, 路径函数, 状态码]
|
||||
var ACTIONS = [
|
||||
[16, 'guichumo', 'PUT', postPath, 200],
|
||||
[10, 'guichumo', 'POST', publishPath, 200],
|
||||
[6, 'guichumo', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
|
||||
[5, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/configmaps/system'; }, 200],
|
||||
[4, 'guichumo', 'PUT', function (r) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + pick(r, PLUGINS); }, 200],
|
||||
[4, 'guichumo', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
|
||||
[4, 'guichumo', 'DELETE', attachPath, 204],
|
||||
[3, 'guichumo', 'DELETE', commentPath, 204],
|
||||
[3, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/roles/role-template-editor'; }, 200],
|
||||
[2, 'guichumo', 'POST', function () { return '/login'; }, 200],
|
||||
[2, 'guichumo', 'POST', function () { return '/logout'; }, 200],
|
||||
[12, 'editor.zhang', 'PUT', postPath, 200],
|
||||
[6, 'editor.zhang', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
|
||||
[2, 'editor.zhang', 'POST', function () { return '/login'; }, 200],
|
||||
[2, 'editor.zhang', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
|
||||
[8, 'writer.li', 'PUT', postPath, 200],
|
||||
[6, 'writer.li', 'POST', approvePath, 200],
|
||||
[3, 'writer.li', 'POST', replyPath, 200],
|
||||
[2, 'writer.li', 'POST', function () { return '/login'; }, 200]
|
||||
var POSTS = [
|
||||
{ name: 'hello-halo', title: '你好,Halo', summary: '从零开始搭建自己的写作空间。' },
|
||||
{ name: 'self-host-guide', title: '自托管指南', summary: '用 Docker 部署 Halo 的完整步骤。' },
|
||||
{ name: 'reading-notes-11', title: '读书笔记 #11', summary: '本周读完的三本书。' },
|
||||
{ name: 'plugin-dev-diary', title: '插件开发日志', summary: '从脚手架到上架。' },
|
||||
{ name: 'weekly-2026-w46', title: '每周摘要 · 2026 W46', summary: '站点一周动态。' },
|
||||
{ name: 'spring-festival-2026', title: '春节计划', summary: '假期更新安排。' }
|
||||
];
|
||||
|
||||
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, a) { return sum + a[0]; }, 0);
|
||||
var PLUGINS = [
|
||||
{ name: 'plugin-search-widget', displayName: '搜索组件', version: { old: '1.2.0', next: '1.3.0' } },
|
||||
{ name: 'plugin-comment-widget', displayName: '评论组件', version: { old: '1.5.0', next: '1.6.0' } },
|
||||
{ name: 'plugin-sitemap', displayName: 'Sitemap', version: { old: '1.0.4', next: '1.0.5' } },
|
||||
{ name: 'plugin-links', displayName: '友情链接', version: { old: '2.1.1', next: '2.2.0' } }
|
||||
];
|
||||
|
||||
function userCtx(r, name) {
|
||||
var u = USERS[name];
|
||||
// ---------- 文档快照(diff 用,结构贴近 Halo 扩展模型)----------
|
||||
function postDoc(entry, patch) {
|
||||
var spec = {
|
||||
title: entry.title,
|
||||
slug: entry.name,
|
||||
visible: 'PUBLIC',
|
||||
publish: true,
|
||||
pinned: false,
|
||||
allowComment: true,
|
||||
summary: entry.summary
|
||||
};
|
||||
Object.keys(patch || {}).forEach(function (key) {
|
||||
spec[key] = patch[key];
|
||||
});
|
||||
return {
|
||||
username: name,
|
||||
remoteIp: pick(r, u.ips),
|
||||
userAgent: UAS[pick(r, u.uas)]
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Post',
|
||||
metadata: {
|
||||
name: entry.name,
|
||||
labels: { 'content.halo.run/pinned': 'false' },
|
||||
annotations: { 'content.halo.run/permalink-pattern': '/archives/:slug' },
|
||||
version: 128,
|
||||
creationTimestamp: '2026-10-01T08:00:00Z'
|
||||
},
|
||||
spec: spec,
|
||||
status: { phase: 'PUBLISHED', permalink: '/archives/' + entry.name }
|
||||
};
|
||||
}
|
||||
|
||||
function rec(timestamp, username, method, path, statusCode, remoteIp, userAgent) {
|
||||
var res = AuditCore.resolveResource(path);
|
||||
function commentDoc(name, approved) {
|
||||
return {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Comment',
|
||||
metadata: { name: name, version: 7 },
|
||||
spec: {
|
||||
raw: '写得很好,收藏了。',
|
||||
owner: { displayName: '访客' + name.slice(-4), kind: 'Email' },
|
||||
approved: approved,
|
||||
hidden: false,
|
||||
allowNotification: true
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function pluginDoc(plugin, enabled, version) {
|
||||
return {
|
||||
apiVersion: 'plugin.halo.run/v1alpha1',
|
||||
kind: 'Plugin',
|
||||
metadata: { name: plugin.name, labels: { 'plugin.halo.run/plugin-name': plugin.name } },
|
||||
spec: {
|
||||
displayName: plugin.displayName,
|
||||
version: version,
|
||||
enabled: enabled,
|
||||
author: { name: 'halo-sigs' },
|
||||
requires: '>=2.20.0'
|
||||
},
|
||||
status: { phase: enabled ? 'STARTED' : 'DISABLED' }
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- 记录组装 ----------
|
||||
function recCtx(r, username) {
|
||||
var u = USERS[username] || USERS.guichumo;
|
||||
return {
|
||||
id: null,
|
||||
timestamp: timestamp,
|
||||
username: username,
|
||||
method: AuditCore.normalizeMethod(method),
|
||||
path: path,
|
||||
resourceType: res.resourceType,
|
||||
resourceName: res.resourceName,
|
||||
statusCode: statusCode,
|
||||
remoteIp: remoteIp,
|
||||
userAgent: userAgent
|
||||
remoteIp: pick(r, u.ips),
|
||||
userAgent: UAS[pick(r, u.uas)],
|
||||
authenticated: true
|
||||
};
|
||||
}
|
||||
|
||||
function make(overrides) {
|
||||
return AuditCore.buildRecord(Object.assign({
|
||||
statusCode: 200,
|
||||
authenticated: true,
|
||||
recordChanges: true
|
||||
}, overrides));
|
||||
}
|
||||
|
||||
function postPath(name) { return '/apis/content.halo.run/v1alpha1/posts/' + name; }
|
||||
function postsPath() { return '/apis/content.halo.run/v1alpha1/posts'; }
|
||||
function commentPath(name) { return '/apis/content.halo.run/v1alpha1/comments/' + name; }
|
||||
function pluginPath(name) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + name; }
|
||||
|
||||
/**
|
||||
* 基础操作集:[权重, 构造函数(r) → 记录输入]
|
||||
* 每次构造经过 buildRecord:资源解析、语义动作、登录结果、字段 diff 与插件一致。
|
||||
*/
|
||||
var ACTIONS = [
|
||||
[16, function (r) {
|
||||
var entry = pick(r, POSTS);
|
||||
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang', 'writer.li']));
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: postPath(entry.name),
|
||||
previous: postDoc(entry),
|
||||
body: postDoc(entry, {
|
||||
title: entry.title + '(修订)',
|
||||
summary: entry.summary + ' 已补充示例。'
|
||||
})
|
||||
});
|
||||
}],
|
||||
[9, function (r) {
|
||||
var entry = pick(r, POSTS);
|
||||
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang']));
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: postPath(entry.name) + '/publish'
|
||||
});
|
||||
}],
|
||||
[7, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
var slug = 'draft-' + hex(r, 5);
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: postsPath(),
|
||||
statusCode: 201,
|
||||
body: {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Post',
|
||||
metadata: { name: slug },
|
||||
spec: { title: '草稿 · ' + slug, slug: slug, visible: 'PUBLIC', publish: false }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[6, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
|
||||
previous: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'ConfigMap',
|
||||
metadata: { name: 'system', version: 9 },
|
||||
data: { theme: 'theme-earth', locale: 'zh-CN' }
|
||||
},
|
||||
body: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'ConfigMap',
|
||||
metadata: { name: 'system', version: 10 },
|
||||
data: { theme: 'theme-earth', locale: 'zh-CN', 'site.title': '青竹小站' }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[5, function (r) {
|
||||
var plugin = pick(r, PLUGINS);
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: pluginPath(plugin.name) + '/activation',
|
||||
previous: pluginDoc(plugin, false, plugin.version.old),
|
||||
body: pluginDoc(plugin, true, plugin.version.old)
|
||||
});
|
||||
}],
|
||||
[5, function (r) {
|
||||
var ctx = recCtx(r, pick(r, ['editor.zhang', 'writer.li']));
|
||||
var name = 'attachment-' + hex(r, 6);
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/storage.halo.run/v1alpha1/attachments',
|
||||
statusCode: 201,
|
||||
body: {
|
||||
apiVersion: 'storage.halo.run/v1alpha1',
|
||||
kind: 'Attachment',
|
||||
metadata: { name: name },
|
||||
spec: { displayName: 'cover-' + hex(r, 4) + '.png', mediaType: 'image/png', size: rint(r, 80, 640) * 1024 }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[3, function (r) {
|
||||
var ctx = recCtx(r, 'editor.zhang');
|
||||
var name = 'attachment-' + hex(r, 6);
|
||||
return Object.assign(ctx, {
|
||||
method: 'DELETE',
|
||||
path: '/apis/storage.halo.run/v1alpha1/attachments/' + name,
|
||||
statusCode: 204,
|
||||
previous: {
|
||||
apiVersion: 'storage.halo.run/v1alpha1',
|
||||
kind: 'Attachment',
|
||||
metadata: { name: name },
|
||||
spec: { displayName: 'old-cover.png', mediaType: 'image/png', size: 245760 }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[4, function (r) {
|
||||
var ctx = recCtx(r, 'writer.li');
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply',
|
||||
body: {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Reply',
|
||||
metadata: { name: 'reply-' + hex(r, 4) },
|
||||
spec: { raw: '感谢支持,已更新示例。', quoteReply: 'comment-' + hex(r, 4) }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[3, function (r) {
|
||||
var ctx = recCtx(r, 'editor.zhang');
|
||||
var name = 'comment-' + hex(r, 6);
|
||||
return Object.assign(ctx, {
|
||||
method: 'DELETE',
|
||||
path: commentPath(name),
|
||||
statusCode: 204,
|
||||
previous: commentDoc(name, true)
|
||||
});
|
||||
}],
|
||||
[3, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/roles/role-template-editor',
|
||||
previous: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'Role',
|
||||
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
|
||||
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update'] }]
|
||||
},
|
||||
body: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'Role',
|
||||
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
|
||||
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update', 'delete'] }]
|
||||
}
|
||||
});
|
||||
}],
|
||||
[2, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/users',
|
||||
statusCode: 201,
|
||||
body: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'User',
|
||||
metadata: { name: 'alice-' + hex(r, 4) },
|
||||
spec: {
|
||||
displayName: 'Alice',
|
||||
email: 'alice-' + hex(r, 3) + '@example.com',
|
||||
// 运行时生成的假口令:用于验证 spec.password 在 diff 中被脱敏
|
||||
password: demoSecret(r),
|
||||
roles: ['role-template-author']
|
||||
}
|
||||
}
|
||||
});
|
||||
}],
|
||||
[2, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/users/guichumo/password',
|
||||
previous: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'User',
|
||||
metadata: { name: 'guichumo' },
|
||||
spec: { password: demoSecret(r) }
|
||||
},
|
||||
body: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'User',
|
||||
metadata: { name: 'guichumo' },
|
||||
spec: { password: demoSecret(r) }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[2, function (r) {
|
||||
var ctx = recCtx(r, 'writer.li');
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'
|
||||
});
|
||||
}],
|
||||
[2, function (r) {
|
||||
var ctx = recCtx(r, 'editor.zhang');
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/categories',
|
||||
statusCode: 201,
|
||||
body: {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Category',
|
||||
metadata: { name: 'category-' + hex(r, 4) },
|
||||
spec: { displayName: '技术随笔', slug: 'tech-notes', priority: 10 }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[2, function (r) {
|
||||
var ctx = recCtx(r, 'editor.zhang');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/theme.halo.run/v1alpha1/themes/theme-earth/activation'
|
||||
});
|
||||
}],
|
||||
[1, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/api.halo.run/v1alpha1/settings/basic'
|
||||
});
|
||||
}],
|
||||
[1, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'POST',
|
||||
path: '/apis/api.halo.run/v1alpha1/tags',
|
||||
statusCode: 201,
|
||||
body: {
|
||||
apiVersion: 'content.halo.run/v1alpha1',
|
||||
kind: 'Tag',
|
||||
metadata: { name: 'tag-' + hex(r, 4) },
|
||||
spec: { displayName: 'Halo', slug: 'halo' }
|
||||
}
|
||||
});
|
||||
}],
|
||||
[1, function (r) {
|
||||
var ctx = recCtx(r, 'guichumo');
|
||||
return Object.assign(ctx, {
|
||||
method: 'PUT',
|
||||
path: '/apis/api.halo.run/v1alpha1/menus/menu-primary',
|
||||
previous: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'Menu',
|
||||
metadata: { name: 'menu-primary' },
|
||||
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories'] }
|
||||
},
|
||||
body: {
|
||||
apiVersion: 'v1alpha1',
|
||||
kind: 'Menu',
|
||||
metadata: { name: 'menu-primary' },
|
||||
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories', '/about'] }
|
||||
}
|
||||
});
|
||||
}]
|
||||
];
|
||||
|
||||
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, item) { return sum + item[0]; }, 0);
|
||||
|
||||
/**
|
||||
* 生成模拟审计日志(按时间倒序,id 从旧到新递增)
|
||||
* @param {number} [now] 当前时间戳(默认 Date.now()),测试传固定值保证确定性
|
||||
* @returns {Array}
|
||||
*/
|
||||
function generateLogs(now) {
|
||||
if (typeof now !== 'number') now = Date.now();
|
||||
var r = mulberry32(20261121);
|
||||
if (typeof now !== 'number') {
|
||||
now = Date.now();
|
||||
}
|
||||
var r = mulberry32(20261122);
|
||||
var logs = [];
|
||||
|
||||
// 基础记录:均匀散布在近 90 天
|
||||
function add(record) {
|
||||
logs.push(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
// ---- 基础记录:均匀散布在近 90 天 ----
|
||||
for (var i = 0; i < BASE_COUNT; i++) {
|
||||
var roll = r() * TOTAL_WEIGHT;
|
||||
var action = ACTIONS[0];
|
||||
var action = ACTIONS[0][1];
|
||||
for (var j = 0; j < ACTIONS.length; j++) {
|
||||
roll -= ACTIONS[j][0];
|
||||
if (roll <= 0) { action = ACTIONS[j]; break; }
|
||||
if (roll <= 0) {
|
||||
action = ACTIONS[j][1];
|
||||
break;
|
||||
}
|
||||
var ctx = userCtx(r, action[1]);
|
||||
var time = now - rint(r, 5 * MIN, 90 * DAY);
|
||||
logs.push(rec(
|
||||
new Date(time).toISOString(), ctx.username,
|
||||
action[2], action[3](r), action[4],
|
||||
ctx.remoteIp, ctx.userAgent
|
||||
));
|
||||
}
|
||||
var input = action(r);
|
||||
input.timestamp = new Date(now - rint(r, 5 * MIN, 90 * DAY)).toISOString();
|
||||
add(make(input));
|
||||
}
|
||||
|
||||
// ---- 故事线(固定时间锚点)----
|
||||
// ---- 故事线 1:排查「hello-halo 这篇文章谁改过」 ----
|
||||
var hello = POSTS[0];
|
||||
add(make({
|
||||
username: 'editor.zhang',
|
||||
remoteIp: '116.24.65.201',
|
||||
userAgent: UAS.edge,
|
||||
method: 'PUT',
|
||||
path: postPath(hello.name),
|
||||
timestamp: new Date(now - 6 * DAY - 3 * 3600 * 1000).toISOString(),
|
||||
previous: postDoc(hello),
|
||||
body: postDoc(hello, { title: '你好,Halo(补充开箱截图)', summary: '从零开始搭建自己的写作空间,附开箱截图。' })
|
||||
}));
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'PUT',
|
||||
path: postPath(hello.name),
|
||||
timestamp: new Date(now - 2 * DAY - 5 * 3600 * 1000).toISOString(),
|
||||
previous: postDoc(hello, { title: '你好,Halo(补充开箱截图)' }),
|
||||
body: postDoc(hello, { title: '你好,Halo', summary: '从零开始搭建自己的写作空间。', visible: 'PRIVATE' })
|
||||
}));
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'PUT',
|
||||
path: postPath(hello.name),
|
||||
timestamp: new Date(now - 2 * DAY - 2 * 3600 * 1000).toISOString(),
|
||||
previous: postDoc(hello, { visible: 'PRIVATE' }),
|
||||
body: postDoc(hello, { visible: 'PUBLIC', pinned: true })
|
||||
}));
|
||||
|
||||
// 1. 攻击者爆破登录:20 天前,同一 IP 6 次失败,UA 为 python-requests
|
||||
var burstBase = now - 20 * DAY - 3600 * 1000 * 3; // 约 20 天前的凌晨
|
||||
[0, 41, 88, 135, 210, 400].forEach(function (off) {
|
||||
logs.push(rec(
|
||||
new Date(burstBase + off * 1000).toISOString(), '未知用户',
|
||||
'POST', '/login', 401, '203.0.113.66', UAS.bot
|
||||
));
|
||||
// ---- 故事线 2:登录爆破回溯(同一 IP、无差别撞库 + 升级前的登录页访问记录) ----
|
||||
var burstBase = now - 20 * DAY - 3 * 3600 * 1000;
|
||||
var attackAccounts = ['admin', 'root', 'oracle', 'test', 'admin', 'postgres'];
|
||||
attackAccounts.forEach(function (account, idx) {
|
||||
add(make({
|
||||
method: 'POST',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
location: '/login?error=invalid-credential&method=form',
|
||||
attemptedUsername: account,
|
||||
remoteIp: '203.0.113.66',
|
||||
userAgent: UAS.bot,
|
||||
timestamp: new Date(burstBase + [0, 41, 88, 135, 210, 400][idx] * 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);
|
||||
});
|
||||
|
||||
// 2. 站长忘记密码:12 天前输错两次后登录成功
|
||||
var b2 = now - 12 * DAY - 3600 * 1000 * 10;
|
||||
[[0, 401], [97, 401], [180, 200]].forEach(function (pair) {
|
||||
var ctx = { remoteIp: '192.168.1.23', userAgent: UAS.chrome };
|
||||
logs.push(rec(
|
||||
new Date(b2 + pair[0] * 1000).toISOString(),
|
||||
pair[1] === 200 ? 'guichumo' : '未知用户',
|
||||
'POST', '/login', pair[1], ctx.remoteIp, ctx.userAgent
|
||||
));
|
||||
// ---- 故事线 3:忘记密码(失败两次后成功) ----
|
||||
var retryBase = now - 12 * DAY - 10 * 3600 * 1000;
|
||||
[
|
||||
{ at: 0, account: 'guichumo', ok: false },
|
||||
{ at: 97, account: 'guichumo', ok: false },
|
||||
{ at: 180, account: 'guichumo', ok: true }
|
||||
].forEach(function (step) {
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
method: 'POST',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
location: step.ok ? '/uc' : '/login?error=bad-credentials&method=form',
|
||||
attemptedUsername: step.account,
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
timestamp: new Date(retryBase + step.at * 1000).toISOString()
|
||||
}));
|
||||
});
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
method: 'POST',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
location: '/challenges/two-factor/totp',
|
||||
attemptedUsername: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
timestamp: new Date(now - 9 * DAY - 8 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
method: 'POST',
|
||||
path: '/logout',
|
||||
statusCode: 302,
|
||||
location: '/login?logout',
|
||||
remoteIp: '192.168.1.23',
|
||||
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);
|
||||
|
||||
// 3. 越权尝试:8 天前 editor.zhang 尝试修改系统设置被拒绝
|
||||
logs.push(rec(
|
||||
new Date(now - 8 * DAY - 3600 * 1000 * 14).toISOString(), 'editor.zhang',
|
||||
'PUT', '/apis/v1alpha1/configmaps/system', 403, '116.24.65.201', UAS.edge
|
||||
));
|
||||
// ---- 故事线 4:定时发布(系统内部变更:无 IP/UA,执行者「系统」) ----
|
||||
add(AuditCore.buildSystemRecord({
|
||||
id: 'auditlog-system-0001',
|
||||
timestamp: new Date(now - DAY - 5 * 3600 * 1000).toISOString(),
|
||||
method: 'PUT',
|
||||
resourceType: 'posts',
|
||||
resourceName: 'weekly-2026-w46',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w46',
|
||||
changes: [
|
||||
{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' },
|
||||
{ field: 'spec.publishTime', changeType: 'ADDED', oldValue: null, newValue: '2026-11-21T02:00:00Z' }
|
||||
]
|
||||
}));
|
||||
add(AuditCore.buildSystemRecord({
|
||||
id: 'auditlog-system-0002',
|
||||
timestamp: new Date(now - 3 * DAY - 4 * 3600 * 1000).toISOString(),
|
||||
method: 'DELETE',
|
||||
resourceType: 'posts',
|
||||
resourceName: 'draft-night-notes',
|
||||
path: '/apis/content.halo.run/v1alpha1/posts/draft-night-notes',
|
||||
changes: [
|
||||
{ field: 'spec.title', changeType: 'REMOVED', oldValue: '夜间随笔(未发布)', newValue: null },
|
||||
{ field: 'metadata.name', changeType: 'REMOVED', oldValue: 'draft-night-notes', newValue: null }
|
||||
]
|
||||
}));
|
||||
|
||||
// 4. 权限不足:5 天前 writer.li 尝试删除评论被拒绝
|
||||
logs.push(rec(
|
||||
new Date(now - 5 * DAY - 3600 * 1000 * 9).toISOString(), 'writer.li',
|
||||
'DELETE', '/apis/content.halo.run/v1alpha1/comments/comment-a3f802', 403, '120.79.10.45', UAS.safari
|
||||
));
|
||||
// ---- 故事线 5:插件生命周期(升级 / 停用 / 卸载) ----
|
||||
var search = PLUGINS[0];
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'PUT',
|
||||
path: pluginPath(search.name) + '/upgrade',
|
||||
previous: pluginDoc(search, true, search.version.old),
|
||||
body: pluginDoc(search, true, search.version.next),
|
||||
timestamp: new Date(now - 7 * DAY - 6 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'PUT',
|
||||
path: pluginPath(search.name) + '/activation',
|
||||
previous: pluginDoc(search, true, search.version.next),
|
||||
body: pluginDoc(search, false, search.version.next),
|
||||
timestamp: new Date(now - 6 * DAY - 9 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
var links = PLUGINS[3];
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '116.24.65.187',
|
||||
userAgent: UAS.edge,
|
||||
method: 'DELETE',
|
||||
path: pluginPath(links.name) + '/uninstall',
|
||||
statusCode: 204,
|
||||
previous: pluginDoc(links, true, links.version.next),
|
||||
timestamp: new Date(now - 1 * DAY - 7 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
|
||||
// 5. 资源不存在:3 天前删除一个已不存在的附件
|
||||
logs.push(rec(
|
||||
new Date(now - 3 * DAY - 3600 * 1000 * 20).toISOString(), 'guichumo',
|
||||
'DELETE', '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42', 404, '192.168.1.23', UAS.chrome
|
||||
));
|
||||
// ---- 故事线 6:越权与异常 ----
|
||||
add(make({
|
||||
username: 'editor.zhang',
|
||||
remoteIp: '116.24.65.201',
|
||||
userAgent: UAS.edge,
|
||||
method: 'PUT',
|
||||
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
|
||||
statusCode: 403,
|
||||
timestamp: new Date(now - 8 * DAY - 14 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
add(make({
|
||||
username: 'writer.li',
|
||||
remoteIp: '120.79.10.45',
|
||||
userAgent: UAS.safari,
|
||||
method: 'DELETE',
|
||||
path: commentPath('comment-a3f802'),
|
||||
statusCode: 403,
|
||||
timestamp: new Date(now - 5 * DAY - 9 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'DELETE',
|
||||
path: '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42',
|
||||
statusCode: 404,
|
||||
timestamp: new Date(now - 3 * DAY - 20 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
add(make({
|
||||
username: 'writer.li',
|
||||
remoteIp: '120.79.10.45',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'POST',
|
||||
path: '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish',
|
||||
statusCode: 500,
|
||||
timestamp: new Date(now - 2 * DAY - 6 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
|
||||
// 6. 服务端异常:2 天前发布文章返回 500
|
||||
logs.push(rec(
|
||||
new Date(now - 2 * DAY - 3600 * 1000 * 6).toISOString(), 'writer.li',
|
||||
'POST', '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish', 500, '120.79.10.45', UAS.chrome
|
||||
));
|
||||
// ---- 故事线 7:误操作定位(删除文章,含字段 diff) ----
|
||||
var deleted = { name: 'weekly-2026-w45', title: '每周摘要 · 2026 W45', summary: '站点一周动态。' };
|
||||
add(make({
|
||||
username: 'guichumo',
|
||||
remoteIp: '192.168.1.23',
|
||||
userAgent: UAS.chrome,
|
||||
method: 'DELETE',
|
||||
path: postPath(deleted.name),
|
||||
statusCode: 204,
|
||||
previous: postDoc(deleted),
|
||||
timestamp: new Date(now - DAY - 2 * 3600 * 1000).toISOString()
|
||||
}));
|
||||
|
||||
// 7. 误操作定位:1 天前删除了一篇文章
|
||||
logs.push(rec(
|
||||
new Date(now - DAY - 3600 * 1000 * 2).toISOString(), 'guichumo',
|
||||
'DELETE', '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w45', 204, '192.168.1.23', UAS.chrome
|
||||
));
|
||||
|
||||
// 排序 + 分配 id(最新记录 id 数字最大)
|
||||
// ---- 排序 + 分配记录标识(最新记录编号最大) ----
|
||||
logs.sort(function (a, b) {
|
||||
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
|
||||
});
|
||||
logs.forEach(function (l, idx) {
|
||||
l.id = 'audit-' + String(logs.length - idx).padStart(4, '0');
|
||||
logs.forEach(function (log, idx) {
|
||||
if (!log.id || log.id.indexOf('auditlog-system-') !== 0) {
|
||||
log.id = 'auditlog-' + String(logs.length - idx).padStart(4, '0');
|
||||
}
|
||||
});
|
||||
return logs;
|
||||
}
|
||||
|
||||
@@ -66,13 +66,24 @@
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>操作审计</h1>
|
||||
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 <span class="readonly-hint">(只读,不可篡改)</span></p>
|
||||
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 · 改了什么
|
||||
<span class="readonly-hint">(只读,不可篡改)</span></p>
|
||||
</div>
|
||||
<button class="btn btn-outline" id="btn-simulate">
|
||||
<div class="header-actions">
|
||||
<button class="btn btn-outline" id="btn-export" title="按当前筛选条件导出全部记录(UTF-8 BOM CSV)">
|
||||
<svg viewBox="0 0 24 24"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"/></svg>
|
||||
导出
|
||||
</button>
|
||||
<button class="btn btn-outline" id="btn-refresh" title="按当前筛选重新查询">
|
||||
<svg viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.6M20 4v4h-4"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
<button class="btn btn-primary" id="btn-simulate">
|
||||
<svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg>
|
||||
模拟一次操作
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tabs" id="tabs">
|
||||
<button class="tab active" data-tab="logs">审计日志</button>
|
||||
@@ -83,68 +94,101 @@
|
||||
<b>审计已关闭。</b>当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。
|
||||
</div>
|
||||
|
||||
<!-- 登录失败告警横幅(达到阈值时出现) -->
|
||||
<div class="banner banner-danger alert-banner" id="alert-banner" hidden>
|
||||
<div class="alert-banner-body">
|
||||
<b>登录失败告警已触发。</b>
|
||||
<span id="alert-banner-text"></span>
|
||||
</div>
|
||||
<div class="alert-banner-actions">
|
||||
<button class="btn-link" id="alert-banner-view">只看失败记录</button>
|
||||
<button class="icon-btn" id="alert-banner-close" title="关闭">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ---- 审计日志 ---- -->
|
||||
<section id="panel-logs">
|
||||
<div class="filter-bar card">
|
||||
<div class="filter-item">
|
||||
<label for="f-operator">操作者</label>
|
||||
<select id="f-operator"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-type">资源类型</label>
|
||||
<div class="card filter-card">
|
||||
<div class="filter-grid">
|
||||
<label class="filter-item">
|
||||
<span>操作者</span>
|
||||
<input id="f-operator" type="text" placeholder="用户名,精确匹配" autocomplete="off">
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>资源类型</span>
|
||||
<select id="f-type"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-method">动作</label>
|
||||
<select id="f-method"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-result">结果</label>
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>动作</span>
|
||||
<select id="f-method">
|
||||
<option value="">全部</option>
|
||||
<option value="POST">POST</option>
|
||||
<option value="PUT">PUT</option>
|
||||
<option value="DELETE">DELETE</option>
|
||||
<option value="PATCH">PATCH</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>语义动作</span>
|
||||
<select id="f-action"><option value="">全部</option></select>
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>结果</span>
|
||||
<select id="f-result">
|
||||
<option value="">全部</option>
|
||||
<option value="success">成功</option>
|
||||
<option value="failure">失败</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>关键字</span>
|
||||
<input id="f-keyword" type="search" placeholder="资源名称 / 路径" autocomplete="off">
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>开始时间</span>
|
||||
<input id="f-start" type="datetime-local">
|
||||
</label>
|
||||
<label class="filter-item">
|
||||
<span>结束时间</span>
|
||||
<input id="f-end" type="datetime-local">
|
||||
</label>
|
||||
<div class="filter-actions">
|
||||
<button class="btn btn-primary btn-sm" id="btn-apply">查询</button>
|
||||
<button class="btn btn-outline btn-sm" id="btn-reset">重置</button>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-time">时间范围</label>
|
||||
<select id="f-time">
|
||||
<option value="all">全部时间</option>
|
||||
<option value="24h">近 24 小时</option>
|
||||
<option value="7d">近 7 天</option>
|
||||
<option value="30d">近 30 天</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-item grow">
|
||||
<label for="f-keyword">关键字</label>
|
||||
<input id="f-keyword" type="search" placeholder="资源名称 / 路径,如 hello-halo" autocomplete="off">
|
||||
<div class="filter-note" id="filter-note" hidden>
|
||||
<span id="filter-note-text"></span>
|
||||
<button class="btn-link" id="btn-clear">✕ 清除筛选</button>
|
||||
</div>
|
||||
<button class="btn-link" id="btn-clear" hidden>✕ 清除筛选</button>
|
||||
</div>
|
||||
|
||||
<div class="card table-card">
|
||||
<div class="audit-list-wrap">
|
||||
<table class="audit-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:170px">时间</th>
|
||||
<th style="width:150px">操作者</th>
|
||||
<th style="width:90px">动作</th>
|
||||
<th>资源</th>
|
||||
<th style="width:110px">结果</th>
|
||||
<th style="width:140px">来源 IP</th>
|
||||
<th style="width:190px">操作者 / 时间</th>
|
||||
<th style="width:76px">动作</th>
|
||||
<th style="width:300px">资源 / 路径</th>
|
||||
<th style="width:130px">描述</th>
|
||||
<th style="width:84px">结果</th>
|
||||
<th style="width:120px">IP</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pagination">
|
||||
<span class="pg-info" id="pg-info"></span>
|
||||
<span class="pg-right">
|
||||
<select id="pg-size" title="每页条数">
|
||||
<option value="10">10 条/页</option>
|
||||
<option value="20">20 条/页</option>
|
||||
<option value="20" selected>20 条/页</option>
|
||||
<option value="50">50 条/页</option>
|
||||
</select>
|
||||
<button class="icon-btn" id="pg-prev" title="上一页">‹</button>
|
||||
<span class="pg-page" id="pg-page">1 / 1</span>
|
||||
<button class="icon-btn" id="pg-next" title="下一页">›</button>
|
||||
</span>
|
||||
</div>
|
||||
@@ -154,34 +198,110 @@
|
||||
<!-- ---- 插件设置 ---- -->
|
||||
<section id="panel-settings" hidden>
|
||||
<div class="card settings-card">
|
||||
<div class="card-title">基本设置</div>
|
||||
<div class="card-title">审计设置</div>
|
||||
<div class="card-sub">对应 settings.yaml 的 audit 分组,Console 自动渲染;演示页保存在内存中。</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">审计开关</div>
|
||||
<div class="s-desc">开启后,已登录用户对后台 API(/apis/**)的写操作与登录/登出事件将被记录(对应 settings.yaml,Console 自动渲染)</div>
|
||||
<div class="s-name">启用审计</div>
|
||||
<div class="s-desc">关闭后不再记录新的操作审计日志,已有记录仍可查询</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="set-enabled" checked>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">记录字段变更</div>
|
||||
<div class="s-desc">对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏),关闭后仅记录操作元信息</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="set-record-changes" checked>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">记录系统内部变更</div>
|
||||
<div class="s-desc">记录定时发布等非页面操作触发的资源变更(执行者记为「系统」),关闭后仅记录页面/API 操作</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="set-record-system" checked>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">保留天数</div>
|
||||
<div class="s-desc">超过保留期的记录由每日定时任务自动清理,无需人工干预(默认 90 天,最小 7 天)</div>
|
||||
<div class="s-desc">超过保留期的审计记录将在每日自动清理(最小 7 天,默认 90 天)</div>
|
||||
</div>
|
||||
<input type="number" id="set-retention" class="input num" min="7" max="365" value="90">
|
||||
<input type="number" id="set-retention" class="input num" min="7" step="1" value="90">
|
||||
</div>
|
||||
|
||||
<div class="settings-actions">
|
||||
<button class="btn btn-primary" id="btn-save-settings">保存设置</button>
|
||||
<span class="hint">Demo 仅保存在当前页面内存中,刷新后恢复默认</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card settings-card">
|
||||
<div class="card-title">告警通知</div>
|
||||
<div class="card-sub">独立于审计开关。Webhook 地址凭据只存于 Halo Secret,设置仅保存 Secret 引用;演示页不发起真实网络请求。</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">启用登录失败告警</div>
|
||||
<div class="s-desc">统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(默认关闭)</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="set-alert-enabled">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">Webhook 地址(Secret)</div>
|
||||
<div class="s-desc">选择或创建存放 Webhook 地址的 Secret(键 <code>webhookUrl</code>)。地址仅在服务端读取,可含 access_token 等凭据</div>
|
||||
</div>
|
||||
<input type="text" id="set-alert-secret" class="input secret-input" placeholder="operation-audit-webhook">
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">触发阈值(次)</div>
|
||||
<div class="s-desc">统计窗口内累计登录失败达到该次数即触发一次告警(默认 5)</div>
|
||||
</div>
|
||||
<input type="number" id="set-alert-threshold" class="input num" min="1" step="1" value="5">
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">统计窗口(分钟)</div>
|
||||
<div class="s-desc">失败次数的累计窗口;告警后窗口重开,登录成功立即清零(默认 5)</div>
|
||||
</div>
|
||||
<input type="number" id="set-alert-window" class="input num" min="1" step="1" value="5">
|
||||
</div>
|
||||
|
||||
<div class="settings-actions">
|
||||
<button class="btn btn-outline" id="btn-test-alert">发送测试告警</button>
|
||||
<button class="btn btn-outline" id="btn-simulate-alert">模拟 5 次登录失败</button>
|
||||
<span class="hint">推送 type: "test" 的测试消息,演示页仅预览 JSON 负载</span>
|
||||
</div>
|
||||
<pre class="alert-preview" id="alert-test-output" hidden></pre>
|
||||
</div>
|
||||
|
||||
<div class="card settings-card">
|
||||
<div class="card-title">清理预览</div>
|
||||
<div class="clean-stats" id="clean-stats"></div>
|
||||
<div class="settings-actions">
|
||||
<button class="btn btn-outline" id="btn-clean">模拟一次清理</button>
|
||||
<span class="hint">真实插件由每日定时任务自动执行</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
@@ -197,8 +317,18 @@
|
||||
<span>模拟一次后台操作</span>
|
||||
<button class="icon-btn" id="modal-close">✕</button>
|
||||
</div>
|
||||
<p class="modal-sub">选择操作者与方法、输入请求路径后发送,Demo 将按技术方案 D1 的捕获规则(<code>/apis/**</code> 写操作 + <code>/login</code>、<code>/logout</code>)判断是否写入审计日志。</p>
|
||||
<p class="modal-sub">
|
||||
演示页按真实捕获管线逐步判定:<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">
|
||||
<button class="seg-tab active" data-sim-tab="http">页面 / API 操作</button>
|
||||
<button class="seg-tab" data-sim-tab="system">系统内部变更</button>
|
||||
</div>
|
||||
|
||||
<div id="sim-http-fields">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="sim-user">操作者</label>
|
||||
@@ -214,7 +344,7 @@
|
||||
<select id="sim-method">
|
||||
<option>GET</option>
|
||||
<option>POST</option>
|
||||
<option>PUT</option>
|
||||
<option selected>PUT</option>
|
||||
<option>DELETE</option>
|
||||
<option>PATCH</option>
|
||||
</select>
|
||||
@@ -226,20 +356,14 @@
|
||||
<input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
|
||||
<div class="presets">
|
||||
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200}'>编辑文章</button>
|
||||
<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":"editor.zhang","method":"POST","path":"/apis/api.halo.run/v1alpha1/comments/comment-8fa2c1/approve","status":200}'>审核评论</button>
|
||||
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":401}'>登录失败</button>
|
||||
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读)</button>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="sim-status">模拟响应</label>
|
||||
<label for="sim-status">响应状态</label>
|
||||
<select id="sim-status">
|
||||
<option value="200">200 成功</option>
|
||||
<option value="200" selected>200 成功</option>
|
||||
<option value="201">201 创建成功</option>
|
||||
<option value="204">204 删除成功</option>
|
||||
<option value="302">302 重定向(登录用)</option>
|
||||
<option value="400">400 请求错误</option>
|
||||
<option value="401">401 未认证</option>
|
||||
<option value="403">403 权限不足</option>
|
||||
@@ -247,6 +371,70 @@
|
||||
<option value="500">500 服务端异常</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sim-location">重定向目标(仅 /login)</label>
|
||||
<input id="sim-location" type="text" placeholder="成功后为 /uc;失败含 error 参数" autocomplete="off">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="sim-attempted">尝试的用户名(登录请求)</label>
|
||||
<input id="sim-attempted" type="text" placeholder="如 admin,可留空" autocomplete="off">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sim-prev">写入前资源(JSON,可选)</label>
|
||||
<input id="sim-prev-note" type="text" value="由内置快照自动提供" disabled>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="sim-body">请求体 JSON(可选,用于字段 diff;敏感字段自动脱敏)</label>
|
||||
<textarea id="sim-body" rows="4" spellcheck="false" placeholder='{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo"},"spec":{"title":"新标题"}}'></textarea>
|
||||
</div>
|
||||
|
||||
<div class="presets">
|
||||
<button class="chip" data-preset='{"user":"editor.zhang","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200,"snapshot":"post","body":{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo","labels":{"content.halo.run/pinned":"false"}},"spec":{"title":"你好,Halo(Demo 修改)","slug":"hello-halo","visible":"PUBLIC","publish":true,"pinned":false,"allowComment":true,"summary":"从零开始搭建自己的写作空间。"}}}'>编辑文章(含 diff)</button>
|
||||
<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":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读,不记录)</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="sim-system-fields" hidden>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="sys-method">事件类型</label>
|
||||
<select id="sys-method">
|
||||
<option value="PUT">更新(PUT 语义)</option>
|
||||
<option value="DELETE">删除(DELETE 语义)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sys-type">资源类型</label>
|
||||
<select id="sys-type"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sys-name">资源名称</label>
|
||||
<input id="sys-name" type="text" value="weekly-2026-w46" autocomplete="off">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sys-changes">字段变更(JSON 数组)</label>
|
||||
<textarea id="sys-changes" rows="4" spellcheck="false">[
|
||||
{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},
|
||||
{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}
|
||||
]</textarea>
|
||||
</div>
|
||||
<div class="presets">
|
||||
<button class="chip" data-sys-preset='{"method":"PUT","type":"posts","name":"weekly-2026-w46","changes":[{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}]}'>定时发布文章</button>
|
||||
<button class="chip" data-sys-preset='{"method":"DELETE","type":"posts","name":"draft-night-notes","changes":[{"field":"spec.title","changeType":"REMOVED","oldValue":"夜间随笔(未发布)","newValue":null}]}'>清理未发布草稿</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-outline" id="sim-cancel">取消</button>
|
||||
|
||||
@@ -2,199 +2,703 @@
|
||||
* 操作审计 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: 认证操作 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 = 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: 登录/登出按方法区分,失败回显由 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 },
|
||||
{ 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' },
|
||||
// 升级前落库的登录页访问记录(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: 按操作者筛选', () => {
|
||||
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: 语义动作筛「登录/登出」不混入登录页访问记录(它们展示为「访问登录页/登出页」)', () => {
|
||||
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: 按动作筛选(方法名大小写不敏感)', () => {
|
||||
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', 'a6']);
|
||||
});
|
||||
|
||||
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, 7);
|
||||
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a6', 'a5', 'a7']);
|
||||
});
|
||||
|
||||
// ---------------- 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), 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', '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 +711,106 @@ 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)、登录成功与升级前的登录页访问记录', () => {
|
||||
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' && 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);
|
||||
}
|
||||
}
|
||||
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 记录');
|
||||
});
|
||||
|
||||
|
Before Width: | Height: | Size: 162 KiB After Width: | Height: | Size: 162 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 134 KiB After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 201 KiB |
|
After Width: | Height: | Size: 193 KiB |
@@ -31,7 +31,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
||||
### 4.1 操作记录(核心)
|
||||
|
||||
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
|
||||
> 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获 `/login`、`/logout`(技术方案 D1)。
|
||||
> 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获(技术方案 D1)。只记录认证操作 `POST /login`(登录尝试)与 `POST /logout`(登出);登录/登出页面的 GET 访问(打开登录页、匿名访问被弹回登录页 `/login?authentication_required`、失败回显、登出确认页)不是操作,不记录——否则每次页面访问都会落一条「未知用户 · 登录 200」,看起来像登录成功,真正的登录成败反而被淹没。
|
||||
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
|
||||
- 每条记录字段:
|
||||
|
||||
@@ -84,7 +84,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
|
||||
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否含 `error` 参数区分,见 `LoginOutcome`):失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)标注语义动作 `login-failure`,列表/详情/CSV 显示红色「失败」而非裸状态码,避免绿色 200/302 误读为登录成功;HTTP 状态码仍如实记录 | V2+ 已实现 |
|
||||
| 登录成败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否跳回登录页区分,见 `LoginOutcome`;只有响应明确确认才算成功):失败的登录尝试(`POST /login`)在列表/详情/CSV 中显示红色「失败」,成功显示「成功」,而非被 302/页面渲染的绿色 HTTP 200 掩盖;HTTP 状态码仍如实记录。升级前落库的登录页访问记录(`GET /login`、`GET /logout`)纠正为灰色「—」的「访问登录页/登出页」,不计成败 | V2+ 已实现 |
|
||||
| 操作回滚 | 不在产品范围内 | 不做 |
|
||||
|
||||
## 7. 已知局限
|
||||
@@ -94,8 +94,8 @@ Console 左侧菜单新增"操作审计"页:
|
||||
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
|
||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
||||
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
||||
- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向,失败目标含 `error` 参数):Halo 若调整失败重定向格式或引入新的登录方式,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登录页 GET 与登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||
- 升级前落库的历史记录无法补标注登录失败:表单登录失败(POST /login,302)在列表中仍显示数字状态码,仅失败回显页(GET,路径含 `error` 参数)可现场推导;升级后新记录由捕获时标注(`spec.action = login-failure`),不再有此局限
|
||||
- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向):2xx 或重定向到登录页以外(`/uc`、已保存的原请求、两步验证页)才算成功,跳回登录页(含 `error` 参数或路径即 `/login`)、缺失 Location、4xx/5xx 一律判失败——Halo 若调整登录端点契约,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||
- 升级前落库的登录页访问记录(当时 GET 也被记成「登录/登出」,标注 `login`/`logout`)不改写标注(审计自身不可篡改):展示与导出按方法纠正为「访问登录页/登出页」且结果不计成败,结果筛选与「登录/登出」语义动作筛选均已排除它们;带 `login-failure` 标注的失败回显页(`GET /login?error=...`)仍按登录失败展示
|
||||
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
||||
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
||||
|
||||
@@ -143,6 +143,7 @@ Artifact path and SHA-256:
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [发布验收待办完成记录](./operation-audit-release-todos-completion.md)
|
||||
- [插件发布验收清单(本地存档)](./plugin-release-checklist.md)
|
||||
- [Halo 官方插件清单文档](https://docs.halo.run/developer-guide/plugin/basics/manifest.md)
|
||||
- [Halo 官方 UI 构建输出格式](https://docs.halo.run/developer-guide/plugin/basics/ui/build.md)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# 操作审计插件发布验收待办完成记录
|
||||
|
||||
> 对 [验收清单确认报告](./operation-audit-release-checklist-review.md)(首轮确认)列出的
|
||||
> 6 项待办的执行总结。逐项实测证据的完整记录见
|
||||
> [测试报告第四轮](./operation-audit-test-report.md)。
|
||||
>
|
||||
> - 完成日期:2026-11-22
|
||||
> - 制品基线:`plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
|
||||
> (commit `81693e4` 干净构建)
|
||||
> - 最终状态:**发布就绪**,tag `v0.1.0`(本地,指向 commit `5d05d63`)
|
||||
|
||||
## 一、待办完成总览
|
||||
|
||||
首轮确认报告的 6 项待办(2×P0、2×P1、2×P2)全部补齐并复测通过:
|
||||
|
||||
| 优先级 | 待办 | 完成方式与结果 | Commit |
|
||||
| --- | --- | --- | --- |
|
||||
| P0 | 以正式版本号(非 SNAPSHOT)重新干净构建,复查三处一致 | `clean build -Pversion=0.1.0` 全绿;JAR 文件名 / JAR 内 `plugin.yaml` `spec.version` / Manifest `Implementation-Version` 三处均为 0.1.0 | `81693e4` |
|
||||
| P0 | 补 CI/CD 工作流 | `.github/workflows/ci.yml` + `cd.yml` 复用官方 `halo-sigs/reusable-workflows@v5` | `44eca75` |
|
||||
| P1 | 补卸载(uninstall)测试 | 对齐 Console「卸载并删除配置」真实流程实测通过(详见[测试报告](./operation-audit-test-report.md)第四轮) | `753de51` |
|
||||
| P1 | 2.26.0 最低版本下探实测 | 官方 2.26.0 发布 JAR 全新实例关键路径全部通过(详见[测试报告](./operation-audit-test-report.md)) | `5d05d63` |
|
||||
| P1 | 发布制品 SHA-256 与发布证据块 | SHA-256 已记录于确认报告[发布证据块](./operation-audit-release-checklist-review.md) | `5d05d63` |
|
||||
| P2 | 补 `plugin.yaml` 元数据 | `logo.svg` 内置 + `homepage` / `repo` / `issues` / `author.website` / `license.url`(URL 逐一可达性验证) | `81693e4` |
|
||||
| P2 | UI 输出目录迁移 `ui/` | `processUiResources` 输出至 `resources/main/ui`,JAR 内 `ui/ui-plugin.json` 入口/样式齐备 | `81693e4` |
|
||||
|
||||
## 二、关键执行细节
|
||||
|
||||
### 1. 正式版本构建与三处一致复查
|
||||
|
||||
- `JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew clean build -Pversion=0.1.0`
|
||||
全绿(后端 + UI 全部检查);
|
||||
- 复查:`plugin-operation-audit-0.1.0.jar` ↔ `unzip -p … plugin.yaml` 中
|
||||
`spec.version: "0.1.0"` ↔ Manifest `Implementation-Version: 0.1.0` 一致;
|
||||
- 制品 SHA-256:`3d2a2ad4…db563`(完整值见确认报告发布证据块)。
|
||||
|
||||
### 2. CI/CD 工作流
|
||||
|
||||
- CI(push/PR → master):官方可复用工作流 `plugin-ci.yaml@v5`,执行
|
||||
`./gradlew clean build`(全部测试,不可跳过);
|
||||
- CD(GitHub Release published):`plugin-cd.yaml@v5`,自动
|
||||
`./gradlew clean build -x check -Pversion=${tag 去 v 前缀}`,保证 tag ↔ JAR 名 ↔
|
||||
`spec.version` 一致;`artifacts-path` 限定 `plugin-operation-audit/build/libs`;
|
||||
`skip-appstore-release: true`(首次上架审核通过前不同步应用市场);
|
||||
- 适配本仓库布局:官方工作流从仓库根执行 `./gradlew`,而 Gradle 构建根在
|
||||
`plugin-operation-audit/` 子目录——根目录 `gradlew` / `gradlew.bat` 为转发脚本,
|
||||
经 `build-args: "-p plugin-operation-audit"` 指定项目目录(委托链路已本地验证);
|
||||
UI 子项目使用 npm(无 pnpm-lock.yaml),故 `skip-node-setup: true`。
|
||||
|
||||
### 3. 卸载(uninstall)生命周期实测(Halo 2.26.1 烟测实例)
|
||||
|
||||
- 流程对齐 Console「卸载并删除配置」分支(先经 Halo 2.26.1 源码考证
|
||||
`use-plugin.ts` 与 `PluginReconciler#cleanupResources`):
|
||||
停用 → `DELETE` Plugin CR(finalizer 约 24s 清理)→ 删 Setting → 删 ConfigMap;
|
||||
- 核对结果:CR / JAR / Setting / ConfigMap / RoleTemplate 全部清理;
|
||||
审计数据保留(重装后 169 → 172 条回归);停用期间 pf4j `disabled.txt`
|
||||
写入的残留被 Halo 重装启动时自动清除;
|
||||
- 唯一残留:宿主侧 RoleBinding 孤儿绑定(Halo 平台行为,RoleTemplate 已删、
|
||||
无授权效果,记录备查)。
|
||||
|
||||
### 4. 2.26.0 最低版本下探实测
|
||||
|
||||
- 实例:官方 2.26.0 发布 JAR(下载件 sha256 与官方 `.sha256` 逐字符一致),
|
||||
一次性全新数据目录,测试后停用丢弃;
|
||||
- 关键路径全部通过:setup / admin 登录(RSA + CSRF 契约)/ install / enable
|
||||
(STARTED)/ 审计捕获 / query / export / 匿名拒绝 / `ui/` ESM bundle 下发 /
|
||||
实例日志 0 ERROR;
|
||||
- 行为差异实测记录:2.26.0 的登录失败返回 **401 JSON**(2.26.1 为
|
||||
302 → `?error=` 参数),插件认证端点过滤器在两种形态下均正确标注
|
||||
`login-failure` 语义动作;
|
||||
- 至此 `spec.requires >=2.26.0` 的实测验证完成(2.26.1 为当前版本复验)。
|
||||
|
||||
### 5. manifest 元数据与 ui/ 迁移
|
||||
|
||||
- `logo.svg` 置于 `src/main/resources/`(官方插件同款相对路径引用方式);
|
||||
- `homepage` / `repo` / `issues` 指向仓库托管地址(逐一 curl 验证 200);
|
||||
- `ui/` 目录为 Halo ≥2.25.0 官方规范输出位置(`console/` 为旧项目兼容回退);
|
||||
迁移同时清理旧构建残留的 `console/` 目录,防止过期产物入 JAR。
|
||||
|
||||
## 三、提交记录
|
||||
|
||||
```
|
||||
5d05d63 docs: 发布验收全部待办完成——2.26.0 下探通过,验收报告更新为发布就绪
|
||||
753de51 docs: 测试报告补卸载(uninstall)生命周期实测记录
|
||||
44eca75 ci: 发布验收 P0 项——补齐 CI/CD 工作流
|
||||
81693e4 chore: 发布验收 P2 项——UI 产物迁至 ui/,补齐 manifest 元数据
|
||||
tag: v0.1.0 → 5d05d63(本地 annotated tag)
|
||||
```
|
||||
|
||||
## 四、剩余发布动作(发布操作,非验收缺口)
|
||||
|
||||
1. 推送 master 与 tag `v0.1.0`;
|
||||
2. 在代码托管平台创建 GitHub Release(tag `v0.1.0`)——CD 工作流自动构建并
|
||||
把 JAR 上传为 Release 资产;
|
||||
3. 发布 commit 的 CI 必须绿色(CD 带 `-x check`,不能替代 CI 与测试);
|
||||
4. 应用市场首次审核通过后,再按官方发布文档配置 `app-id` 与最小权限的
|
||||
`HALO_PAT` 令牌开启自动同步。
|
||||
|
||||
## 五、环境备注
|
||||
|
||||
- Docker Hub 在本机不可达(registry 连接超时),2.26.0 实例改用官方独立 JAR
|
||||
(经 GitHub release 镜像加速下载,官方 SHA-256 校验通过);
|
||||
- 本机 `JAVA_HOME` 指向 jre7,所有 Gradle 调用需临时覆盖为 JDK 21;
|
||||
- 全部测试实例均为一次性数据目录(`workdir` / `workdir-260`),与生产数据无任何
|
||||
关联,测试完成后停用。
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
| # | 决策 | 结论 | 理由 |
|
||||
|---|---|---|---|
|
||||
| D1 | 捕获通道 | 双过滤器分治:`/apis/**` 写操作走 `AfterSecurityWebFilter`;认证端点 `/login`、`/logout` 走 `BeforeSecurityWebFilter`(Security 链之前) | 表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),链尾过滤器永远看不到认证端点请求,必须在链首承接 |
|
||||
| D1 | 捕获通道 | 双过滤器分治:`/apis/**` 写操作走 `AfterSecurityWebFilter`;认证操作 `POST /login`、`POST /logout` 走 `BeforeSecurityWebFilter`(Security 链之前) | 表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),链尾过滤器永远看不到认证操作请求,必须在链首承接 |
|
||||
| D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 |
|
||||
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
|
||||
|
||||
@@ -51,13 +51,14 @@ plugin-operation-audit/
|
||||
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
|
||||
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标 error 参数(纯函数)
|
||||
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标是否跳回登录页(纯函数)
|
||||
│ │ │ ├── AuditResult.java # 结果语义:成功 / 失败 / 页面访问(筛选与 CSV 共用,纯函数)
|
||||
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
||||
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证端点捕获(BeforeSecurityWebFilter,链首)
|
||||
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证操作捕获(BeforeSecurityWebFilter,链首,仅 POST)
|
||||
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
|
||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||
│ │ └── housekeeping/
|
||||
@@ -83,13 +84,13 @@ plugin-operation-audit/
|
||||
|
||||
- 双过滤器分治(P0 缺陷实证后修订):
|
||||
- **`/apis/**` 写操作**:`AfterSecurityWebFilter` 扩展点(位于 Security 过滤链最后、认证之后,可获取当前登录用户,`doFinally` 可读最终响应状态码)。
|
||||
- **认证端点 `/login`、`/logout`**:`BeforeSecurityWebFilter` 扩展点(位于 Security 过滤链最前,`SecurityWebFiltersOrder.FIRST`)。P0 根因:表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求——POST /login、/logout 曾永不产生审计记录,登录失败告警生产路径随之失效。
|
||||
- **认证操作 `POST /login`、`POST /logout`**:`BeforeSecurityWebFilter` 扩展点(位于 Security 过滤链最前,`SecurityWebFiltersOrder.FIRST`)。P0 根因:表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证操作请求——POST /login、/logout 曾永不产生审计记录,登录失败告警生产路径随之失效。
|
||||
- 捕获规则(`CaptureRule`,纯函数):
|
||||
- `shouldCapture`:`POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`(链尾过滤器消费)
|
||||
- `isAuthEndpoint`:路径精确匹配 `/login`、`/logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录
|
||||
- 操作者归属:`/apis/**` 请求从认证上下文解析;认证端点在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
|
||||
- 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证端点记录不判匿名。
|
||||
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录且链尾过滤器不重复记录。
|
||||
- `isAuthOperation`:`POST /login` 与 `POST /logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录。`isAuthEndpoint`(路径精确匹配 `/login`、`/logout`)仅用于路径归类:登录/登出页面的 GET 访问不是操作,原样透传不记录(现场反馈:页面访问落库成「未知用户 · 登录 200」,列表里全是成功、真正的登录成败被淹没)
|
||||
- 操作者归属:`/apis/**` 请求从认证上下文解析;认证操作在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
|
||||
- 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证操作记录不判匿名。
|
||||
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录,登录/登出页面的 GET 访问全链不记录。
|
||||
|
||||
### D2 审计写入:响应式直写
|
||||
|
||||
@@ -216,7 +217,8 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
```
|
||||
|
||||
- `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。
|
||||
- 登录成败判定(`LoginOutcome`,纯函数):Halo 2.26 登录端点**表单提交的成功与失败均为 302 重定向**(成功 → `/uc` 或 2FA 页,失败 → `/login?error=invalid-credential&method=...`),仅 XHR/JSON 请求以 200/401 区分成败——不能只看状态码。规则:2xx 成功;3xx 以重定向目标查询串是否含 `error` 参数判定(含无值形式 `error`);其余(401、状态码缺失)失败。失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)的记录标注语义动作 `login-failure`(`spec.action`),列表/详情/CSV 据此显示红色「失败」;HTTP 状态码仍如实记录。告警服务(`LoginFailureAlertService`)按同一判定结果清零/累计,修复了旧版「2xx 即成功」把表单成功登录误计为失败的问题。
|
||||
- 登录成败判定(`LoginOutcome`,纯函数):Halo 2.26.1 登录端点**表单提交的成功与失败均为 302 重定向**(`LoginSuccessHandler` → `/uc`、已保存的原请求或 2FA 页;`LoginFailureHandler` → `/login?error=invalid-credential|account-disabled|rate-limit-exceeded&method=...`),仅 XHR/JSON 请求以 200/401 区分成败——不能只看状态码。规则:**只有响应明确确认才算成功**——2xx 成功;3xx 以重定向目标是否跳回登录页判定(路径即 `/login`,或查询串含 `error` 参数;缺失 Location 同样无法确认成功);其余(401、403、状态码缺失)失败。失败的登录尝试(`POST /login`)标注语义动作 `login-failure`(`spec.action`)。告警服务(`LoginFailureAlertService`)按同一判定结果清零/累计。
|
||||
- 结果语义(`AuditResult`,纯函数;结果筛选 `AuditLogFilters`、CSV 导出与前端 `audit.ts` 共用同一规则):登录失败(标注 `login-failure`)为失败;认证端点的页面访问(非 POST 的 `/login`、`/logout`,仅升级前落库的历史记录)不计成败;其余按状态码 2xx/3xx 判成功。展示:登录失败红色「失败」、登录成功绿色「成功」(表单登录成败同为 302,裸状态码读不出成败)、页面访问灰色「—」并描述为「访问登录页/登出页」(`OperationDescription.semanticAction` 按方法纠正历史记录的 `login`/`logout` 标注,标注本身不改写)。
|
||||
- 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。
|
||||
|
||||
### 5.2 资源解析规则(通用,不追求语义完美)
|
||||
|
||||
@@ -23,6 +23,10 @@
|
||||
> 联调(含多角色权限矩阵与生命周期往返)再次全部通过,详见
|
||||
> [复测记录](#复测记录2026-11-22-第三轮commit-fd3ea71)。
|
||||
|
||||
> **复测状态(2026-12-05 第五轮,commit `fc79842`)**:针对生产反馈「登录失败也显示成功」
|
||||
> 的修复——登录页的 GET 访问不再记为登录,登录成败以响应确认为准;自动化检查与真实 Halo
|
||||
> 2.26.1 升级场景复测通过,详见[复测记录](#复测记录2026-12-05-第五轮commit-fc79842)。
|
||||
|
||||
## 可复核结果
|
||||
|
||||
```text
|
||||
@@ -101,7 +105,7 @@ Known limitations: 见文末"未覆盖项"
|
||||
|
||||
### 浏览器级 UI 验证(桌面 + 窄屏人工检查)
|
||||
|
||||
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `gui-test-screenshots/`:
|
||||
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `docs/assets/gui-test-screenshots/`:
|
||||
|
||||
- 菜单入口:`plugin` 分组下出现「操作审计」,选中态高亮正确(t1);
|
||||
- 列表页(1280px):筛选区(操作者/资源类型/动作/语义动作/结果/关键字/起止时间)、
|
||||
@@ -235,6 +239,11 @@ Known limitations: DevTools haloServer/pullHaloImage 因本机无
|
||||
|
||||
> 本轮新增核对项:GET /login 页面访问也产生 `login`(HTTP 200)记录——属
|
||||
> `isAuthEndpoint` 设计内覆盖(失败回显 `?error=...` 会被标注登录失败),非噪声缺陷。
|
||||
>
|
||||
> ⚠️ **此判断已于 2026-12-05 第五轮推翻**(commit `fc79842`):对登录页的 GET 访问不是
|
||||
> 登录事件,却被记成绿色「登录 200」,正是生产反馈「登录失败也显示成功」的根因;现已改为
|
||||
> 只记录 `POST /login`、`POST /logout`,详见
|
||||
> [第五轮复测记录](#复测记录2026-12-05-第五轮commit-fc79842)。
|
||||
|
||||
## 复测记录(2026-11-22 第三轮,commit `fd3ea71`)
|
||||
|
||||
@@ -402,11 +411,138 @@ Known limitations: 2.26.0 最低版本下探已于本节补充执
|
||||
权限拒绝与 UI 资源下发全部正常;2.26.1(此前三轮联调平台)为当前版本复验。
|
||||
`spec.requires >=2.26.0` 的实测验证完成。
|
||||
|
||||
## 复测记录(2026-12-05 第五轮,commit `fc79842`)
|
||||
|
||||
**触发来源:生产环境现场反馈。** 站长在生产站(Halo 2.26.1)的操作审计页反馈
|
||||
「没有失败,全是成功,登录失败也显示成功」,截图中的记录全是
|
||||
`未知用户 · GET auth /login`、`GET auth /login?authentication_required`,描述「登录」、
|
||||
结果绿色 200。本轮在一次性实例上复现、修复并复测;第二轮记录中「GET /login 页面访问
|
||||
产生 login 记录属设计内覆盖,非噪声缺陷」的判断据此**推翻**。
|
||||
|
||||
```text
|
||||
Commit: fc79842(master)
|
||||
制品: plugin-operation-audit-0.1.0-SNAPSHOT.jar
|
||||
SHA-256 73b4fb37246c9e02fb38ba43ef76ee32514299ca322e8f4651f994367647a4de
|
||||
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8097 一次性实例,H2 内置库,
|
||||
数据目录 C:/Users/Windows11/.halo-repro/workdir-baseline,与生产数据无关联)
|
||||
升级场景: 实例中保留修复前构建(afda8d0)写入的数据,停服替换 JAR 后启动
|
||||
(Windows 部署路径);插件 STARTED,历史记录全部保留
|
||||
Java and Node.js versions: Java 21.0.10、Node v24.19.0
|
||||
Automated checks: PASS(./gradlew clean build:后端 27 类 286/286,UI vitest 9 文件 74/74,
|
||||
vue-tsc 与 vite 构建通过;demo node:test 61/61)
|
||||
Manual paths checked: 登录页 GET 访问不落库 → 失败登录(表单 302 / JSON 401 / 缺 CSRF 403)
|
||||
→ 成功登录 → 登出 → 结果筛选 → 语义动作筛选 → CSV 导出 → Console 页面
|
||||
Known limitations: 本轮未在 2.26.0 重测;生产站实际部署的插件构建未核对(见文末「本轮未覆盖」)
|
||||
```
|
||||
|
||||
### 现象复现(修复前,commit `afda8d0` 构建)
|
||||
|
||||
Halo 2.26.1 的登录页是服务端渲染表单,表单登录无论成败在 HTTP 层**都是 302**,而登录页
|
||||
自身的响应恒为 200。修复前的认证端点过滤器对 `/login`、`/logout` 不区分方法,把对页面的
|
||||
GET 访问也当成登录事件落库:
|
||||
|
||||
| 浏览器行为 | 宿主实际响应 | 修复前落库(`action` / 状态码) |
|
||||
| --- | --- | --- |
|
||||
| 打开登录页 `GET /login` | 200 | `login` / 200 |
|
||||
| 匿名访问受保护页,被弹回 `GET /login?authentication_required` | 302 → 登录页 200 | `login` / 200 |
|
||||
| 密码错误 `POST /login`,浏览器跟随跳转到 `GET /login?error=invalid-credential&method=local` | 302 → 登录页 200 | `login-failure` / 302,另加一条 `login-failure` / 200 |
|
||||
| 密码正确 `POST /login` | 302 → `/uc` | `login` / 302 |
|
||||
|
||||
`POST /login` 的成败标注本身是对的,但**每一次对登录页的访问都会落一条绿色「登录 200」**
|
||||
(即生产截图中的记录)。从登录页发起的一次输错密码的登录共落 3 条记录,其中 1 条是绿色
|
||||
「登录 200」;刷新登录页、被弹回登录页、扫描器反复探测 `/login` 同样如此,列表看起来
|
||||
「全是成功」,真正的登录成败被淹没。
|
||||
|
||||
### 修复内容(commit `fc79842`)
|
||||
|
||||
| 层 | 改动 |
|
||||
| --- | --- |
|
||||
| 捕获 | 认证端点只记录认证操作 `POST /login`、`POST /logout`;登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出确认页)原样透传,不触碰请求体、不落库(`CaptureRule.isAuthOperation`) |
|
||||
| 成败判定 | `LoginOutcome.isFailure`:仅 2xx,或 30x 且跳转目标不是登录页(`/uc`、已保存的原请求、两步验证页)才算成功;跳回 `/login`、带 `error` 参数、缺失 Location、4xx/5xx 一律判失败 |
|
||||
| 结果语义 | 新增 `AuditResult`(成功 / 失败 / 页面访问),作为结果筛选、CSV 导出与列表徽标的同一套规则 |
|
||||
| 历史记录 | 升级前落库的 GET 记录**不改写**(审计只追加):描述按方法纠正为「访问登录页 / 访问登出页」,结果显示灰色「—」,不计成败;结果筛选与「登录 / 登出」语义动作筛选均排除它们;带 `login-failure` 标注的旧回显页仍按「登录失败 · 失败」展示 |
|
||||
| 界面 | 登录成功显示「成功」、登录失败显示红色「失败」,其余操作仍显示状态码;详情抽屉与 CSV 结果列同步 |
|
||||
| 测试 | 后端 270 → 286、UI 69 → 74、demo 56 → 61 |
|
||||
|
||||
### 真实实例脚本复核(交付 JAR 本体)
|
||||
|
||||
自实例启动(13:30:02)起写入的记录:
|
||||
|
||||
| 检查项 | 实测 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 打开登录页 `GET /login` | 200,认证记录 0 条 | ✅ |
|
||||
| 匿名访问受保护页 → `GET /login?authentication_required` | 302 → 200,认证记录 0 条 | ✅ |
|
||||
| 登出确认页 `GET /logout` | 200,认证记录 0 条 | ✅ |
|
||||
| 自启动起写入的认证端点记录 | 18 条**全部为 POST**(`/login`、`/logout`);页面访问记录 0 条 | ✅ |
|
||||
| 密码错误 `POST /login`(表单) | 302 → `/login?error=invalid-credential&method=local`,记 `login-failure` | ✅ |
|
||||
| 密码错误 / 不存在的账号(命中宿主限频时) | 302 → `/login?error=rate-limit-exceeded&method=local`,记 `login-failure` | ✅ |
|
||||
| 密码错误(`Accept: application/json`) | 401,记 `login-failure` | ✅ |
|
||||
| 缺少 `_csrf` 的 `POST /login` | 403,记 `login-failure` | ✅ |
|
||||
| 密码正确 `POST /login` | 302 → `/uc`,记 `login` | ✅ |
|
||||
| `POST /logout` | 302 → `/login?logout`,记 `logout` | ✅ |
|
||||
| 结果筛选 `result=success` | 不含任何页面访问记录 | ✅ |
|
||||
| 结果筛选 `result=failure` | 28 条:24 条 `POST` 登录失败、3 条旧回显页、1 条 `POST /logout` 403;不含旧「登录 / 登出」页面访问记录 | ✅ |
|
||||
| 语义动作筛选 `spec.action=login` | 12 条,全部为 `POST /login`(302) | ✅ |
|
||||
| CSV 导出(描述 / 结果) | 登录 / 成功 ×13、登录失败 / 失败 ×28、登出 / 成功 ×4、登出 / 失败 ×1、访问登录页 / 页面访问 ×7、访问登出页 / 页面访问 ×1 | ✅ |
|
||||
| 实例日志 | 0 ERROR | ✅ |
|
||||
|
||||
说明:
|
||||
|
||||
- 修复前构建留在库中的 11 条 GET 记录(存储标注 `login` ×7、`login-failure` ×3、
|
||||
`logout` ×1)原样保留、未改写:导出时 8 条为「访问登录页 / 访问登出页 · 页面访问」,
|
||||
3 条带 `login-failure` 标注的旧回显页仍为「登录失败 · 失败」。
|
||||
- Halo 2.26.1 内置登录限频为每 IP 每分钟 3 次尝试
|
||||
(`resilience4j.ratelimiter.configs.authentication`)。连续失败尝试会触发限频:复核输出中
|
||||
`invalid-credential` 与 `rate-limit-exceeded`(表单 302 / JSON 401)两种拒绝原因都实际出现过,
|
||||
二者都是被拒绝的登录尝试,均记 `login-failure`。限频窗口内即使密码正确,宿主同样拒绝
|
||||
(复核中实际出现 1 次),该尝试也如实记为登录失败。
|
||||
- 18 条新记录 = 登录成功 5 + 登出 2 + 登录失败 11(脚本两轮的失败场景 8 条,另有 3 条来自
|
||||
复核命令本身:2 次命令行输错实例密码的真实失败登录,以及上述被限频拒绝的 1 次)。
|
||||
- `spec.action=login` 的 12 条取自脚本复核时点,CSV 直方图取自随后的事后抽查
|
||||
(期间又有 1 次成功登录)。
|
||||
|
||||
### Console 页面(应用内浏览器真实登录)
|
||||
|
||||
截图所用构建与交付 JAR 逐条目内容一致(67 个条目的名称 / 大小 / CRC-32 全部相同,
|
||||
仅打包时间戳不同);截图存于 `docs/assets/gui-test-screenshots/`。
|
||||
|
||||
| 检查项 | 实测 | 结果 | 截图 |
|
||||
| --- | --- | --- | --- |
|
||||
| 浏览器输错密码 | 落在 `/login?error=invalid-credential&method=local`,列表新增一行「登录失败 · 失败」 | ✅ | t6 |
|
||||
| 登录成功 / 登出 | 「登录 · 成功」(绿)、「登出 · 302」 | ✅ | t6 |
|
||||
| 修复前写入的 GET 记录 | 「访问登录页 · —」(灰,含 `/login?authentication_required`);带 `login-failure` 标注的旧回显页仍为「登录失败 · 失败」 | ✅ | t7 |
|
||||
| 结果 = 成功(资源类型 auth) | 10 条:8 条「登录 · 成功」+ 2 条「登出 · 302」,无页面访问记录 | ✅ | t8 |
|
||||
| 结果 = 失败(资源类型 auth) | 17 条「登录失败 · 失败」+ 1 条「登出 · 403」 | ✅ | — |
|
||||
|
||||
详情抽屉的结果语义(成功 / 失败 / 页面访问)由 `AuditLogDetail.appearance.spec.ts` 锁定,
|
||||
本轮未做浏览器截图。
|
||||
|
||||
### 与前几轮记录的关系
|
||||
|
||||
- 第二轮「GET /login 页面访问产生 login 记录属设计内覆盖,非噪声缺陷」的判断作废:该行为
|
||||
正是本次现场反馈的根因,现已改为不记录。
|
||||
- 首轮 P0 修复(`f4d1200`)确立的「认证端点在 Security 链最前承接」结论不变,本次只收紧
|
||||
了它记录的范围(仅 POST)与成败判定。
|
||||
|
||||
### 本轮未覆盖
|
||||
|
||||
- **未在 Halo 2.26.0 重测**:本轮改动用到的 `Queries.notEqual` / `Queries.startsWith` 已在
|
||||
2.26.0 平台 API(`api-2.26.0.jar`,即 `halo-2.26.0.jar` 内置的那份)中核对签名存在,但
|
||||
最低版本上的运行时复测未做,留待下次发布前执行。
|
||||
- **生产站实际部署的插件构建未核对**:若生产站输错密码后没有新增 `POST /login` 记录,
|
||||
说明线上仍是修复前的构建,需升级 JAR 才生效。
|
||||
- Webhook 公网投递同前几轮,未重测。
|
||||
|
||||
## 附:测试环境残留与清理
|
||||
|
||||
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / Sm0keTest2026,
|
||||
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / 测试密码已脱敏,
|
||||
数据目录 `C:/Users/Windows11/.halo-smoke-test/workdir`,可丢弃,与生产数据无任何关联);
|
||||
- 第三轮联调中将 auditor3 密码重置为 `AuditR3.2026`(供只读角色矩阵复测),
|
||||
- 第三轮联调中重置了 auditor3 密码(测试凭据已脱敏,供只读角色矩阵复测),
|
||||
残留测试用户 auditor3(role-template-audit-view)保留于实例中;
|
||||
- 已恢复干净版插件 JAR 并确认无诊断日志残留(重启后 0 条 AUDIT-DIAG);
|
||||
- 源码工作区干净,仅新增截图证据目录 `gui-test-screenshots/`(未纳入版本控制)。
|
||||
- 源码工作区干净,截图证据已归档至 `docs/assets/gui-test-screenshots/` 并纳入版本控制。
|
||||
- 2026-12-05 核对:上述 8099 实例已不在运行(端口未监听),数据目录仍保留。
|
||||
- 第五轮的一次性实例(127.0.0.1:8097,数据目录
|
||||
`C:/Users/Windows11/.halo-repro/workdir-baseline`)已停服,目录保留、可整体删除;
|
||||
复现与抽查脚本在 `C:/Users/Windows11/.halo-repro/scripts/`(`repro.py`、`spotcheck.py`、
|
||||
`inspect.py`),不随仓库分发。
|
||||
|
||||
@@ -9,8 +9,14 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
|
||||
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
|
||||
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出),登录请求白名单提取尝试的用户名落库
|
||||
(`spec.attemptedUsername`,密码等其余字段绝不落库,登录失败时操作者记"未知用户")。
|
||||
另捕获认证操作 `POST /login`、`POST /logout`(登录成功/失败/登出),登录请求白名单
|
||||
提取尝试的用户名落库(`spec.attemptedUsername`,密码等其余字段绝不落库,登录时操作者
|
||||
记"未知用户")。登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出
|
||||
确认页)不是操作,不记录。
|
||||
- **登录成败标注**:表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定
|
||||
(`LoginOutcome`,只有响应明确确认才算成功);列表/详情显示「成功」/红色「失败」,
|
||||
CSV 结果列同理。升级前落库的登录页访问记录(`GET /login`,曾显示成绿色「登录 200」)
|
||||
纠正为灰色「—」的「访问登录页」,不计成败。
|
||||
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
|
||||
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
|
||||
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
|
||||
@@ -133,9 +139,9 @@ Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配
|
||||
## 技术说明
|
||||
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证操作 `POST /login`、
|
||||
`POST /logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器
|
||||
命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证操作请求,
|
||||
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||
Extension + 索引查询,全程响应式非阻塞。
|
||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||
@@ -186,8 +192,9 @@ Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配
|
||||
资源组合 `alerts + alerts/test`(create 动词)不在只读角色模板授权内,仅管理角色可用;
|
||||
设置页经自定义 FormKit 输入(Halo 2.25+ `formkit.inputs`,`@formkit/vue` 已被
|
||||
bundler kit 外部化为宿主共享模块)注册「发送测试告警」按钮,`ignore: true` 不落任何配置值。
|
||||
- 关于测试:`./gradlew test`(当前 244 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、登录尝试用户名提取
|
||||
- 关于测试:`./gradlew test`(当前 286 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为(含认证端点仅记录
|
||||
`POST /login`、`POST /logout`,登录成败判定与结果语义)、登录尝试用户名提取
|
||||
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
|
||||
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
|
||||
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
|
||||
|
||||
@@ -103,11 +103,6 @@ public class AuditLogCsvExporter {
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端一致:登录失败标注(HTTP 状态码可能为 200/302——失败回显页
|
||||
// 渲染/失败重定向)一律失败,其余 2xx/3xx 成功
|
||||
var failedLogin = OperationDescription.LOGIN_FAILURE_ACTION.equals(spec.getAction());
|
||||
var success = !failedLogin && statusCode != null && statusCode >= 200
|
||||
&& statusCode < 400;
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
@@ -116,10 +111,13 @@ public class AuditLogCsvExporter {
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||
// 优先落库语义动作(含登录失败标注与页面访问纠正),历史记录回退
|
||||
// method/path 现场推导
|
||||
escape(OperationDescription.describe(spec)),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
// 结果语义与前端一致(AuditResult):登录失败标注一律失败(HTTP 状态码
|
||||
// 可能是 302/200),认证端点的页面访问记录(历史 GET)不计成败,其余按状态码
|
||||
escape(AuditResult.of(spec).label()),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
escape(spec.getRemoteIp()),
|
||||
escape(spec.getUserAgent()));
|
||||
|
||||
@@ -25,6 +25,22 @@ final class AuditLogFilters {
|
||||
static final Set<String> FILTERABLE_FIELDS = Set.of("spec.username", "spec.resourceType",
|
||||
"spec.method", "spec.action", "spec.statusCode");
|
||||
|
||||
/**
|
||||
* 登录/登出操作的语义动作键:按其筛选时排除页面访问记录——升级前落库的
|
||||
* GET /login、GET /logout 带同样的标注,但展示为「访问登录页/登出页」。
|
||||
*/
|
||||
private static final Set<String> AUTH_OPERATION_ACTIONS = Set.of("login", "logout");
|
||||
|
||||
/**
|
||||
* 页面访问记录({@link OperationDescription#isAuthPageVisit} 的索引查询形态):
|
||||
* 非 POST 的 {@code /login}、{@code /logout} 请求(含查询串)。不是操作,不计成败。
|
||||
*/
|
||||
private static final Condition PAGE_VISIT = Queries.and(
|
||||
Queries.notEqual("spec.method", "POST"),
|
||||
Queries.or(
|
||||
Queries.startsWith("spec.path", "/login"),
|
||||
Queries.startsWith("spec.path", "/logout")));
|
||||
|
||||
private AuditLogFilters() {
|
||||
}
|
||||
|
||||
@@ -44,7 +60,11 @@ final class AuditLogFilters {
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
throw new IllegalArgumentException("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
var condition = Queries.equal(field, value);
|
||||
if ("spec.action".equals(field) && AUTH_OPERATION_ACTIONS.contains(value)) {
|
||||
condition = Queries.and(condition, Queries.not(PAGE_VISIT));
|
||||
}
|
||||
conditions.add(condition);
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
@@ -56,9 +76,9 @@ final class AuditLogFilters {
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||
// 结果筛选(与 AuditResult 同一规则):success = 2xx/3xx 且非登录失败标注、
|
||||
// 非页面访问;failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,
|
||||
// 仅凭状态码识别不出)或 4xx/5xx(页面访问除外)。页面访问记录不计成败
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
var loginFailure = Queries.equal("spec.action",
|
||||
@@ -68,10 +88,12 @@ final class AuditLogFilters {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
conditions.add(Queries.not(loginFailure));
|
||||
conditions.add(Queries.not(PAGE_VISIT));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.or(
|
||||
Queries.greaterThan("spec.statusCode", "400", true),
|
||||
loginFailure));
|
||||
loginFailure,
|
||||
Queries.and(Queries.greaterThan("spec.statusCode", "400", true),
|
||||
Queries.not(PAGE_VISIT))));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
|
||||
@@ -27,8 +27,10 @@ public class AuditLogSpec {
|
||||
|
||||
/**
|
||||
* 语义动作键(语义动作标注,产品设计 V2):捕获时由 method/path 推导落库
|
||||
* (如 login/logout/create/update/delete/publish/restore),注册索引后支持
|
||||
* 按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导)。
|
||||
* (如 login/logout/create/update/delete/publish/login-failure,可空),注册索引后
|
||||
* 支持按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导);
|
||||
* 升级前落库的登录页访问记录(GET,现已不再记录)带 login/logout 标注,
|
||||
* 展示时按方法纠正为页面访问。
|
||||
*/
|
||||
private String action;
|
||||
|
||||
@@ -41,7 +43,10 @@ public class AuditLogSpec {
|
||||
/** 完整请求路径(资源语义解析的兜底,保证完整性)。 */
|
||||
private String path;
|
||||
|
||||
/** 响应状态码(结果:2xx 成功,其余失败)。 */
|
||||
/**
|
||||
* 响应状态码,如实记录。结果语义见 {@link AuditResult}:不能只看状态码——表单登录
|
||||
* 成败均为 302,登录失败靠语义动作 {@code login-failure} 标注识别。
|
||||
*/
|
||||
private Integer statusCode;
|
||||
|
||||
/** 来源 IP。 */
|
||||
|
||||
@@ -39,9 +39,8 @@ public class AuditRecorder {
|
||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
|
||||
* 302 重定向且目标含 error 参数)或失败回显
|
||||
* (GET /login?error=...,HTTP 200),语义动作标注
|
||||
* login-failure;其余请求为 false
|
||||
* 302 重定向且回跳登录页),语义动作标注 login-failure;
|
||||
* 其余请求为 false
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
@@ -162,14 +161,14 @@ public class AuditRecorder {
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
|
||||
// 登录失败(POST /login 失败或 GET /login?error=... 失败回显)标注
|
||||
// login-failure——回显页 HTTP 200 无法由路径重新推导,必须落库标注
|
||||
// 登录失败(POST /login 回跳登录页或 4xx/5xx)标注 login-failure——
|
||||
// 表单登录失败的 HTTP 状态码与成功相同(302),结果只能靠落库标注区分
|
||||
spec.setAction(loginFailed ? OperationDescription.LOGIN_FAILURE_ACTION
|
||||
: OperationDescription.actionOf(
|
||||
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||
spec.setPath(snapshot.getFullPath());
|
||||
// 状态码如实记录(失败回显页为 200、表单登录失败为 302),登录成败看语义动作标注
|
||||
// 状态码如实记录(表单登录成败均为 302),登录成败看语义动作标注
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
/**
|
||||
* 审计记录的结果语义(纯函数):结果筛选({@link AuditLogFilters})、CSV 导出
|
||||
* ({@link AuditLogCsvExporter})与前端 {@code ui/src/utils/audit.ts} 的结果徽标
|
||||
* 共用同一规则——什么算成功、什么算失败,只能有一个定义。
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #FAILURE}:登录失败(语义动作 {@code login-failure},HTTP 状态码可能是
|
||||
* 302/200);其余按状态码判定,4xx/5xx 为失败;</li>
|
||||
* <li>{@link #PAGE_VISIT}:认证端点的页面访问(升级前落库的 GET /login、GET /logout
|
||||
* 历史记录)——不是操作,不计成败;</li>
|
||||
* <li>{@link #SUCCESS}:其余状态码 2xx/3xx。</li>
|
||||
* </ul>
|
||||
*/
|
||||
enum AuditResult {
|
||||
SUCCESS("成功"),
|
||||
FAILURE("失败"),
|
||||
PAGE_VISIT("页面访问");
|
||||
|
||||
/** 导出 CSV「结果」列的中文值。 */
|
||||
private final String label;
|
||||
|
||||
AuditResult(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
static AuditResult of(AuditLogSpec spec) {
|
||||
if (OperationDescription.LOGIN_FAILURE_ACTION.equals(
|
||||
OperationDescription.semanticAction(spec))) {
|
||||
return FAILURE;
|
||||
}
|
||||
if (OperationDescription.isAuthPageVisit(spec.getMethod(), spec.getPath())) {
|
||||
return PAGE_VISIT;
|
||||
}
|
||||
var statusCode = spec.getStatusCode();
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
? SUCCESS : FAILURE;
|
||||
}
|
||||
|
||||
String label() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthOperation;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isLoginAttempt;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -13,16 +13,21 @@ import run.halo.app.security.BeforeSecurityWebFilter;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 认证端点({@code /login}、{@code /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||
* 认证操作({@code POST /login}、{@code POST /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||
*
|
||||
* <p>以 {@link BeforeSecurityWebFilter} 扩展点注册:位于 Security 过滤链最前
|
||||
* ({@code SecurityWebFiltersOrder.FIRST})。原先认证端点由
|
||||
* {@code AfterSecurityWebFilter} 扩展点注册的 {@link OperationAuditWebFilter} 捕获,
|
||||
* 但该扩展点位于认证环节之后——表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
|
||||
* 请求后直接完成 302 响应、不再向下游传递,POST /login 与 POST /logout 永远到不了
|
||||
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证端点整体
|
||||
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证操作整体
|
||||
* 移交本过滤器,在 Security 链之前承接捕获与记录。
|
||||
*
|
||||
* <p>只记录认证操作本身:{@code POST /login} 是登录尝试,{@code POST /logout} 是登出。
|
||||
* 登录/登出页面的 GET 访问(打开登录页、匿名访问被弹回登录页、登录失败后的回显、
|
||||
* 登出确认页)原样透传、不记录——它们只是渲染页面(HTTP 200),落库会显示成
|
||||
* 「未知用户 · 登录 · 200」,看起来像登录成功,真正的成败反而被淹没(现场实测反馈)。
|
||||
*
|
||||
* <p>操作者归属:Security 链最前无认证上下文(SecurityContext 由链内更晚位置的
|
||||
* ReactorContextWebFilter 写入订阅上下文,对链首过滤器不可见),统一记
|
||||
* {@link AuditLogSpec#UNKNOWN_USERNAME 未知用户}(既有兜底路径);登录尝试的账号
|
||||
@@ -30,13 +35,12 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* 并进入告警负载(功能评审 P0-1),账号归属信息不受影响。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||
* {@code error} 参数区分,不能只看状态码)。
|
||||
* 回调给 {@link LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否
|
||||
* 跳回登录页区分,不能只看状态码)。
|
||||
*
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||
* 与筛选;HTTP 状态码仍如实记录。
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):失败的 POST {@code /login} 落库
|
||||
* 标注登录失败,供列表红色标记与筛选;HTTP 状态码仍如实记录。
|
||||
*
|
||||
* <p>任何失败均静默降级(记录器与告警服务内部兜底),绝不影响登录主流程(设计原则 4)。
|
||||
*/
|
||||
@@ -54,16 +58,17 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
var request = exchange.getRequest();
|
||||
var path = request.getPath().value();
|
||||
var method = request.getMethod().name();
|
||||
if (!isAuthEndpoint(path)) {
|
||||
// 非 /login、/logout 一律原样透传:不触碰请求体、不读会话,零附加开销
|
||||
if (!isAuthOperation(path, method)) {
|
||||
// 登录/登出页面的 GET 访问等非认证操作一律原样透传:不触碰请求体、不记录
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var loginAttempt = new LoginAttempt();
|
||||
var loginAttempted = isLoginAttempt(path, method);
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 登出与登录页 GET 原样透传
|
||||
var bodyPrepared = isLoginAttempt(path, method)
|
||||
// 登出原样透传
|
||||
var bodyPrepared = loginAttempted
|
||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||
: Mono.just(exchange);
|
||||
return bodyPrepared
|
||||
@@ -72,9 +77,10 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
writeMarker.onRequestComplete(request);
|
||||
var statusCode = statusOf(exchange);
|
||||
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
|
||||
// 以重定向目标是否含 error 参数区分;GET /login?error=... 为失败回显
|
||||
var loginFailed = isLoginFailed(path, method, statusCode, exchange, snapshot);
|
||||
if (isLoginAttempt(path, method)) {
|
||||
// 以重定向目标是否跳回登录页区分;登出不存在登录成败
|
||||
var loginFailed = loginAttempted && LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
if (loginAttempted) {
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 成功清零计数、失败累计,独立于审计记录
|
||||
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
|
||||
@@ -90,21 +96,4 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
var status = exchange.getResponse().getStatusCode();
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败判定(LoginOutcome):POST {@code /login} 按状态码 + 重定向目标判定
|
||||
* (表单登录成败均为 302,以 Location 是否含 {@code error} 参数区分);
|
||||
* 登出与登录页 GET 仅失败回显({@code GET /login?error=...},HTTP 200)判为失败。
|
||||
*/
|
||||
private static boolean isLoginFailed(String path, String method, Integer statusCode,
|
||||
ServerWebExchange exchange, RequestSnapshot snapshot) {
|
||||
if (isLoginAttempt(path, method)) {
|
||||
return LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
}
|
||||
if ("GET".equals(method)) {
|
||||
return LoginOutcome.isFailureEcho(snapshot.getFullPath());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,18 @@ import java.util.Set;
|
||||
* <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
|
||||
* 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
|
||||
* 可获得认证用户上下文);</li>
|
||||
* <li>认证端点 {@code /login}、{@code /logout} 精确匹配({@link #isAuthEndpoint},
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 消费)——登录端点不在 /apis/** 下,且
|
||||
* 表单登录/登出过滤器命中请求后直接完成响应、不再向下游传递,链尾的
|
||||
* AfterSecurityWebFilter 永远看不到(P0 缺陷实测),因此必须在 Security 链之前
|
||||
* 独立捕获。</li>
|
||||
* <li>认证操作 {@code POST /login}(登录尝试)与 {@code POST /logout}(登出)精确匹配
|
||||
* ({@link #isAuthOperation},由 {@link AuthEndpointAuditWebFilter} 消费)——
|
||||
* 登录/登出端点不在 /apis/** 下,且表单登录/登出过滤器命中请求后直接完成响应、
|
||||
* 不再向下游传递,链尾的 AfterSecurityWebFilter 永远看不到(P0 缺陷实测),
|
||||
* 因此必须在 Security 链之前独立捕获。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录/登出页面的 GET 访问不是操作,不记录({@link #isAuthEndpoint} 仅用于路径归类):
|
||||
* 打开登录页、匿名访问被弹回登录页({@code /login?authentication_required})、登录失败
|
||||
* 后的回显({@code /login?error=...})、登出确认页都只是渲染页面(HTTP 200),若落库
|
||||
* 会显示成「未知用户 · 登录 · 200」,看起来像登录成功,而真正的登录尝试是 POST /login。
|
||||
*
|
||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||
*/
|
||||
public final class CaptureRule {
|
||||
@@ -24,16 +29,19 @@ public final class CaptureRule {
|
||||
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
|
||||
public static final String APIS_PREFIX = "/apis/";
|
||||
|
||||
/** 登录端点(告警通道唯一触发路径;登出与登录页 GET 不算登录尝试)。 */
|
||||
/** 登录端点(告警通道唯一触发路径;登录页 GET 不算登录尝试)。 */
|
||||
public static final String LOGIN_ENDPOINT = "/login";
|
||||
|
||||
/** 登出端点(POST 为登出操作;GET 为登出确认页)。 */
|
||||
public static final String LOGOUT_ENDPOINT = "/logout";
|
||||
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否命中捕获规则。path 为不含查询串的请求路径。
|
||||
*
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证端点由 {@link #isAuthEndpoint} 单独判定、
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证操作由 {@link #isAuthOperation} 单独判定、
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
|
||||
* 互不重叠,不会重复记录。
|
||||
*/
|
||||
@@ -44,11 +52,20 @@ public final class CaptureRule {
|
||||
return method != null && WRITE_METHODS.contains(method);
|
||||
}
|
||||
|
||||
/** 是否为登录/登出端点(由 {@link AuthEndpointAuditWebFilter} 捕获)。 */
|
||||
/** 是否为登录/登出端点(仅用于路径归类,不代表需要记录)。 */
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证操作(由 {@link AuthEndpointAuditWebFilter} 捕获):{@code POST /login}
|
||||
* 与 {@code POST /logout}。登录/登出页面的 GET 访问不是操作,不记录。
|
||||
*/
|
||||
public static boolean isAuthOperation(String path, String method) {
|
||||
return isLoginAttempt(path, method)
|
||||
|| "POST".equals(method) && LOGOUT_ENDPOINT.equals(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||
|
||||
@@ -9,9 +9,15 @@ import java.util.Arrays;
|
||||
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
|
||||
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
|
||||
* 因此登录结果须结合重定向目标判定,不能只看状态码。
|
||||
*
|
||||
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把失败
|
||||
* 登录记成成功,远比把异常响应记成失败更糟。
|
||||
*/
|
||||
public final class LoginOutcome {
|
||||
|
||||
/** 登录页路径:重定向回登录页即表示没有登录成功。 */
|
||||
private static final String LOGIN_PAGE_PATH = "/login";
|
||||
|
||||
private LoginOutcome() {
|
||||
}
|
||||
|
||||
@@ -20,9 +26,9 @@ public final class LoginOutcome {
|
||||
*
|
||||
* <ul>
|
||||
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
|
||||
* <li>3xx → 重定向目标查询串含 {@code error} 参数 → 失败(表单登录失败统一重定向
|
||||
* 到 {@code /login?error=invalid-credential&method=...} 等,含无值的
|
||||
* {@code /login?error&method=...});其余重定向目标(成功 → {@code /uc}、
|
||||
* <li>3xx → 重定向目标跳回登录页(查询串含 {@code error} 参数,如
|
||||
* {@code /login?error=invalid-credential&method=...},或路径就是 {@code /login})
|
||||
* 或缺失 Location → 失败;其余重定向目标(成功 → {@code /uc}、
|
||||
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
|
||||
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
|
||||
* </ul>
|
||||
@@ -35,29 +41,17 @@ public final class LoginOutcome {
|
||||
return false;
|
||||
}
|
||||
if (statusCode >= 300 && statusCode < 400) {
|
||||
return location != null && hasErrorParam(location.getRawQuery());
|
||||
// 跳回登录页必然是失败:Halo 2.26 的四种失败重定向均带 error 参数,
|
||||
// 无参跳回登录页同样不可能是登录成功(成功只会去 /uc、已保存的原请求或 2FA 页)
|
||||
return location == null
|
||||
|| LOGIN_PAGE_PATH.equals(location.getPath())
|
||||
|| hasErrorParam(location.getRawQuery());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败回显判定:{@code GET /login} 且查询串含 {@code error} 参数。
|
||||
* 登录失败后 Halo 重定向到带 error 参数的登录页,浏览器随后渲染该页(HTTP 200);
|
||||
* 该请求是失败登录的回显而非独立操作,审计记录须标注登录失败而非「登录成功 200」。
|
||||
*/
|
||||
public static boolean isFailureEcho(String fullPath) {
|
||||
if (fullPath == null) {
|
||||
return false;
|
||||
}
|
||||
var queryStart = fullPath.indexOf('?');
|
||||
if (queryStart < 0 || !"/login".equals(fullPath.substring(0, queryStart))) {
|
||||
return false;
|
||||
}
|
||||
return hasErrorParam(fullPath.substring(queryStart + 1));
|
||||
}
|
||||
|
||||
/** 查询串是否含 {@code error} 参数(可为无值形式 {@code error})。 */
|
||||
private static boolean hasErrorParam(String query) {
|
||||
static boolean hasErrorParam(String query) {
|
||||
if (query == null || query.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -12,10 +12,10 @@ import java.util.Map;
|
||||
* 展示/导出由 {@link #describe} 推导中文短语,历史记录(无 action 字段)同样按
|
||||
* method/path 现场推导,不受影响。
|
||||
*
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code describeOperation}
|
||||
* 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS / SEGMENT_ACTIONS / ACTION_PHRASES /
|
||||
* ACTION_VERBS 映射与子动作解析规则),两处需同步修改。未识别的子动作回退为
|
||||
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code semanticAction} /
|
||||
* {@code describeOperation} 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS /
|
||||
* SEGMENT_ACTIONS / ACTION_PHRASES / ACTION_VERBS 映射与子动作解析规则),两处需同步修改。
|
||||
* 未识别的子动作回退为「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
final class OperationDescription {
|
||||
|
||||
@@ -65,17 +65,28 @@ final class OperationDescription {
|
||||
Map.entry("resetpassword", "resetpassword"));
|
||||
|
||||
/**
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向跳回登录页或 4xx/5xx)落库
|
||||
* 标注,供列表红色标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
* 升级前落库的失败回显页(GET {@code /login?error=...},HTTP 200)带同一标注。
|
||||
*/
|
||||
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||
|
||||
/**
|
||||
* 登录页访问语义动作键:GET {@code /login}(打开登录页、被弹回登录页、失败回显)。
|
||||
* 仅升级前落库的历史记录会出现——页面访问不是操作,现已不记录。
|
||||
*/
|
||||
static final String LOGIN_PAGE_ACTION = "login-page";
|
||||
|
||||
/** 登出页访问语义动作键:GET {@code /logout}(登出确认页),仅升级前的历史记录。 */
|
||||
static final String LOGOUT_PAGE_ACTION = "logout-page";
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||
Map.entry("login", "登录"),
|
||||
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||
Map.entry("logout", "登出"),
|
||||
Map.entry(LOGIN_PAGE_ACTION, "访问登录页"),
|
||||
Map.entry(LOGOUT_PAGE_ACTION, "访问登出页"),
|
||||
Map.entry("auth", "认证操作"),
|
||||
Map.entry("password", "修改密码"),
|
||||
Map.entry("resetpassword", "重置密码"));
|
||||
@@ -102,17 +113,26 @@ final class OperationDescription {
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径判定,
|
||||
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径与方法判定,
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别(未知方法等)返回 null,记录不标注。
|
||||
*
|
||||
* <p>认证端点按方法区分:POST 是登录/登出操作,其余方法是页面访问
|
||||
* ({@link #LOGIN_PAGE_ACTION} / {@link #LOGOUT_PAGE_ACTION});路径含 {@code error}
|
||||
* 参数的登录页是升级前落库的失败回显,无标注时现场推导为登录失败。
|
||||
*/
|
||||
static String actionOf(String method, String resourceType, String path) {
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
if ("/login".equals(cleanPath)) {
|
||||
return "login";
|
||||
var queryStart = path == null ? -1 : path.indexOf('?');
|
||||
if (queryStart >= 0
|
||||
&& LoginOutcome.hasErrorParam(path.substring(queryStart + 1))) {
|
||||
return LOGIN_FAILURE_ACTION;
|
||||
}
|
||||
return "POST".equals(method) ? "login" : LOGIN_PAGE_ACTION;
|
||||
}
|
||||
if ("/logout".equals(cleanPath)) {
|
||||
return "logout";
|
||||
return "POST".equals(method) ? "logout" : LOGOUT_PAGE_ACTION;
|
||||
}
|
||||
if ("auth".equals(resourceType)) {
|
||||
return "auth";
|
||||
@@ -132,6 +152,35 @@ final class OperationDescription {
|
||||
return METHOD_ACTIONS.get(method);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证端点的页面访问:{@code GET /login}、{@code GET /logout}(含查询串),
|
||||
* 即非 POST 的认证端点请求。页面访问不是登录/登出操作,结果不计成败;仅升级前
|
||||
* 落库的历史记录会出现。
|
||||
*/
|
||||
static boolean isAuthPageVisit(String method, String path) {
|
||||
if ("POST".equals(method)) {
|
||||
return false;
|
||||
}
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
return "/login".equals(cleanPath) || "/logout".equals(cleanPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录的语义动作键(展示、导出与结果判定共用):优先落库标注;认证端点的失败回显与
|
||||
* 页面访问(升级前落库为 login/logout 或无标注的历史记录)按方法与路径纠正;
|
||||
* 落库标注未识别时回退 method/path 现场推导(与前端 {@code semanticAction} 一致)。
|
||||
*/
|
||||
static String semanticAction(AuditLogSpec spec) {
|
||||
var derived = actionOf(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||
if (LOGIN_FAILURE_ACTION.equals(derived) || LOGIN_PAGE_ACTION.equals(derived)
|
||||
|| LOGOUT_PAGE_ACTION.equals(derived)) {
|
||||
return derived;
|
||||
}
|
||||
var stored = spec.getAction();
|
||||
return stored != null && describeAction(stored, spec.getResourceType()) != null
|
||||
? stored : derived;
|
||||
}
|
||||
|
||||
/** 由语义动作键推导中文描述;键为 null 或未识别返回 null(调用方回退 method 推导)。 */
|
||||
static String describeAction(String action, String resourceType) {
|
||||
if (action == null) {
|
||||
@@ -158,12 +207,12 @@ final class OperationDescription {
|
||||
}
|
||||
|
||||
/**
|
||||
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||
* 由落库 spec 推导操作中文描述(导出用):以 {@link #semanticAction} 为准
|
||||
* (含登录失败标注与页面访问纠正),无标注或未识别时回退为 method/path 现场推导
|
||||
* (与前端 {@code describeOperation} 一致)。
|
||||
*/
|
||||
static String describe(AuditLogSpec spec) {
|
||||
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||
var phrase = describeAction(semanticAction(spec), spec.getResourceType());
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
|
||||
@@ -116,9 +116,9 @@ class AuditExportEndpointTest {
|
||||
|
||||
@Test
|
||||
void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页
|
||||
// (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」;
|
||||
// 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)状态码落在
|
||||
// 2xx/3xx,结果列仍应为「失败」;描述列优先落库语义动作(登录失败)。
|
||||
// 升级前落库的失败回显页(GET /login?error=...,200,带同一标注)同样导出失败
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var failedFormLogin = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 302, "119.53.161.18", "Mozilla/5.0");
|
||||
@@ -140,6 +140,52 @@ class AuditExportEndpointTest {
|
||||
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportSuccessfulLoginAsSuccessInsteadOfBareRedirectCode() {
|
||||
// 登录成功(表单提交为 302):结果列写「成功」,与失败的「失败」对称
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var success = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth", null,
|
||||
"/login", 302, "116.179.32.88", "Mozilla/5.0");
|
||||
success.getSpec().setAction("login");
|
||||
stubSinglePage(List.of(success));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,admin,POST,auth,,/login,登录,,成功,302,116.179.32.88,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportAuthPageVisitsAsPageVisitInsteadOfLoginSuccess() {
|
||||
// 升级前落库的页面访问记录(GET /login、GET /logout,带着 login/logout 标注、
|
||||
// HTTP 200):原先导出为「登录,成功」,看起来像未知用户登录成功;
|
||||
// 现在描述列写「访问登录页/访问登出页」,结果列写「页面访问」(不计成败)
|
||||
var time = Instant.parse("2026-12-04T14:16:36Z");
|
||||
var bounced = auditLog("auditlog-1", time, "unknown", null, "GET", "auth", null,
|
||||
"/login?authentication_required", 200, "43.228.157.244", "Mozilla/5.0");
|
||||
bounced.getSpec().setAction("login");
|
||||
var opened = auditLog("auditlog-2", time.plusSeconds(9), "unknown", null, "GET", "auth",
|
||||
null, "/login", 200, "43.228.157.244", "Mozilla/5.0");
|
||||
opened.getSpec().setAction("login");
|
||||
var logoutConfirm = auditLog("auditlog-3", time.plusSeconds(60), "unknown", null,
|
||||
"GET", "auth", null, "/logout", 200, "127.0.0.1", "Mozilla/5.0");
|
||||
logoutConfirm.getSpec().setAction("logout");
|
||||
stubSinglePage(List.of(bounced, opened, logoutConfirm));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(4);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,,GET,auth,,/login?authentication_required,访问登录页,,页面访问,200"
|
||||
+ ",43.228.157.244,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(9))
|
||||
+ ",unknown,,GET,auth,,/login,访问登录页,,页面访问,200,43.228.157.244,Mozilla/5.0");
|
||||
assertThat(lines[3]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,,GET,auth,,/logout,访问登出页,,页面访问,200,127.0.0.1,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
|
||||
@@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.after;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
@@ -69,6 +70,9 @@ class AuditFilterChainIntegrationTest {
|
||||
/** doFinally 回调为响应式异步执行,断言等待上限(毫秒)。 */
|
||||
private static final long CALLBACK_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** 「不记录」断言的等待时长(毫秒):确认透传请求在全链上始终没有触发记录。 */
|
||||
private static final long PASS_THROUGH_WAIT_MS = 500;
|
||||
|
||||
private static final String LOGIN_FORM = "username=admin&password=right-password";
|
||||
|
||||
private AuditRecorder recorder;
|
||||
@@ -212,16 +216,36 @@ class AuditFilterChainIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageVisitExactlyOnceThroughRealChain() {
|
||||
// GET /login 会流经全链(无终止过滤器命中):必须仅由链首过滤器记录一次,
|
||||
// 链尾过滤器不得重复记录(两个过滤器按 CaptureRule 分治、互不重叠)
|
||||
void shouldNotRecordLoginPageVisitThroughRealChain() {
|
||||
// 登录页的 GET 访问不是操作:打开登录页、被弹回登录页(?authentication_required)、
|
||||
// 登录失败后的回显(?error=...)都只渲染页面,全链任何位置都不得落库——
|
||||
// 否则列表里全是「未知用户 · 登录 · 200」,真正的登录成败被淹没
|
||||
for (var path : List.of("/login", "/login?authentication_required",
|
||||
"/login?error=invalid-credential&method=local")) {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.get(path)
|
||||
.build());
|
||||
|
||||
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||
}
|
||||
|
||||
// 真实链的记录回调可能异步晚于 block() 返回:等待一段时间后仍为零调用才算数
|
||||
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
|
||||
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordLogoutConfirmPageThroughRealChain() {
|
||||
// 登出确认页(GET /logout)同样只是页面访问
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/logout")
|
||||
.build());
|
||||
|
||||
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||
|
||||
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
|
||||
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
|
||||
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
|
||||
@@ -106,13 +106,16 @@ class AuditQueryEndpointTest {
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// failure = statusCode >= 400(无上界)或语义动作标注 login-failure
|
||||
// (登录失败的 HTTP 状态码可能为 200/302)
|
||||
// failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,仅凭状态码识别不出)
|
||||
// 或 4xx/5xx;页面访问记录(非 POST 的 /login、/logout)不计成败,予以排除
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("400")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
.contains("login-failure")
|
||||
.contains("spec.method")
|
||||
.contains("/login")
|
||||
.contains("/logout");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -126,10 +129,49 @@ class AuditQueryEndpointTest {
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
|
||||
// 与页面访问记录(升级前落库的 GET /login、GET /logout,HTTP 200)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
.contains("login-failure")
|
||||
.contains("spec.method")
|
||||
.contains("/login")
|
||||
.contains("/logout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExcludePageVisitsWhenFilteringByLoginOrLogoutAction() {
|
||||
// 升级前落库的页面访问记录带着 login/logout 标注,但展示为「访问登录页/登出页」:
|
||||
// 按语义动作筛登录/登出操作时不混入
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.action=login")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
assertThat(condition)
|
||||
.contains("spec.action")
|
||||
.contains("login")
|
||||
.contains("spec.method")
|
||||
.contains("/login");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepPlainEqualityForOtherSemanticActions() {
|
||||
// 其余语义动作的等值筛选不带页面访问排除条件
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.action=login-failure")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
assertThat(condition).doesNotContain("spec.method");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -120,7 +120,7 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
|
||||
// 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true,
|
||||
// 表单登录失败(302 重定向回跳登录页):过滤器传入 loginFailed=true,
|
||||
// 语义动作标注 login-failure;状态码仍如实记录 302
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
@@ -133,22 +133,16 @@ class AuditRecorderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailureEcho() {
|
||||
// 登录失败回显(GET /login?error=... 页面渲染 HTTP 200):同样标注登录失败
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.get("http://localhost/login?error=invalid-credential&method=local")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 200,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
void shouldAnnotateLogoutWithoutFailureMark() {
|
||||
// 登出(POST /logout)是认证操作但不是登录尝试:语义动作 logout,不标注登录失败
|
||||
recorder.record(snapshotOf("/logout"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(200);
|
||||
assertThat(spec.getPath()).isEqualTo("/login?error=invalid-credential&method=local");
|
||||
assertThat(spec.getAction()).isEqualTo("logout");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(302);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 结果语义测试(AuditResult):结果筛选与 CSV 导出共用的成败判定。
|
||||
* 登录失败不能只看状态码(表单登录失败的 HTTP 状态码与成功相同,均为 302);
|
||||
* 认证端点的页面访问(升级前落库的 GET 记录)不是操作,不计成败。
|
||||
*/
|
||||
class AuditResultTest {
|
||||
|
||||
private static AuditLogSpec spec(String method, String path, Integer statusCode,
|
||||
String action) {
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setMethod(method);
|
||||
spec.setResourceType("auth");
|
||||
spec.setPath(path);
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setAction(action);
|
||||
return spec;
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginFailureIsFailureRegardlessOfStatusCode() {
|
||||
// 表单登录失败:302(与成功相同的状态码),只能靠落库标注识别
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 302, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
// XHR 登录失败、CSRF 拦截
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 401, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 403, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
// 升级前落库的失败回显(GET /login?error=...,HTTP 200):带标注或由路径推导
|
||||
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200,
|
||||
"login-failure"))).isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200, null)))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulLoginIsSuccess() {
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 302, "login")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 200, "login")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authPageVisitsAreNeitherSuccessNorFailure() {
|
||||
// 升级前落库的页面访问记录:当时带着 login/logout 标注、HTTP 200——
|
||||
// 原先显示为绿色「登录 200」,看起来像未知用户登录成功
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 200, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/login?authentication_required", 200, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/logout", 200, "logout")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 200, null)))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 500, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryRecordsFollowStatusCode() {
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 201, "create")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 302, "create")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 403, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 500, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", null, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsAreUsedForCsvResultColumn() {
|
||||
assertThat(AuditResult.SUCCESS.label()).isEqualTo("成功");
|
||||
assertThat(AuditResult.FAILURE.label()).isEqualTo("失败");
|
||||
assertThat(AuditResult.PAGE_VISIT.label()).isEqualTo("页面访问");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -27,8 +28,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
/**
|
||||
* 认证端点捕获过滤器行为测试(P0 修复):POST /login、POST /logout 必须产生审计记录
|
||||
* (真实环境中表单登录/登出过滤器在链尾过滤器之前直接完成响应,因此由本过滤器在
|
||||
* Security 链之前承接)。操作者统一为未知用户,登录尝试账号由请求体白名单提取;
|
||||
* 登录失败告警回调仅发生在 POST /login;非认证端点请求一律透传、零副作用。
|
||||
* Security 链之前承接)。登录/登出页面的 GET 访问不是操作,一律透传不记录。
|
||||
* 操作者统一为未知用户,登录尝试账号由请求体白名单提取;登录失败告警回调仅发生在
|
||||
* POST /login;非认证端点请求一律透传、零副作用。
|
||||
*/
|
||||
class AuthEndpointAuditWebFilterTest {
|
||||
|
||||
@@ -130,34 +132,75 @@ class AuthEndpointAuditWebFilterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageVisitWithoutFailureMark() {
|
||||
// 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
void shouldPassThroughLoginPageVisitsWithoutRecording() {
|
||||
// 登录页的 GET 访问不是登录操作:打开登录页、匿名访问被弹回登录页
|
||||
// (/login?authentication_required)、登录失败后的回显(/login?error=...)
|
||||
// 都只渲染页面(HTTP 200)。原先一律落库为「未知用户 · 登录 · 200」,在列表里
|
||||
// 与登录成功无法区分(现场反馈:全是成功、登录失败也显示成功)——现在原样透传
|
||||
for (var path : List.of("/login", "/login?authentication_required",
|
||||
"/login?error=invalid-credential&method=local", "/login?logout")) {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
}
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
verify(writeMarker, never()).onRequestComplete(any());
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageErrorEchoAsLoginFailure() {
|
||||
// 登录失败回显:GET /login?error=... 页面渲染 HTTP 200,标注登录失败,
|
||||
// 但不是登录尝试、不触发告警
|
||||
void shouldPassThroughLogoutConfirmPageWithoutRecording() {
|
||||
// 登出确认页(GET /logout)同样只是页面访问,不是登出操作
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login?error=invalid-credential&method=local")
|
||||
.get("/logout")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureWhenRedirectedBackToLoginWithoutErrorParam() {
|
||||
// 302 跳回登录页且不带 error 参数:不可能是登录成功(成功只会去 /uc、已保存的
|
||||
// 原请求或 2FA 页),同样判失败——只有响应明确确认才算成功
|
||||
var exchange = loginExchange("bob", "wrong");
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
|
||||
URI.create("/login")))).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
|
||||
eq("bob"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureWhenRedirectHasNoLocation() {
|
||||
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
|
||||
var exchange = loginExchange("bob", "wrong");
|
||||
WebFilterChain foundWithoutLocation = ex -> {
|
||||
ex.getResponse().setStatusCode(HttpStatus.FOUND);
|
||||
return Mono.empty();
|
||||
};
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, foundWithoutLocation)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
|
||||
}
|
||||
|
||||
private static MockServerWebExchange loginExchange(String username, String password) {
|
||||
var body = "username=" + username + "&password=" + password;
|
||||
return MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -29,7 +29,7 @@ class CaptureRuleTest {
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureAuthEndpointsInApisRule() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 独立捕获(isAuthEndpoint),
|
||||
// 认证操作由 AuthEndpointAuditWebFilter 独立捕获(isAuthOperation),
|
||||
// 通用规则不再包含,两个过滤器按规则分治、互不重叠
|
||||
assertThat(shouldCapture("/login", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/login", "GET")).isFalse();
|
||||
@@ -71,4 +71,21 @@ class CaptureRuleTest {
|
||||
assertThat(CaptureRule.isLoginAttempt(null, "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/login", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatOnlyPostAsAuthOperation() {
|
||||
// 认证操作 = POST /login(登录尝试)+ POST /logout(登出)
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "POST")).isTrue();
|
||||
assertThat(CaptureRule.isAuthOperation("/logout", "POST")).isTrue();
|
||||
// 登录/登出页面的 GET 访问不是操作:打开登录页、被弹回登录页、失败回显、登出确认页
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "GET")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/logout", "GET")).isFalse();
|
||||
// 其余方法与路径一律不算
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "HEAD")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "PUT")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/loginx", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/console/login", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation(null, "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/login", null)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import org.junit.jupiter.api.Test;
|
||||
* 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为
|
||||
* 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON
|
||||
* 请求以 200/401 区分成败,成败判定必须结合重定向目标。
|
||||
*
|
||||
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把
|
||||
* 失败登录记成成功,远比把异常响应记成失败更糟。
|
||||
*/
|
||||
class LoginOutcomeTest {
|
||||
|
||||
@@ -34,26 +37,42 @@ class LoginOutcomeTest {
|
||||
// 两步验证:302 → /challenges/two-factor/totp
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/challenges/two-factor/totp"))).isFalse();
|
||||
// 登录前被弹回的原请求:302 → 已保存的受保护页面
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/console/posts"))).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("http://blog.guichumo.com/console/posts?page=1"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formFailureRedirectWithErrorParamIsFailure() {
|
||||
// 表单登录失败:302 → /login?error=invalid-credential&method=local
|
||||
// (Halo 2.26.1 LoginFailureHandler 的四种失败重定向:invalid-credential /
|
||||
// account-disabled / rate-limit-exceeded / 无值 error)
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=invalid-credential&method=local"))).isTrue();
|
||||
// 账号禁用/限流等其他失败码同样含 error 参数
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=account-disabled&method=local"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=rate-limit-exceeded&method=local"))).isTrue();
|
||||
// 兜底失败分支:error 参数无值(/login?error&method=...)
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?error&method=local"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("http://blog.guichumo.com/login?error=invalid-credential"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectWithoutLocationIsNotFailure() {
|
||||
// 3xx 但缺失 Location(无法确认失败):按成功处理,不凭空判失败
|
||||
assertThat(LoginOutcome.isFailure(302, null)).isFalse();
|
||||
void redirectBackToLoginPageWithoutErrorParamIsFailure() {
|
||||
// 跳回登录页必然是失败:成功只会去 /uc、已保存的原请求或 2FA 页。
|
||||
// 不依赖 error 参数——宿主或第三方登录扩展换了失败重定向格式也不会把失败记成成功
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?authentication_required")))
|
||||
.isTrue();
|
||||
assertThat(LoginOutcome.isFailure(307, URI.create("/login?logout"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectWithoutLocationIsFailure() {
|
||||
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
|
||||
assertThat(LoginOutcome.isFailure(302, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,41 +82,22 @@ class LoginOutcomeTest {
|
||||
assertThat(LoginOutcome.isFailure(0, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientAndServerErrorsAreFailure() {
|
||||
// CSRF 拦截(403)、服务端异常(500)同为失败
|
||||
assertThat(LoginOutcome.isFailure(403, URI.create("/login"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(500, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorParamNameMustMatchExactly() {
|
||||
// 含 error 字样的其他参数(如 errors=1)不算失败标记
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/uc?errors=1"))).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?errors=1"))).isFalse();
|
||||
}
|
||||
|
||||
// ===== GET /login?error=...:失败回显 =====
|
||||
|
||||
@Test
|
||||
void loginPageWithErrorParamIsFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error=invalid-credential&method=local"))
|
||||
.isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error&method=local")).isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local&error=invalid-credential"))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainLoginPageIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherEndpointsAreNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/logout?error=x")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/core.halo.run/v1alpha1/login?error=x"))
|
||||
.isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/uc?error=x")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOrQuerylessPathIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho(null)).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/content.halo.run/v1alpha1/posts")).isFalse();
|
||||
void loginPagePathMustMatchExactly() {
|
||||
// 仅路径恰为 /login 才算跳回登录页;/login-xxx 等前缀相同的路径不算
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login-callback"))).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,15 +12,24 @@ class OperationDescriptionTest {
|
||||
|
||||
@Test
|
||||
void shouldDescribeLoginEndpointIncludingQuery() {
|
||||
// POST /login 是登录操作;GET /login(含任意查询串)只是打开登录页
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.describe("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("登录");
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole"))
|
||||
.isEqualTo("访问登录页");
|
||||
assertThat(OperationDescription.describe("GET", "auth", "/login?authentication_required"))
|
||||
.isEqualTo("访问登录页");
|
||||
// 升级前落库的失败回显(GET /login?error=...)无标注时由 error 参数现场推导
|
||||
assertThat(OperationDescription.describe("GET", "auth",
|
||||
"/login?error=invalid-credential&method=local")).isEqualTo("登录失败");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeLogoutEndpoint() {
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出");
|
||||
// GET /logout 是登出确认页
|
||||
assertThat(OperationDescription.describe("GET", "auth", "/logout"))
|
||||
.isEqualTo("访问登出页");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,14 +113,46 @@ class OperationDescriptionTest {
|
||||
@Test
|
||||
void shouldDeriveLoginLogoutAuthActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/login")).isEqualTo("login");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("login");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/logout")).isEqualTo("logout");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/auth/other"))
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveAuthPageVisitsByMethod() {
|
||||
// 认证端点的页面访问(非 POST):打开登录页、被弹回登录页、登出确认页
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login"))
|
||||
.isEqualTo("login-page");
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?authentication_required")).isEqualTo("login-page");
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/logout"))
|
||||
.isEqualTo("logout-page");
|
||||
// 失败回显(路径含 error 参数)推导为登录失败
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?error=invalid-credential&method=local"))
|
||||
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login?error&method=local"))
|
||||
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
// 含 error 字样的其他参数不算失败标记
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login?errors=1"))
|
||||
.isEqualTo("login-page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectAuthPageVisits() {
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/login")).isTrue();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/login?error=x")).isTrue();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/logout")).isTrue();
|
||||
// POST 是真正的登录/登出操作
|
||||
assertThat(OperationDescription.isAuthPageVisit("POST", "/login")).isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("POST", "/logout")).isFalse();
|
||||
// 其余路径一律不算
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/apis/core.halo.run/v1alpha1/posts"))
|
||||
.isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/loginx")).isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveMethodActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "users",
|
||||
@@ -197,10 +238,15 @@ class OperationDescriptionTest {
|
||||
@Test
|
||||
void shouldDescribeFromActionKey() {
|
||||
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
||||
// 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显)
|
||||
// 登录失败语义动作(POST /login 失败,或升级前落库的 GET /login?error=... 失败回显)
|
||||
assertThat(OperationDescription.describeAction("login-failure", "auth"))
|
||||
.isEqualTo("登录失败");
|
||||
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
||||
// 认证端点的页面访问(升级前落库的历史 GET 记录)
|
||||
assertThat(OperationDescription.describeAction("login-page", "auth"))
|
||||
.isEqualTo("访问登录页");
|
||||
assertThat(OperationDescription.describeAction("logout-page", "auth"))
|
||||
.isEqualTo("访问登出页");
|
||||
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
||||
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
||||
assertThat(OperationDescription.describeAction("update", "posts")).isEqualTo("修改文章");
|
||||
@@ -244,4 +290,57 @@ class OperationDescriptionTest {
|
||||
bogus.setAction("bogus");
|
||||
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCorrectAuthPageVisitsRegardlessOfStoredAction() {
|
||||
// 升级前落库的页面访问记录带着 login/logout 标注(当时 GET 也被当成登录/登出记录):
|
||||
// 展示必须按方法纠正为页面访问,否则这些记录继续显示成「未知用户 · 登录」
|
||||
var loginPage = new AuditLogSpec();
|
||||
loginPage.setMethod("GET");
|
||||
loginPage.setResourceType("auth");
|
||||
loginPage.setPath("/login?authentication_required");
|
||||
loginPage.setAction("login");
|
||||
assertThat(OperationDescription.semanticAction(loginPage)).isEqualTo("login-page");
|
||||
assertThat(OperationDescription.describe(loginPage)).isEqualTo("访问登录页");
|
||||
|
||||
var logoutPage = new AuditLogSpec();
|
||||
logoutPage.setMethod("GET");
|
||||
logoutPage.setResourceType("auth");
|
||||
logoutPage.setPath("/logout");
|
||||
logoutPage.setAction("logout");
|
||||
assertThat(OperationDescription.semanticAction(logoutPage)).isEqualTo("logout-page");
|
||||
assertThat(OperationDescription.describe(logoutPage)).isEqualTo("访问登出页");
|
||||
|
||||
// 无标注的页面访问记录同样推导为页面访问
|
||||
var unannotated = new AuditLogSpec();
|
||||
unannotated.setMethod("GET");
|
||||
unannotated.setResourceType("auth");
|
||||
unannotated.setPath("/login");
|
||||
assertThat(OperationDescription.describe(unannotated)).isEqualTo("访问登录页");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepStoredActionForAuthOperations() {
|
||||
// POST 是真正的认证操作:落库标注优先(成功 login / 失败 login-failure / 登出 logout)
|
||||
var success = new AuditLogSpec();
|
||||
success.setMethod("POST");
|
||||
success.setResourceType("auth");
|
||||
success.setPath("/login");
|
||||
success.setAction("login");
|
||||
assertThat(OperationDescription.semanticAction(success)).isEqualTo("login");
|
||||
|
||||
var failure = new AuditLogSpec();
|
||||
failure.setMethod("POST");
|
||||
failure.setResourceType("auth");
|
||||
failure.setPath("/login");
|
||||
failure.setAction("login-failure");
|
||||
assertThat(OperationDescription.semanticAction(failure)).isEqualTo("login-failure");
|
||||
|
||||
var logout = new AuditLogSpec();
|
||||
logout.setMethod("POST");
|
||||
logout.setResourceType("auth");
|
||||
logout.setPath("/logout");
|
||||
logout.setAction("logout");
|
||||
assertThat(OperationDescription.semanticAction(logout)).isEqualTo("logout");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
deriveAction,
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
isAuthPageVisit,
|
||||
isLoginFailure,
|
||||
resultBadge,
|
||||
resultOutcome,
|
||||
SEMANTIC_ACTIONS,
|
||||
SYSTEM_USERNAME,
|
||||
UNKNOWN_USERNAME,
|
||||
@@ -28,27 +30,58 @@ function spec(overrides: Partial<AuditLogSpec>): AuditLogSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/** 升级前落库的登录页访问记录:GET、HTTP 200、带着 login 标注(当时 GET 也被当成登录记录)。 */
|
||||
function legacyLoginPageVisit(overrides: Partial<AuditLogSpec> = {}): AuditLogSpec {
|
||||
return spec({
|
||||
username: 'unknown',
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 200,
|
||||
remoteIp: '43.228.157.244',
|
||||
action: 'login',
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
describe('describeOperation', () => {
|
||||
it('登录端点(含查询串)描述为 登录', () => {
|
||||
it('登录端点:POST 描述为 登录,GET(含查询串)描述为 访问登录页', () => {
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
}))).toBe('登录')
|
||||
// GET /login?redirect_uri=... 也应识别为登录(spec.path 含查询串)
|
||||
// GET /login 只是打开登录页,不是登录操作(spec.path 含查询串同样如此)
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole',
|
||||
}))).toBe('登录')
|
||||
}))).toBe('访问登录页')
|
||||
// 匿名访问受保护页面被弹回登录页
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?authentication_required',
|
||||
}))).toBe('访问登录页')
|
||||
// 升级前落库的失败回显(GET /login?error=...)无标注时由 error 参数现场推导
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
}))).toBe('登录失败')
|
||||
})
|
||||
|
||||
it('登出端点描述为 登出', () => {
|
||||
it('登出端点:POST 描述为 登出,GET(登出确认页)描述为 访问登出页', () => {
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
}))).toBe('登出')
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
}))).toBe('访问登出页')
|
||||
})
|
||||
|
||||
it('auth 类型但非登录/登出路径回退为 认证操作', () => {
|
||||
@@ -147,25 +180,26 @@ describe('describeOperation', () => {
|
||||
})
|
||||
|
||||
describe('deriveAction 语义动作推导', () => {
|
||||
it('登录/登出/认证操作由路径判定(含查询串剥离)', () => {
|
||||
it('登录/登出按方法区分:POST 是操作,GET 是页面访问;认证操作由路径判定', () => {
|
||||
expect(deriveAction('POST', 'auth', '/login')).toBe('login')
|
||||
expect(deriveAction('GET', 'auth', '/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com'))
|
||||
.toBe('login')
|
||||
.toBe('login-page')
|
||||
expect(deriveAction('GET', 'auth', '/login?authentication_required')).toBe('login-page')
|
||||
expect(deriveAction('POST', 'auth', '/logout')).toBe('logout')
|
||||
expect(deriveAction('GET', 'auth', '/logout')).toBe('logout-page')
|
||||
expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth')
|
||||
})
|
||||
|
||||
it('登录失败回显(GET /login?error=...)推导为 login-failure', () => {
|
||||
// 登录失败后 Halo 重定向到带 error 参数的登录页,页面渲染 HTTP 200;
|
||||
// 历史记录(无落库标注)由路径中的 error 参数现场推导
|
||||
// 升级前落库的失败回显页(HTTP 200)无标注时由路径中的 error 参数现场推导
|
||||
expect(deriveAction('GET', 'auth', '/login?error=invalid-credential&method=local'))
|
||||
.toBe('login-failure')
|
||||
// 兜底失败分支:error 参数无值
|
||||
expect(deriveAction('GET', 'auth', '/login?error&method=local')).toBe('login-failure')
|
||||
// 首次打开登录页(无 error 参数)不是失败回显
|
||||
expect(deriveAction('GET', 'auth', '/login?method=local')).toBe('login')
|
||||
// 不带 error 参数的登录页只是页面访问
|
||||
expect(deriveAction('GET', 'auth', '/login?method=local')).toBe('login-page')
|
||||
// 含 error 字样的其他参数不算失败标记
|
||||
expect(deriveAction('GET', 'auth', '/login?errors=1')).toBe('login')
|
||||
expect(deriveAction('GET', 'auth', '/login?errors=1')).toBe('login-page')
|
||||
})
|
||||
|
||||
it('子动作段优先于 HTTP 方法', () => {
|
||||
@@ -236,92 +270,126 @@ describe('describeOperation 落库标注优先', () => {
|
||||
})
|
||||
|
||||
it('登录失败标注(login-failure)描述为 登录失败', () => {
|
||||
// 表单登录失败(POST /login,302)与失败回显页(GET /login?error=...,200)
|
||||
// 均落库标注,描述为 登录失败 而非按路径推导出的 登录
|
||||
// 表单登录失败(POST /login,302)落库标注 login-failure,描述为 登录失败
|
||||
// 而非按路径推导出的 登录
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
// 升级前落库的失败回显页(GET /login?error=...,200)带同一标注
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
// 历史回显记录(无落库标注)由路径现场推导,同样得到 登录失败
|
||||
// 无标注的历史回显记录由路径现场推导,同样得到 登录失败
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
}))).toBe('登录失败')
|
||||
})
|
||||
|
||||
it('升级前落库的登录页访问记录(GET + login 标注)纠正为 访问登录页,不再显示成登录', () => {
|
||||
// 当时登录页的 GET 访问被记成「未知用户 · 登录 · 200」,看起来像登录成功
|
||||
expect(describeOperation(legacyLoginPageVisit())).toBe('访问登录页')
|
||||
expect(describeOperation(legacyLoginPageVisit({
|
||||
path: '/login?authentication_required',
|
||||
}))).toBe('访问登录页')
|
||||
expect(describeOperation(legacyLoginPageVisit({
|
||||
path: '/logout',
|
||||
action: 'logout',
|
||||
}))).toBe('访问登出页')
|
||||
// 无标注的页面访问记录同样推导为页面访问
|
||||
expect(describeOperation(legacyLoginPageVisit({ action: undefined }))).toBe('访问登录页')
|
||||
// POST 才是登录/登出操作,落库标注照常生效
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
action: 'login',
|
||||
}))).toBe('登录')
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
action: 'logout',
|
||||
}))).toBe('登出')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLoginFailure / resultBadge 登录失败结果展示', () => {
|
||||
it('落库标注 login-failure 判定为登录失败(HTTP 200/302 也可能是失败)', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
describe('isAuthPageVisit 认证端点的页面访问', () => {
|
||||
it('GET /login、GET /logout(含查询串)是页面访问;POST 是认证操作', () => {
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login?authentication_required' })))
|
||||
.toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login?error=x' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/logout' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'POST', path: '/login' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'POST', path: '/logout' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/console/' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/apis/core.halo.run/v1alpha1/login' })))
|
||||
.toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resultOutcome / resultBadge 结果语义', () => {
|
||||
it('登录失败为 failure:红色 失败,不显示裸状态码(表单失败是 302、失败回显是 200)', () => {
|
||||
const failed = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
})
|
||||
expect(isLoginFailure(failed)).toBe(true)
|
||||
expect(resultOutcome(failed)).toBe('failure')
|
||||
expect(resultBadge(failed)).toEqual({ text: '失败', class: 'status-fail' })
|
||||
// XHR 登录失败(401)、CSRF 拦截(403)
|
||||
expect(resultOutcome({ ...failed, statusCode: 401 })).toBe('failure')
|
||||
expect(resultOutcome({ ...failed, statusCode: 403 })).toBe('failure')
|
||||
// 升级前落库的失败回显页(GET,200):带标注或由路径推导
|
||||
const echo = spec({
|
||||
method: 'GET', resourceType: 'auth', statusCode: 200,
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
})
|
||||
expect(resultOutcome({ ...echo, action: 'login-failure' })).toBe('failure')
|
||||
expect(isLoginFailure(echo)).toBe(true)
|
||||
expect(resultBadge({ ...echo, action: 'login-failure' }))
|
||||
.toEqual({ text: '失败', class: 'status-fail' })
|
||||
})
|
||||
|
||||
it('历史回显记录(无落库标注)由路径现场推导', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
}))).toBe(true)
|
||||
// 表单登录失败的历史记录(POST /login,302)无法由路径推导,仍按登录展示
|
||||
// (升级后新记录落库标注,不再有此局限)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
}))).toBe(false)
|
||||
// 成功登录(POST /login,302 → /uc)不是登录失败
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login',
|
||||
}))).toBe(false)
|
||||
it('登录成功为 success:绿色 成功(表单成功同样是 302,裸状态码读不出成败)', () => {
|
||||
const success = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302, action: 'login',
|
||||
})
|
||||
expect(isLoginFailure(success)).toBe(false)
|
||||
expect(resultOutcome(success)).toBe('success')
|
||||
expect(resultBadge(success)).toEqual({ text: '成功', class: 'status-ok' })
|
||||
// XHR 登录成功(200)
|
||||
expect(resultBadge({ ...success, statusCode: 200 }))
|
||||
.toEqual({ text: '成功', class: 'status-ok' })
|
||||
})
|
||||
|
||||
it('登录失败记录结果徽标为红色 失败(不显示裸状态码)', () => {
|
||||
// 失败回显页 HTTP 200:修复前显示绿色 200,误读为登录成功
|
||||
expect(resultBadge(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
// 表单登录失败 302 重定向:同理
|
||||
expect(resultBadge(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
it('登录页访问记录为 page-visit:灰色 —,既不算成功也不算失败', () => {
|
||||
// 升级前落库的 GET /login(HTTP 200、带 login 标注)原先显示绿色「200」,
|
||||
// 看起来像未知用户登录成功;现在按方法纠正为页面访问
|
||||
const visit = legacyLoginPageVisit({ path: '/login?authentication_required' })
|
||||
expect(isLoginFailure(visit)).toBe(false)
|
||||
expect(resultOutcome(visit)).toBe('page-visit')
|
||||
expect(resultBadge(visit)).toEqual({ text: '—', class: 'status-na' })
|
||||
expect(resultOutcome(legacyLoginPageVisit({ path: '/logout', action: 'logout' })))
|
||||
.toBe('page-visit')
|
||||
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
|
||||
expect(resultOutcome(legacyLoginPageVisit({ action: undefined }))).toBe('page-visit')
|
||||
expect(resultOutcome(legacyLoginPageVisit({ statusCode: 500 }))).toBe('page-visit')
|
||||
})
|
||||
|
||||
it('非登录记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||
it('登出与其他记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||
const logout = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/logout', statusCode: 302, action: 'logout',
|
||||
})
|
||||
expect(resultBadge(logout)).toEqual({ text: '302', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 200 }))).toEqual({ text: '200', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 302 }))).toEqual({ text: '302', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 403 }))).toEqual({ text: '403', class: 'status-fail' })
|
||||
|
||||
@@ -107,11 +107,19 @@ const SEGMENT_ACTIONS: Record<string, string> = {
|
||||
/** 登录失败语义动作键(与后端 OperationDescription.LOGIN_FAILURE_ACTION 同步)。 */
|
||||
const LOGIN_FAILURE_ACTION = 'login-failure'
|
||||
|
||||
/** 登录页访问(打开登录页、被弹回登录页、失败回显):仅升级前落库的历史记录。 */
|
||||
const LOGIN_PAGE_ACTION = 'login-page'
|
||||
|
||||
/** 登出页访问(登出确认页):仅升级前落库的历史记录。 */
|
||||
const LOGOUT_PAGE_ACTION = 'logout-page'
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼资源名)。 */
|
||||
const ACTION_PHRASES: Record<string, string> = {
|
||||
login: '登录',
|
||||
[LOGIN_FAILURE_ACTION]: '登录失败',
|
||||
logout: '登出',
|
||||
[LOGIN_PAGE_ACTION]: '访问登录页',
|
||||
[LOGOUT_PAGE_ACTION]: '访问登出页',
|
||||
auth: '认证操作',
|
||||
password: '修改密码',
|
||||
resetpassword: '重置密码',
|
||||
@@ -174,7 +182,7 @@ function pathWithoutQuery(path?: string | null): string {
|
||||
|
||||
/**
|
||||
* 查询串是否含 error 参数(可为无值形式 error)。
|
||||
* 登录失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||
* 升级前落库的失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||
*/
|
||||
function hasErrorParam(path?: string | null): boolean {
|
||||
if (!path) {
|
||||
@@ -190,26 +198,40 @@ function hasErrorParam(path?: string | null): boolean {
|
||||
.some((pair) => (pair.indexOf('=') < 0 ? pair : pair.slice(0, pair.indexOf('='))) === 'error')
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证端点的页面访问(GET /login、GET /logout,含查询串):打开登录页、匿名访问
|
||||
* 被弹回登录页(?authentication_required)、失败回显(?error=...)、登出确认页。
|
||||
* 页面访问不是登录/登出操作,结果不计成败;现已不再记录,只有升级前落库的历史记录
|
||||
* 会出现——当时它们被记成「未知用户 · 登录 · 200」,看起来像登录成功。
|
||||
*/
|
||||
export function isAuthPageVisit(spec: Pick<AuditLogSpec, 'method' | 'path'>): boolean {
|
||||
if (spec.method === 'POST') {
|
||||
return false
|
||||
}
|
||||
const cleanPath = pathWithoutQuery(spec.path)
|
||||
return cleanPath === '/login' || cleanPath === '/logout'
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致):
|
||||
* 登录/登录失败/登出/认证操作由路径判定(GET /login?error=... 为登录失败回显),
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 认证端点按方法区分——POST 是登录/登出操作,其余方法是页面访问,路径带 error 参数的
|
||||
* 登录页是失败回显;子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别返回 null。
|
||||
*
|
||||
* <p>历史局限:升级前落库的表单登录失败记录(POST /login,302)无法由路径重新
|
||||
* 推导出失败,仍推导为 login;仅回显页(GET,error 参数在路径中)可现场推导。
|
||||
*/
|
||||
export function deriveAction(
|
||||
method: string,
|
||||
resourceType: string,
|
||||
path?: string | null,
|
||||
path?: string | null
|
||||
): string | null {
|
||||
const cleanPath = pathWithoutQuery(path)
|
||||
if (cleanPath === '/login') {
|
||||
return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login'
|
||||
if (hasErrorParam(path)) {
|
||||
return LOGIN_FAILURE_ACTION
|
||||
}
|
||||
return method === 'POST' ? 'login' : LOGIN_PAGE_ACTION
|
||||
}
|
||||
if (cleanPath === '/logout') {
|
||||
return 'logout'
|
||||
return method === 'POST' ? 'logout' : LOGOUT_PAGE_ACTION
|
||||
}
|
||||
if (resourceType === 'auth') {
|
||||
return 'auth'
|
||||
@@ -240,19 +262,36 @@ function describeFromAction(action: string | null, resourceType: string): string
|
||||
return verb ? `${verb}${RESOURCE_LABELS[resourceType] ?? resourceType}` : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录的语义动作键(展示与结果判定共用,与后端 OperationDescription.semanticAction 一致):
|
||||
* 优先落库标注(spec.action);认证端点的失败回显与页面访问——升级前落库为 login/logout
|
||||
* 或无标注的历史记录——按方法与路径纠正;落库标注未识别时回退 method/path 现场推导。
|
||||
*/
|
||||
function semanticAction(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): string | null {
|
||||
const derived = deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
if (
|
||||
derived === LOGIN_FAILURE_ACTION ||
|
||||
derived === LOGIN_PAGE_ACTION ||
|
||||
derived === LOGOUT_PAGE_ACTION
|
||||
) {
|
||||
return derived
|
||||
}
|
||||
return spec.action && describeFromAction(spec.action, spec.resourceType) ? spec.action : derived
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作描述(这条操作真正干了什么):推导中文短语,
|
||||
* 如 登录、登出、新建用户、修改文章、发布文章、启用插件、修改密码。
|
||||
*
|
||||
* <p>优先使用落库的语义动作标注(spec.action);历史记录(无 action 字段)由
|
||||
* method/path 现场推导,同样适用。识别失败回退为「method 动词 + 资源名」,
|
||||
* 未识别的资源类型直接使用原始 resourceType。
|
||||
* <p>以记录的语义动作键为准(含登录失败标注与页面访问纠正);识别失败回退为
|
||||
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
export function describeOperation(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>,
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): string {
|
||||
const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
const fromAction = describeFromAction(action, spec.resourceType)
|
||||
const fromAction = describeFromAction(semanticAction(spec), spec.resourceType)
|
||||
if (fromAction) {
|
||||
return fromAction
|
||||
}
|
||||
@@ -277,23 +316,49 @@ export function isSuccessful(statusCode?: number | null): boolean {
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
}
|
||||
|
||||
/** 结果语义(与后端 AuditResult 同一规则,结果筛选与 CSV 导出沿用)。 */
|
||||
export type ResultOutcome = 'success' | 'failure' | 'page-visit'
|
||||
|
||||
type ResultSpec = Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action' | 'statusCode'>
|
||||
|
||||
/**
|
||||
* 记录的结果语义:登录失败(语义动作 login-failure,表单登录失败的 HTTP 状态码与成功
|
||||
* 相同、均为 302,只能靠标注识别)为 failure;认证端点的页面访问(升级前落库的 GET
|
||||
* 记录)不是操作,为 page-visit,不计成败;其余按状态码 2xx/3xx 判成功。
|
||||
*/
|
||||
export function resultOutcome(spec: ResultSpec): ResultOutcome {
|
||||
if (isLoginFailure(spec)) {
|
||||
return 'failure'
|
||||
}
|
||||
if (isAuthPageVisit(spec)) {
|
||||
return 'page-visit'
|
||||
}
|
||||
return isSuccessful(spec.statusCode) ? 'success' : 'failure'
|
||||
}
|
||||
|
||||
/** 结果徽标展示形态:文本与配色 class。 */
|
||||
export interface ResultBadge {
|
||||
text: string
|
||||
class: 'status-ok' | 'status-fail'
|
||||
class: 'status-ok' | 'status-fail' | 'status-na'
|
||||
}
|
||||
|
||||
/**
|
||||
* 结果列徽标(列表/详情共用):登录失败记录(语义动作 login-failure,HTTP 状态码可能
|
||||
* 为 200/302——失败回显页渲染/表单登录失败重定向)显示「失败」而非裸状态码,避免
|
||||
* 绿色 200/302 误读为登录成功;其余记录保持原状——按 HTTP 状态码展示
|
||||
* (2xx/3xx 绿、其余红),与既有行为一致。
|
||||
* 结果列徽标(列表/详情共用):
|
||||
* - 登录失败显示红色「失败」——表单登录失败是 302、失败回显页是 200,裸状态码是绿的;
|
||||
* - 登录成功显示绿色「成功」——表单登录成功同样是 302,与「失败」对称才读得出成败;
|
||||
* - 认证端点的页面访问(升级前落库的历史 GET 记录)显示灰色「—」,不计成败;
|
||||
* - 其余记录按 HTTP 状态码展示(2xx/3xx 绿、其余红)。
|
||||
*/
|
||||
export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action' | 'statusCode'>): ResultBadge {
|
||||
export function resultBadge(spec: ResultSpec): ResultBadge {
|
||||
if (isLoginFailure(spec)) {
|
||||
return { text: '失败', class: 'status-fail' }
|
||||
}
|
||||
if (isAuthPageVisit(spec)) {
|
||||
return { text: '—', class: 'status-na' }
|
||||
}
|
||||
if (semanticAction(spec) === 'login' && isSuccessful(spec.statusCode)) {
|
||||
return { text: '成功', class: 'status-ok' }
|
||||
}
|
||||
return {
|
||||
text: String(spec.statusCode),
|
||||
class: isSuccessful(spec.statusCode) ? 'status-ok' : 'status-fail',
|
||||
@@ -301,13 +366,13 @@ export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' |
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录失败记录:优先落库语义动作标注(spec.action,POST /login 失败与
|
||||
* 失败回显均落库),历史记录回退由路径现场推导(仅回显页可推导)。
|
||||
* 是否为登录失败记录:以记录的语义动作键为准(POST /login 失败落库标注 login-failure;
|
||||
* 升级前落库的失败回显页带同一标注,或由路径中的 error 参数现场推导)。
|
||||
*/
|
||||
export function isLoginFailure(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action'>): boolean {
|
||||
const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
return action === LOGIN_FAILURE_ACTION
|
||||
export function isLoginFailure(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): boolean {
|
||||
return semanticAction(spec) === LOGIN_FAILURE_ACTION
|
||||
}
|
||||
|
||||
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
||||
|
||||
@@ -39,3 +39,18 @@ describe('AuditLogDetail 字段变更区块', () => {
|
||||
expect(sfc).not.toContain('删除变更')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AuditLogDetail 结果语义', () => {
|
||||
it('结果与列表徽标、结果筛选、CSV 导出共用同一规则(resultOutcome)', () => {
|
||||
// 登录失败靠语义动作标注识别(HTTP 状态码可能是 302/200),不能在组件里按状态码另判一套
|
||||
expect(sfc).toContain('resultOutcome(props.log.spec)')
|
||||
expect(sfc).not.toContain('isSuccessful(')
|
||||
})
|
||||
|
||||
it('结果三态:成功 / 失败 / 页面访问(中性灰,不计成败)', () => {
|
||||
// 升级前落库的登录页访问记录原先显示「成功 · 200」,误读为未知用户登录成功
|
||||
expect(sfc).toContain("'page-visit': '页面访问'")
|
||||
expect(sfc).toContain("'page-visit': 'status-na'")
|
||||
expect(sfc).toContain('.status-na {')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,9 +8,8 @@ import {
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
formatTime,
|
||||
isLoginFailure,
|
||||
isSuccessful,
|
||||
methodBadgeClass,
|
||||
resultOutcome,
|
||||
} from '@/utils/audit'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -24,27 +23,26 @@ const emit = defineEmits<{
|
||||
|
||||
const close = () => emit('update:visible', false)
|
||||
|
||||
// 结果语义:登录失败记录(HTTP 状态码可能为 200/302)显示「登录失败」,
|
||||
// 其余按 HTTP 状态码判定成败
|
||||
const resultText = computed(() => {
|
||||
if (!props.log) {
|
||||
return '-'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return '登录失败'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
||||
})
|
||||
const RESULT_TEXT = {
|
||||
success: '成功',
|
||||
failure: '失败',
|
||||
// 认证端点的页面访问(升级前落库的 GET 记录):不是操作,不计成败
|
||||
'page-visit': '页面访问',
|
||||
} as const
|
||||
|
||||
const resultBadgeClass = computed(() => {
|
||||
if (!props.log) {
|
||||
return 'status-fail'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return 'status-fail'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? 'status-ok' : 'status-fail'
|
||||
})
|
||||
const RESULT_CLASS = {
|
||||
success: 'status-ok',
|
||||
failure: 'status-fail',
|
||||
'page-visit': 'status-na',
|
||||
} as const
|
||||
|
||||
// 结果语义(与列表徽标、结果筛选、CSV 导出同一规则):登录失败靠语义动作标注识别
|
||||
// (HTTP 状态码可能是 302/200),页面访问不计成败,其余按 HTTP 状态码判定
|
||||
const outcome = computed(() => (props.log ? resultOutcome(props.log.spec) : 'failure'))
|
||||
|
||||
const resultText = computed(() => RESULT_TEXT[outcome.value])
|
||||
|
||||
const resultBadgeClass = computed(() => RESULT_CLASS[outcome.value])
|
||||
|
||||
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
||||
const changes = computed(() => props.log?.spec.changes ?? [])
|
||||
@@ -347,6 +345,8 @@ const rawJson = computed(() =>
|
||||
}
|
||||
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
|
||||
.status-fail { color: #d71d1d; background: rgba(215, 29, 29, 0.12); }
|
||||
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰 */
|
||||
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
|
||||
.raw-json {
|
||||
margin-top: 1rem;
|
||||
font-size: 0.75rem;
|
||||
|
||||
@@ -110,4 +110,11 @@ describe('AuditLogList 页面外观', () => {
|
||||
expect(descIdx).toBeGreaterThan(resourceIdx)
|
||||
expect(statusIdx).toBeGreaterThan(descIdx)
|
||||
})
|
||||
|
||||
it('结果徽标有中性灰样式:页面访问(登录页/登出页的 GET)不计成败', () => {
|
||||
// 升级前落库的登录页访问记录原先显示绿色 200,误读为未知用户登录成功;
|
||||
// resultBadge 现判为 page-visit,需有既非成功色也非失败色的样式承接
|
||||
expect(sfc).toContain("resultBadge(log.spec)")
|
||||
expect(styleRule('.status-na')).toMatch(/color:\s*#6b7280/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -387,8 +387,9 @@ onMounted(fetchLogs)
|
||||
</VEntityField>
|
||||
</template>
|
||||
<template #end>
|
||||
<!-- 结果列:登录失败记录(HTTP 200/302 也可能是失败,语义动作已标注)
|
||||
显示红色「失败」,避免绿色 200/302 误读为登录成功;
|
||||
<!-- 结果列:登录失败显示红色「失败」(表单登录失败是 302,裸状态码是绿的),
|
||||
登录成功显示「成功」;升级前落库的登录页访问(GET,HTTP 200)显示
|
||||
灰色「—」——只是打开过登录页,不计成败,不再以绿色 200 误读为登录成功;
|
||||
徽标经 #title 插槽渲染(当前版本组件在无 title 时不渲染 #extra,
|
||||
原先徽标实际不可见) -->
|
||||
<VEntityField width="4rem">
|
||||
@@ -590,6 +591,8 @@ onMounted(fetchLogs)
|
||||
}
|
||||
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
|
||||
.status-fail { color: var(--audit-red); background: rgba(215, 29, 29, 0.12); }
|
||||
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰,既不是成功色也不是失败色 */
|
||||
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
|
||||
.audit-pagination {
|
||||
/* 在白卡内铺满整行:白底与上方列表左右对齐;上下各留 1rem,
|
||||
文字的垂直位置与原分页条一致;上边缘 1px 分隔线同控制台卡片 footer 观感 */
|
||||
|
||||