Compare commits
13
Commits
9865149ab3
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d05d63b8e | ||
|
|
753de51f7b | ||
|
|
44eca75e6e | ||
|
|
81693e4778 | ||
|
|
b6a21dfaa7 | ||
|
|
1987412e07 | ||
|
|
fd3ea71e31 | ||
|
|
99bd109e80 | ||
|
|
f4d1200d46 | ||
|
|
cc2c618fe7 | ||
|
|
34764c7641 | ||
|
|
87ae0c79bb | ||
|
|
9e89ed75ed |
@@ -0,0 +1,27 @@
|
|||||||
|
name: CD
|
||||||
|
|
||||||
|
# Halo 官方可复用插件 CD 工作流:基于 GitHub Release tag 注入版本号构建 JAR 并
|
||||||
|
# 上传到 Release 资产。可复用工作流内部执行:
|
||||||
|
# ./gradlew clean build -x check -Pversion=${tag 去 v 前缀} <build-args>
|
||||||
|
# 因此 Release tag(如 v0.1.0)自动保证 JAR 文件名 / plugin.yaml spec.version /
|
||||||
|
# Manifest Implementation-Version 三处一致。
|
||||||
|
# 注意:CD 构建带 -x check,不能替代发布前必须通过且不可跳过的 CI 与测试。
|
||||||
|
# 首次上架应用市场审核通过前,skip-appstore-release: true —— 只上传
|
||||||
|
# GitHub Release 资产,不自动同步应用市场;审核通过后按官方发布文档
|
||||||
|
# 配置 app-id 与最小权限的个人令牌(HALO_PAT)后再开启同步。
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
cd:
|
||||||
|
uses: halo-sigs/reusable-workflows/.github/workflows/plugin-cd.yaml@v5
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
with:
|
||||||
|
ui-path: "plugin-operation-audit/ui"
|
||||||
|
artifacts-path: "plugin-operation-audit/build/libs"
|
||||||
|
build-args: "-p plugin-operation-audit"
|
||||||
|
skip-node-setup: true
|
||||||
|
skip-appstore-release: true
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
# Halo 官方可复用插件 CI 工作流:./gradlew clean build(含全部后端测试与 UI 检查)。
|
||||||
|
# 本仓库 Gradle 构建根在 plugin-operation-audit/ 子目录:
|
||||||
|
# - 根目录 gradlew/gradlew.bat 是转发脚本;
|
||||||
|
# - build-args 传 -p 指定项目目录。
|
||||||
|
# UI 子项目使用 npm(package-lock.json),没有 pnpm-lock.yaml,
|
||||||
|
# 因此 skip-node-setup: true,由 ubuntu-latest 预装的 Node/npm 配合
|
||||||
|
# node-gradle 插件(download = false)完成前端构建与 vitest 测试。
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ci:
|
||||||
|
uses: halo-sigs/reusable-workflows/.github/workflows/plugin-ci.yaml@v5
|
||||||
|
with:
|
||||||
|
ui-path: "plugin-operation-audit/ui"
|
||||||
|
artifacts-path: "plugin-operation-audit/build/libs"
|
||||||
|
build-args: "-p plugin-operation-audit"
|
||||||
|
skip-node-setup: true
|
||||||
@@ -11,7 +11,8 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||||
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
|
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
|
||||||
| 语义动作标注 | 捕获时标注语义动作键(登录/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
| 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||||
|
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标 `error` 参数区分):失败尝试与失败回显页(`GET /login?error=...`)在列表/详情/CSV 中显示红色「失败」,而非被页面渲染的绿色 HTTP 200 掩盖 |
|
||||||
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
||||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
||||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
|||||||
### 4.1 操作记录(核心)
|
### 4.1 操作记录(核心)
|
||||||
|
|
||||||
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
|
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
|
||||||
> 注:登录端点不在 `/apis/**` 下,捕获规则将其作为唯一必要例外精确匹配 `/login`、`/logout`(技术方案 D1)。
|
> 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获 `/login`、`/logout`(技术方案 D1)。
|
||||||
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
|
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
|
||||||
- 每条记录字段:
|
- 每条记录字段:
|
||||||
|
|
||||||
@@ -79,22 +79,23 @@ Console 左侧菜单新增"操作审计"页:
|
|||||||
|
|
||||||
| 功能 | 说明 | 阶段 |
|
| 功能 | 说明 | 阶段 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
| 语义动作标注 | 区分"发布/编辑/恢复/登录失败"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
||||||
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
|
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
|
||||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
|
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
|
||||||
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||||
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
|
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
|
||||||
|
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否含 `error` 参数区分,见 `LoginOutcome`):失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)标注语义动作 `login-failure`,列表/详情/CSV 显示红色「失败」而非裸状态码,避免绿色 200/302 误读为登录成功;HTTP 状态码仍如实记录 | V2+ 已实现 |
|
||||||
| 操作回滚 | 不在产品范围内 | 不做 |
|
| 操作回滚 | 不在产品范围内 | 不做 |
|
||||||
|
|
||||||
## 7. 已知局限
|
## 7. 已知局限
|
||||||
|
|
||||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2)
|
|
||||||
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准
|
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准
|
||||||
- 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先)
|
- 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先)
|
||||||
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
|
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
|
||||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
||||||
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
||||||
- 登录失败告警仅覆盖 POST /login 的失败结果(非 2xx),不含尝试的用户名(与登录记录同一局限);告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向,失败目标含 `error` 参数):Halo 若调整失败重定向格式或引入新的登录方式,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登录页 GET 与登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||||
|
- 升级前落库的历史记录无法补标注登录失败:表单登录失败(POST /login,302)在列表中仍显示数字状态码,仅失败回显页(GET,路径含 `error` 参数)可现场推导;升级后新记录由捕获时标注(`spec.action = login-failure`),不再有此局限
|
||||||
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
||||||
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
||||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
||||||
@@ -103,7 +104,7 @@ Console 左侧菜单新增"操作审计"页:
|
|||||||
## 8. 技术要点(均已在 v2.26.1 源码级验证)
|
## 8. 技术要点(均已在 v2.26.1 源码级验证)
|
||||||
|
|
||||||
- 运行环境:Halo 2.26.1(Spring Boot 4);插件 JDK 21,Gradle 插件 `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0
|
- 运行环境:Halo 2.26.1(Spring Boot 4);插件 JDK 21,Gradle 插件 `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0
|
||||||
- 捕获通道:`AfterSecurityWebFilter` 扩展点——位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码
|
- 捕获通道:双过滤器分治——`/apis/**` 写操作由 `AfterSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码);认证端点 `/login`、`/logout` 由 `BeforeSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最前,先于表单登录/登出终止过滤器,操作者记"未知用户")。P0 缺陷实证:链尾过滤器永远看不到表单登录/登出请求(命中即 302 终止,不向下游传递),认证端点必须在链首承接
|
||||||
- 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行
|
- 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行
|
||||||
- 存储:自定义 Extension + 索引查询
|
- 存储:自定义 Extension + 索引查询
|
||||||
- 参考项目:[halo-plugin-sso](https://github.com/liuyiwuqing/halo-plugin-sso)(审计闭环范本)、[plugin-comment-widget](https://github.com/halo-dev/plugin-comment-widget)(`AfterSecurityWebFilter` 实战)、[notify-hub](https://github.com/shirainbown/notify-hub)(事件监听与稳定性模式)
|
- 参考项目:[halo-plugin-sso](https://github.com/liuyiwuqing/halo-plugin-sso)(审计闭环范本)、[plugin-comment-widget](https://github.com/halo-dev/plugin-comment-widget)(`AfterSecurityWebFilter` 实战)、[notify-hub](https://github.com/shirainbown/notify-hub)(事件监听与稳定性模式)
|
||||||
|
|||||||
@@ -59,8 +59,8 @@
|
|||||||
|
|
||||||
### 3.4 WebFlux 响应式(第 6 条)
|
### 3.4 WebFlux 响应式(第 6 条)
|
||||||
|
|
||||||
- 全链路响应式:`AfterSecurityWebFilter` 扩展点、`ReactiveExtensionClient`、
|
- 全链路响应式:`AfterSecurityWebFilter`/`BeforeSecurityWebFilter` 扩展点、
|
||||||
出站用 `WebClient`、定时清理用 Reactor 调度(未用 `@Scheduled`)。
|
`ReactiveExtensionClient`、出站用 `WebClient`、定时清理用 Reactor 调度(未用 `@Scheduled`)。
|
||||||
- 未发现 `.block()` / `RestTemplate` / 阻塞 IO;仅有的 `synchronized`
|
- 未发现 `.block()` / `RestTemplate` / 阻塞 IO;仅有的 `synchronized`
|
||||||
(`LoginFailureAlertService` 窗口计数)为内存短临界区,非阻塞客户端。
|
(`LoginFailureAlertService` 窗口计数)为内存短临界区,非阻塞客户端。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# 操作审计插件发布验收清单确认报告
|
||||||
|
|
||||||
|
> 依据 [plugin-release-checklist.md](./plugin-release-checklist.md) 对本插件做发布前逐项确认。
|
||||||
|
>
|
||||||
|
> - 确认日期:2026-11-22(首轮确认 + 同日待办补齐复测)
|
||||||
|
> - 被测制品:**正式版干净构建产物**
|
||||||
|
> `plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
|
||||||
|
> - 源码基线:commit `81693e4`(master,工作区干净)
|
||||||
|
> - 结论速览:**发布就绪**——首轮确认的 2 项 P0、2 项 P1、2 项 P2 待办已全部补齐
|
||||||
|
> 并复测通过(正式版本号构建、CI/CD 工作流、卸载测试、2.26.0 下探、SHA-256
|
||||||
|
> 证据块、manifest 元数据与 ui/ 迁移),见文末[结论与待办](#结论与待办)。
|
||||||
|
> 首轮确认时的历史状态以"首轮确认"标注保留在正文。
|
||||||
|
|
||||||
|
## 一、构建发布制品 — ✅ 通过(1 项前提)
|
||||||
|
|
||||||
|
| 检查项 | 结果 | 证据 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `clean build` 成功并运行所有接入 `check` 的检查 | ✅ | BUILD SUCCESSFUL;后端 26 类 270 测试、UI 9 spec 69 测试全部通过 |
|
||||||
|
| JAR 文件名 = Gradle 项目版本 = `spec.version` | ✅ | 三处均为 `0.1.0-SNAPSHOT`(devtools 自动注入 JAR 内 plugin.yaml) |
|
||||||
|
| `git status --short` 只有预期变化 | ✅ | 干净,`build/` 已忽略 |
|
||||||
|
| 多模块只发布插件 JAR | ✅ | `build/libs` 仅 1 个 JAR;`ui` 子项目只产出前端资源,无多余制品 |
|
||||||
|
|
||||||
|
> 环境注意:本机 `JAVA_HOME` 指向 jre7,Gradle 调用需临时覆盖为 JDK 21
|
||||||
|
> (`JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew ...`),与测试报告记录一致。
|
||||||
|
|
||||||
|
✅ **正式版补构建(P0 完成)**:已以 `clean build -Pversion=0.1.0` 完成干净构建,
|
||||||
|
三处一致复查通过——JAR 文件名 `plugin-operation-audit-0.1.0.jar`、JAR 内
|
||||||
|
`plugin.yaml` 的 `spec.version: 0.1.0`(devtools 注入)、Manifest
|
||||||
|
`Implementation-Version: 0.1.0` 全部一致;制品 SHA-256 见[发布证据块](#五记录发布证据--✅-就绪本轮补齐)。
|
||||||
|
|
||||||
|
## 二、检查 JAR 内容 — ✅ 基本通过(2 项缺口)
|
||||||
|
|
||||||
|
| 检查项 | 结果 | 证据 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `plugin.yaml` 在 JAR 根目录,name/version/requires/许可证正确 | ✅ | `operation-audit`、`>=2.26.0`、`GPL-3.0` 均正确;无插件依赖声明(本插件无依赖,N/A) |
|
||||||
|
| Logo、主页、问题反馈地址 | ❌ 缺失 | `spec.logo`、`spec.homepage`、`spec.repo`、`spec.issues` 均未声明(对照官方 manifest 文档均为有效字段;上架应用市场必需) |
|
||||||
|
| Manifest 的 `Plugin-Main-Class` 和 `Implementation-Version` | ✅ | `run.halo.app.plugin.BasePlugin` 正确——已对照 Halo 2.26.1 源码:`YamlPluginDescriptorFinder` 对所有插件硬编码使用 `BasePlugin`,devtools 写入值与运行时一致;`Implementation-Version: 0.1.0-SNAPSHOT` 一致 |
|
||||||
|
| 后端类、extensions、运行时资源完整 | ✅ | 40+ 类、`extensions/role-template.yaml`、`extensions/settings.yaml`、`META-INF/plugin-components.idx` 齐全 |
|
||||||
|
| UI 打包完整、清单声明的资源均存在 | ✅ | `ui-plugin.json`(ESM)声明的入口与样式均在 JAR 内;**已从 `console/` 迁移到官方规范的 `ui/` 目录(P2 完成,commit `81693e4`)**——`processUiResources` 输出到 `resources/main/ui` 并清理旧构建残留的 `console/`;正式版 JAR 复核 `ui/ui-plugin.json` + 入口/样式齐备 |
|
||||||
|
| 已运行 `generateApiClient`,无手写重复 | ✅ | `ui/src/api/generated/` 产物入库;封装层(`ui/src/api/index.ts`)复用宿主 `axiosInstance`;全量检索确认无手写同资源类型/路径 |
|
||||||
|
| JAR 不含凭据、`.env`、测试数据等敏感文件 | ✅ | 条目清单干净:仅类、extensions、console 资源、plugin.yaml、MANIFEST |
|
||||||
|
|
||||||
|
### Plugin-Main-Class 专项考证
|
||||||
|
|
||||||
|
本插件 JAR 的 Manifest 值为基类 `run.halo.app.plugin.BasePlugin` 而非具体类
|
||||||
|
`run.halo.operationaudit.OperationAuditPlugin`。经查证属**预期行为**:
|
||||||
|
|
||||||
|
- Halo 2.26.1 的 `YamlPluginDescriptorFinder#convert` 将插件类硬编码为
|
||||||
|
`run.halo.app.plugin.BasePlugin`,不读取 Manifest 的 `Plugin-Main-Class`;
|
||||||
|
- devtools 0.8.0 的 `PluginJarManifestCustomizer` 默认即写入该值(内部含
|
||||||
|
`ResolvePluginMainClassName` 解析任务与 `DEFAULT_MAIN_CLASS` 兜底)。
|
||||||
|
|
||||||
|
写入值与运行时行为一致,清单该项判定通过。
|
||||||
|
|
||||||
|
## 三、验证安装和升级 — ✅ 大部分通过(引用三轮真实 Halo 联调)
|
||||||
|
|
||||||
|
[测试报告](./operation-audit-test-report.md)已覆盖:
|
||||||
|
|
||||||
|
- 默认 `deployment` 模式上传安装、启用 ✅;
|
||||||
|
- 插件信息、默认配置、权限、Console 入口及主要功能(浏览器级逐项人工检查)✅;
|
||||||
|
- 重启 Halo 后插件启动、配置与持久化数据 ✅;
|
||||||
|
- 禁用→重新启用,运行时资源释放恢复 ✅;
|
||||||
|
- 同实例换 JAR 升级 ✅(Windows 文件锁注意事项已记录);
|
||||||
|
- 权限矩阵(admin + 仅授予 `role-template-audit-view` 的只读用户,含匿名拒绝路径)✅;
|
||||||
|
- 无依赖插件,"依赖缺失/停用/版本不满足"状态 N/A ✅;
|
||||||
|
- FormKit 设置表单、凭据入 Secret、出站环回地址 SSRF 拦截实测 ✅。
|
||||||
|
|
||||||
|
**未覆盖项**(清单明确要求、测试报告已自认):
|
||||||
|
|
||||||
|
- ✅ **卸载(uninstall)测试**已于第四轮补测通过(见下);
|
||||||
|
- ✅ **`requires` 最低版本 2.26.0 下探实测**已完成(见下);
|
||||||
|
- ⚠️ Webhook 公网投递链路未验证(避免向外部服务发送数据,合理限制,保留)。
|
||||||
|
|
||||||
|
**第四轮补测(2026-11-22,commit `81693e4`,详见测试报告)**:
|
||||||
|
|
||||||
|
- **卸载生命周期** ✅:对齐 Console「卸载并删除配置」路径实测——CR/JAR/Setting/
|
||||||
|
ConfigMap/RoleTemplate 全部清理,审计数据保留(重装后 169→172 条回归),
|
||||||
|
pf4j `disabled.txt` 停用残留被 Halo 重装启动时自动清除;唯一残留为宿主侧
|
||||||
|
RoleBinding 孤儿绑定(Halo 平台行为,RoleTemplate 已删、无授权效果,已记录);
|
||||||
|
- **2.26.0 最低版本下探** ✅:官方 2.26.0 实例全新安装 0.1.0,安装/启用/审计捕获/
|
||||||
|
查询导出/权限拒绝路径全部正常(详见测试报告第四轮 2.26.0 下探记录)。
|
||||||
|
|
||||||
|
## 四、核对 CI/CD — ✅ 已配置(本轮补齐)
|
||||||
|
|
||||||
|
[.github/workflows/ci.yml](../.github/workflows/ci.yml) / [cd.yml](../.github/workflows/cd.yml)
|
||||||
|
复用官方 `halo-sigs/reusable-workflows`(`plugin-ci.yaml@v5` / `plugin-cd.yaml@v5`):
|
||||||
|
|
||||||
|
- CI:push/PR 触发 `./gradlew clean build`(全部后端测试 + UI 检查,不可跳过);
|
||||||
|
- CD:Release published 触发,工作流自动执行
|
||||||
|
`./gradlew clean build -x check -Pversion=${tag 去 v 前缀}`,
|
||||||
|
由构建保证 Release tag(如 `v0.1.0`)↔ JAR 文件名 ↔ `spec.version` 一致
|
||||||
|
(`-Pversion=0.1.0` 三处一致已实测验证,见章节一);
|
||||||
|
- `artifacts-path: plugin-operation-audit/build/libs` 仅匹配插件 JAR(仓库唯一制品目录);
|
||||||
|
- `skip-appstore-release: true`:首次上架审核通过前只上传 Release 资产,不自动同步应用市场;
|
||||||
|
- 仓库 Gradle 根在 `plugin-operation-audit/` 子目录,官方工作流从仓库根执行 `./gradlew`——
|
||||||
|
根目录 `gradlew`/`gradlew.bat` 为转发脚本,`build-args: "-p plugin-operation-audit"` 指定项目目录;
|
||||||
|
UI 子项目使用 npm(无 pnpm-lock.yaml),故 `skip-node-setup: true`,由 runner 预装
|
||||||
|
Node/npm 配合 node-gradle 插件完成前端构建。
|
||||||
|
|
||||||
|
## 五、记录发布证据 — ✅ 就绪(本轮补齐)
|
||||||
|
|
||||||
|
发布证据块(正式版制品,构建于 commit `81693e4`,工作流/文档提交不影响制品内容):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Commit and tag: 81693e4(tag v0.1.0,见下方说明)
|
||||||
|
Plugin version: 0.1.0
|
||||||
|
Halo versions tested: 2.26.1(烟测实例,H2);2.26.0(最低版本下探,见章节三补充)
|
||||||
|
Clean install: pass(install API → enable → STARTED,见第四轮测试记录)
|
||||||
|
Upgrade from: 0.1.0-SNAPSHOT → 0.1.0,pass(upgrade API,169 条历史数据保留)
|
||||||
|
Commands run: ./gradlew clean build -Pversion=0.1.0(JDK 21);
|
||||||
|
联调:upgrade/install/uninstall/enable API、登录/登出审计、
|
||||||
|
query/export、匿名与只读角色路径(详见测试报告第四轮)
|
||||||
|
Roles and dependency states: admin 与 auditor3(仅 role-template-audit-view)实测;
|
||||||
|
无插件依赖,N/A
|
||||||
|
Known limitations: Windows 升级 JAR 文件锁环境限制(本轮 upgrade API 实测正常);
|
||||||
|
Webhook 公网投递未验证(避免向外部服务发送数据)
|
||||||
|
Artifact path and SHA-256:
|
||||||
|
plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar
|
||||||
|
SHA-256: 3d2a2ad4ea8ea53af169806be95fe348d2da2fa263f8d681fee38abea47db563
|
||||||
|
```
|
||||||
|
|
||||||
|
**Release tag 说明**:发布流程为——推送 master 后在代码托管平台创建 tag `v0.1.0`
|
||||||
|
并发布 Release;CD 工作流将以 tag 版本号(`v0.1.0` → `-Pversion=0.1.0`)构建并
|
||||||
|
把 JAR 作为 Release 资产上传。本地已按此版本号完成干净构建与验收(章节一、三),
|
||||||
|
**发布前仍需在 CI 上通过一次完整构建**(CD 带 `-x check`,不能替代 CI 与测试)。
|
||||||
|
|
||||||
|
## 结论与待办
|
||||||
|
|
||||||
|
**发布就绪**:原 6 项待办(2×P0、2×P1、2×P2)已全部完成——
|
||||||
|
|
||||||
|
| 优先级 | 待办 | 状态 | 对应章节 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| P0 | 以正式版本号(非 SNAPSHOT)重新干净构建,并复查版本三处一致 | ✅ `clean build -Pversion=0.1.0` 全绿,JAR 名 / `spec.version` / Manifest 一致(0.1.0) | 一 |
|
||||||
|
| P0 | 补 CI/CD 工作流(可复用 CI 跑 `clean build` + 基于 Release tag 的 CD) | ✅ `plugin-ci/cd.yaml@v5` 已配置(44eca75),artifacts-path 限定制品目录、首上架不自动同步应用市场 | 四 |
|
||||||
|
| P1 | 补卸载(uninstall)测试与 2.26.0 最低版本下探实测 | ✅ 卸载生命周期实测通过(753de51);2.26.0 下探见章节三补充 | 三 |
|
||||||
|
| P1 | 生成发布版制品的 SHA-256 并补全发布证据块(含 Release tag) | ✅ 0.1.0 制品 SHA-256 已记录于发布证据块 | 五 |
|
||||||
|
| P2 | 补 `plugin.yaml` 的 `spec.logo` / `spec.homepage` / `spec.repo` / `spec.issues` | ✅ logo.svg 内置 + homepage/repo/issues/author.website/license.url 已补(81693e4) | 二 |
|
||||||
|
| P2 | UI 输出目录从 `console/` 迁移到 `ui/`(官方当前规范位置) | ✅ `processUiResources` 迁至 `ui/`,JAR 内 `ui/ui-plugin.json` 入口/样式齐备(81693e4) | 二 |
|
||||||
|
|
||||||
|
**剩余发布动作**(非验收缺口,属发布操作):
|
||||||
|
推送 master → 创建 tag `v0.1.0` 并发布 GitHub Release → CI 绿 → CD 产出 Release
|
||||||
|
资产 → (审核通过后)配置应用市场同步。
|
||||||
|
|
||||||
|
## 参考链接
|
||||||
|
|
||||||
|
- [插件发布验收清单(本地存档)](./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)
|
||||||
|
- [Halo v2.26.1 YamlPluginDescriptorFinder 源码](https://github.com/halo-dev/halo/blob/v2.26.1/application/src/main/java/run/halo/app/plugin/YamlPluginDescriptorFinder.java)
|
||||||
|
- [操作审计插件测试报告](./operation-audit-test-report.md)
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
| # | 决策 | 结论 | 理由 |
|
| # | 决策 | 结论 | 理由 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| D1 | 捕获通道 | 单一 `AfterSecurityWebFilter`,路径规则为 `/apis/**` 写操作 + `/login` + `/logout` | 登录端点不在 `/apis/**` 下,扩路径匹配而非引入第二套机制 |
|
| D1 | 捕获通道 | 双过滤器分治:`/apis/**` 写操作走 `AfterSecurityWebFilter`;认证端点 `/login`、`/logout` 走 `BeforeSecurityWebFilter`(Security 链之前) | 表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),链尾过滤器永远看不到认证端点请求,必须在链首承接 |
|
||||||
| D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 |
|
| D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 |
|
||||||
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
|
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
| 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 |
|
| 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 |
|
||||||
| 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 |
|
| 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 |
|
||||||
| 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 |
|
| 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 |
|
||||||
| 捕获通道 | `AfterSecurityWebFilter` 扩展点(实现 `WebFilter`,注册在 Security 链之后) | 产品文档第 8 节已源码级验证 |
|
| 捕获通道 | `AfterSecurityWebFilter` + `BeforeSecurityWebFilter` 扩展点(实现 `WebFilter`,分别注册在 Security 链最后与最前) | 产品文档第 8 节已源码级验证;P0 缺陷实证双通道必要性 |
|
||||||
| 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 |
|
| 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 |
|
||||||
| Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 |
|
| Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 |
|
||||||
| 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 |
|
| 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 |
|
||||||
@@ -51,12 +51,14 @@ plugin-operation-audit/
|
|||||||
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
|
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
|
||||||
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
|
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
|
||||||
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
||||||
|
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标 error 参数(纯函数)
|
||||||
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
||||||
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
||||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||||
│ │ │ ├── OperationAuditWebFilter.java
|
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证端点捕获(BeforeSecurityWebFilter,链首)
|
||||||
|
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
|
||||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||||
│ │ └── housekeeping/
|
│ │ └── housekeeping/
|
||||||
│ │ └── RetentionCleaner.java # 定时清理
|
│ │ └── RetentionCleaner.java # 定时清理
|
||||||
@@ -77,14 +79,17 @@ plugin-operation-audit/
|
|||||||
|
|
||||||
## 4. 核心设计决策
|
## 4. 核心设计决策
|
||||||
|
|
||||||
### D1 捕获通道与路径规则
|
### D1 捕获通道与路径规则(P0 修订)
|
||||||
|
|
||||||
- 实现一个 `WebFilter`,以 `AfterSecurityWebFilter` 扩展点方式注册(位于 Security 过滤链最后、认证之后,`doFinally` 可读最终响应状态码)。
|
- 双过滤器分治(P0 缺陷实证后修订):
|
||||||
|
- **`/apis/**` 写操作**:`AfterSecurityWebFilter` 扩展点(位于 Security 过滤链最后、认证之后,可获取当前登录用户,`doFinally` 可读最终响应状态码)。
|
||||||
|
- **认证端点 `/login`、`/logout`**:`BeforeSecurityWebFilter` 扩展点(位于 Security 过滤链最前,`SecurityWebFiltersOrder.FIRST`)。P0 根因:表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求——POST /login、/logout 曾永不产生审计记录,登录失败告警生产路径随之失效。
|
||||||
- 捕获规则(`CaptureRule`,纯函数):
|
- 捕获规则(`CaptureRule`,纯函数):
|
||||||
- `POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`
|
- `shouldCapture`:`POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`(链尾过滤器消费)
|
||||||
- 或路径精确匹配 `/login`、`/logout`
|
- `isAuthEndpoint`:路径精确匹配 `/login`、`/logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录
|
||||||
- 匿名判断**不在请求期做,而在记录时做**:登录请求开始时用户必然匿名,只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致。
|
- 操作者归属:`/apis/**` 请求从认证上下文解析;认证端点在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
|
||||||
- 该规则是产品设计"一条通用规则覆盖全部管理面操作"的唯一必要例外(登录端点不在 `/apis/**` 下),需在产品文档中同步注明。
|
- 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证端点记录不判匿名。
|
||||||
|
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录且链尾过滤器不重复记录。
|
||||||
|
|
||||||
### D2 审计写入:响应式直写
|
### D2 审计写入:响应式直写
|
||||||
|
|
||||||
@@ -211,6 +216,7 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
- `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。
|
- `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 即成功」把表单成功登录误计为失败的问题。
|
||||||
- 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。
|
- 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。
|
||||||
|
|
||||||
### 5.2 资源解析规则(通用,不追求语义完美)
|
### 5.2 资源解析规则(通用,不追求语义完美)
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
# 操作审计插件测试报告
|
||||||
|
|
||||||
|
> 依据 [plugin-testing.md](./plugin-testing.md) 的分层验证流程执行,覆盖源码级自动化检查、
|
||||||
|
> 真实 Halo 安装联调与浏览器级 UI 验证。
|
||||||
|
>
|
||||||
|
> - 测试日期:2026-11-22
|
||||||
|
> - 被测插件:`plugin-operation-audit` 0.1.0-SNAPSHOT(commit `34764c7`,master)
|
||||||
|
> - 结论速览:**自动化检查全部通过;JAR 安装联调发现 1 个 P0 功能缺陷**
|
||||||
|
> (POST /login、/logout 永不达审计过滤器),详见[缺陷记录](#p0-缺陷post-loginlogout-永不产生审计记录登录失败告警生产路径失效)。
|
||||||
|
>
|
||||||
|
> **修复状态(2026-11-22 更新)**:P0 已按本报告修复方向修复(commit `f4d1200`)——
|
||||||
|
> 认证端点改由 `BeforeSecurityWebFilter` 在 Security 链最前捕获(新增
|
||||||
|
> `AuthEndpointAuditWebFilter`),并按修复方向补充真实过滤链集成测试。真实 Halo 2.26.1
|
||||||
|
> 复测:浏览器表单登录(错误密码 302→error、正确密码 302→/uc)与登出均产生审计记录、
|
||||||
|
> Console 登录失败红色标注正常;回归期间额外发现并修复了首版修复的
|
||||||
|
> "缓存请求体导致 CSRF 表单参数通道失效(登录页 403)"缺陷(commit `f4d1200` 内),
|
||||||
|
> 已以"启用 CSRF + 表单参数令牌"的集成测试锁死。
|
||||||
|
|
||||||
|
> **复测状态(2026-11-22 第二轮,commit `99bd109`)**:全量自动化检查与真实 Halo
|
||||||
|
> 联调冒烟再次全部通过,详见[复测记录](#复测记录2026-11-22-第二轮commit-99bd109)。
|
||||||
|
|
||||||
|
> **复测状态(2026-11-22 第三轮,commit `fd3ea71`)**:全量自动化检查与真实 Halo
|
||||||
|
> 联调(含多角色权限矩阵与生命周期往返)再次全部通过,详见
|
||||||
|
> [复测记录](#复测记录2026-11-22-第三轮commit-fd3ea71)。
|
||||||
|
|
||||||
|
## 可复核结果
|
||||||
|
|
||||||
|
```text
|
||||||
|
Commit: 34764c7 (master, 测试期间诊断代码已全部回滚,工作区干净)
|
||||||
|
Halo versions tested: 2.26.1(官方独立 JAR;plugin.yaml 声明 requires >=2.26.0)
|
||||||
|
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain 自动选定;本机 JAVA_HOME
|
||||||
|
指向 jre7,每次 Gradle 调用需临时覆盖 JAVA_HOME)、
|
||||||
|
Node v24.19.0、pnpm 11.22.0(项目 UI 实际使用 npm)
|
||||||
|
Commands run: ./gradlew test --rerun、./gradlew :ui:testFrontend :ui:buildFrontend、
|
||||||
|
./gradlew check、./gradlew clean build;
|
||||||
|
Halo 安装/启用/停用/升级/重启等 API 调用(见下方联调章节)
|
||||||
|
Automated checks: PASS(后端 265/265,UI 69/69,类型检查与构建通过)
|
||||||
|
Roles and dependency states: admin(超级管理员全量权限)与 auditor3(仅授予
|
||||||
|
role-template-audit-view)两个角色实测
|
||||||
|
Manual paths checked: 安装→启用→审计捕获→查询/导出→停用→升级→重启恢复→
|
||||||
|
权限矩阵→Console 桌面与 390px 窄屏人工检查
|
||||||
|
Known limitations: 见文末"未覆盖项"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 一、自动化检查(全部通过)
|
||||||
|
|
||||||
|
| 检查项 | 命令 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 后端 JUnit 5 | `./gradlew test --rerun`(强制重跑,避免缓存假绿) | **24 个测试类 / 265 个测试全部通过**,0 skipped / 0 failures / 0 errors |
|
||||||
|
| UI 单元测试 | `./gradlew :ui:testFrontend`(vitest) | **9 个 spec / 69 个测试全部通过** |
|
||||||
|
| UI 类型检查与构建 | `./gradlew :ui:buildFrontend`(vue-tsc + vite) | 通过;bundler kit 输出 ESM,共享依赖对齐 Halo 2.26.0 |
|
||||||
|
| 完整检查生命周期 | `./gradlew check` | 通过(UI build/test 已接入 check) |
|
||||||
|
| 发布前干净构建 | `./gradlew clean build` | 通过;产物 `build/libs/plugin-operation-audit-0.1.0-SNAPSHOT.jar` |
|
||||||
|
|
||||||
|
### JAR 打包内容核验
|
||||||
|
|
||||||
|
`unzip -l` 核对产物:
|
||||||
|
|
||||||
|
- `plugin.yaml`、`extensions/role-template.yaml`、`extensions/settings.yaml` 齐全;
|
||||||
|
- `console/main.Bwbl9zw-.js`、`console/assets/index.UH34KxXN.css` 的 hash 与本次
|
||||||
|
vite 构建输出一致,确认 `processUiResources` 的"先清空再拷贝"策略有效,无历史版本残留;
|
||||||
|
- `console/ui-plugin.json` 与 `META-INF/plugin-components.idx` 就位。
|
||||||
|
|
||||||
|
### 生成 API 客户端差异审查
|
||||||
|
|
||||||
|
- 生成产物 20 个文件全部入库(`ui/src/api/generated/`),`git status` 干净,无手改痕迹;
|
||||||
|
- 生成客户端 3 个端点与后端 `SpringdocRouteBuilder` 声明逐一比对:
|
||||||
|
`GET auditlogs/-/query`、`GET auditlogs/-/export`、`POST alerts/-/test`;
|
||||||
|
- 与 `build.gradle` groupingRules 的 `pathsToMatch` 一致;UI 封装层
|
||||||
|
(`ui/src/api/index.ts`)复用宿主 `axiosInstance`,未自建 Axios 客户端。
|
||||||
|
|
||||||
|
## 二、真实 Halo 安装联调
|
||||||
|
|
||||||
|
**环境**:Docker 不可用,DevTools `haloServer` 无法运行。改用 Halo 2.26.1 官方独立 JAR
|
||||||
|
(`java -jar halo-2.26.1.jar --halo.work-dir=<一次性目录> --server.port=8099`,H2 内置库),
|
||||||
|
等效覆盖"最终 JAR 安装验证"层级。数据目录为一次性测试目录,未使用任何生产数据。
|
||||||
|
|
||||||
|
| 生命周期节点 | 操作方式 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 安装 | `POST /apis/api.console.halo.run/v1alpha1/plugins/install`(multipart) | 200,JAR 落至 workdir/plugins |
|
||||||
|
| 启用 | `PUT plugins/operation-audit` 更新 `spec.enabled` | STARTED;插件自身启用的写操作即被审计捕获 |
|
||||||
|
| 审计捕获(HTTP 通道) | admin 的 `PUT/POST /apis/**` 写操作 | 正常记录(含 404 失败路径、语义动作、状态码、IP、UA) |
|
||||||
|
| 审计捕获(内部变更通道) | 系统角色模板 reconcile、通知订阅清理等 | 记录为 `system` 执行者,归属正确 |
|
||||||
|
| 查询/导出 | `GET auditlogs/-/query`、`/-/export` | 200,数据与筛选正常 |
|
||||||
|
| 停用/启用 | `PUT spec.enabled=false/true` | 正常;停用期间查询端点随插件下线 |
|
||||||
|
| 重启恢复 | 杀进程后重启 Halo | 插件自动恢复 STARTED(`spec.enabled=true` 持久化生效),**历史审计数据完整保留** |
|
||||||
|
| 升级 | 换 JAR 后重启(详见 Windows 限制) | 新 JAR 生效 |
|
||||||
|
|
||||||
|
### 权限矩阵(不同角色实测)
|
||||||
|
|
||||||
|
预置 `auditor3` 用户,仅授予 `role-template-audit-view`(verbs 仅 get/list):
|
||||||
|
|
||||||
|
| 请求 | 期望 | 实测 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| auditor3 `GET auditlogs/-/query` | 200 | **200** ✅ |
|
||||||
|
| auditor3 `GET auditlogs/-/export` | 200 | **200** ✅ |
|
||||||
|
| auditor3 `DELETE /apis/audit.guichumo.com/v1alpha1/auditlogs/{name}` | 403 | **403** ✅(只读角色技术上无法删除审计记录) |
|
||||||
|
| auditor3 `POST alerts/-/test` | 403 | **403** ✅ |
|
||||||
|
| auditor3 `GET /apis/api.console.halo.run/v1alpha1/users`(越权探测) | 403 | **403** ✅ |
|
||||||
|
| 匿名 `GET auditlogs/-/query` | 拒绝 | **302 → /login** ✅ |
|
||||||
|
|
||||||
|
### 浏览器级 UI 验证(桌面 + 窄屏人工检查)
|
||||||
|
|
||||||
|
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `gui-test-screenshots/`:
|
||||||
|
|
||||||
|
- 菜单入口:`plugin` 分组下出现「操作审计」,选中态高亮正确(t1);
|
||||||
|
- 列表页(1280px):筛选区(操作者/资源类型/动作/语义动作/结果/关键字/起止时间)、
|
||||||
|
动作徽标(DELETE 红 / POST 蓝 / PUT 橙 / GET 灰)、结果徽标(200)、历史链接、
|
||||||
|
IP 列均正常渲染;真实审计数据即时可见(t1);
|
||||||
|
- 窄屏(390px):筛选栏单列堆叠(≤480px 断点,符合 34764c7 修订后的设计)、
|
||||||
|
表格进入横向滚动容器且题头与数据列对齐同步(t3、t4);
|
||||||
|
- 插件设置页:审计设置/告警通知两组表单正常回显当前 ConfigMap 值;
|
||||||
|
自定义 FormKit 输入「发送测试告警」按钮注册成功并渲染(t5);Secret 选择器
|
||||||
|
正确展示已创建的 Secret 及 `包含字段: webhookUrl`;
|
||||||
|
- 全程无可见页面错误(本浏览器运行时不支持只读 console 采集,以页面可见表现为准)。
|
||||||
|
|
||||||
|
### SSRF 防护实测(出站地址校验)
|
||||||
|
|
||||||
|
- 配置回环地址 Webhook(`http://127.0.0.1:8199/hook`)后调用测试告警端点:
|
||||||
|
正确拒绝,返回 `success:false` 与明确中文原因"Webhook 主机解析到受限网络地址
|
||||||
|
(环回/内网/链路本地/云元数据等),已拒绝"——`OutboundUrlGuard` 端到端生效;
|
||||||
|
- 完整投递链路(真实送达接收端)需公网 Webhook,为避免向外部服务发送数据而**未执行**。
|
||||||
|
|
||||||
|
## P0 缺陷:POST /login、/logout 永不产生审计记录,登录失败告警生产路径失效
|
||||||
|
|
||||||
|
### 现象(稳定复现,跨全新数据库、跨重启)
|
||||||
|
|
||||||
|
| 请求 | 记录情况 |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /login`(登录页访问) | ✅ 有记录(anonymousUser, action=login) |
|
||||||
|
| **`POST /login` 成功(302 → /uc)** | ❌ **无记录** |
|
||||||
|
| **`POST /login` 失败(302 → /login?error=invalid-credential)** | ❌ **无记录** |
|
||||||
|
| **`POST /logout`(302 → /login?logout)** | ❌ **无记录** |
|
||||||
|
| `PUT/POST /apis/**`(含 404 失败路径) | ✅ 正常记录 |
|
||||||
|
| 内部变更通道(reconcile 等) | ✅ 正常记录(system) |
|
||||||
|
|
||||||
|
同期验证排除项:登录主流程未被破坏(插件启用后正确密码仍可登录);无任何 WARN/DEBUG
|
||||||
|
日志(静默失败);告警设置启用且 Secret 已配置时,阈值窗口仍未触发任何告警路径日志。
|
||||||
|
|
||||||
|
### 根因(诊断日志实证)
|
||||||
|
|
||||||
|
`OperationAuditWebFilter` 经 `AfterSecurityWebFilter` 扩展点注册,位于 Security 过滤链
|
||||||
|
**内部**、认证环节之后。临时加入 `filter enter` / `doFinally` / `operator` 三处诊断日志并
|
||||||
|
实测(Halo 2.26.1):
|
||||||
|
|
||||||
|
- `GET /login`:`filter enter` → `doFinally` → `operator resolved` 完整链路,记录成功;
|
||||||
|
- **`POST /login`:过滤器 `filter()` 从未被调用(无 `filter enter` 日志)**——表单登录/
|
||||||
|
登出过滤器命中请求后直接完成 302 响应,不再向下游传递,审计过滤器永远看不到该请求;
|
||||||
|
- `POST /logout` 同理。
|
||||||
|
|
||||||
|
因此 doFinally 中的审计记录与**登录失败告警回调**(同一入口,`LoginFailureAlertService`
|
||||||
|
回调)在生产路径上均为死代码。265 个单元测试全绿,是因为组件隔离测试未覆盖过滤器与
|
||||||
|
安全链的集成(`LoginOutcome`、告警窗口逻辑等单测均直接驱动组件,不经过真实过滤链)。
|
||||||
|
|
||||||
|
### 修复方向(建议)
|
||||||
|
|
||||||
|
为 `/login`、`/logout` 注册一个独立的普通 `WebFilter`(位于 Security 过滤链之前)承接
|
||||||
|
认证端点的捕获与记录(操作者解析对匿名/未知场景本就有兜底路径);`/apis/**` 捕获保留
|
||||||
|
现有 `AfterSecurityWebFilter` 注册以继续获得认证用户上下文。同时补充一条真实过滤链
|
||||||
|
集成测试(至少断言 POST /login 会产生记录),防止回归。
|
||||||
|
|
||||||
|
### 复现命令(脱离本报告可独立复跑)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 启动干净实例(一次性数据目录)
|
||||||
|
java -jar halo-2.26.1.jar --halo.work-dir=<tmp> --server.port=8099
|
||||||
|
# 2. 初始化系统并安装启用插件(POST /system/setup、POST .../plugins/install、PUT spec.enabled=true)
|
||||||
|
# 3. 任一次 POST /login(成功或失败均可)
|
||||||
|
# 4. 对比:GET /apis/audit.guichumo.com/v1alpha1/auditlogs 中只有 GET /login 记录,无 POST 记录
|
||||||
|
```
|
||||||
|
|
||||||
|
## 其他发现(低优先级)
|
||||||
|
|
||||||
|
1. **Windows 上插件 JAR 被运行实例锁定**:`upgrade` API 报 500
|
||||||
|
(`FileSystemException: 另一个程序正在使用此文件`),停用插件后句柄仍不释放,只能停服
|
||||||
|
换 JAR。属 Halo on Windows 的环境限制,建议在 README 记录 Windows 升级注意事项。
|
||||||
|
2. `testAlert` 端点对非法地址的失败反馈体验良好(结构化 `success:false` + 原因),可保持。
|
||||||
|
3. 本机环境注意:`JAVA_HOME` 指向 `jre7`,Gradle 调用需临时覆盖为 JDK 21
|
||||||
|
(`JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew ...`)。
|
||||||
|
|
||||||
|
## 未覆盖项
|
||||||
|
|
||||||
|
- Webhook 公网投递链路(需外部接收端,未向外部服务发送数据);
|
||||||
|
- 卸载(uninstall)测试;
|
||||||
|
- `spec.requires` 最低版本 2.26.0 的实测(仅测 2.26.1,未按官方建议"不得仅凭编译成功
|
||||||
|
推断兼容范围"下探到最低版本);
|
||||||
|
- 其他浏览器/设备兼容性(仅 Chromium 内核桌面与 390px 视口);
|
||||||
|
- DevTools `haloServer` / `watch` 开发工作流(Docker 不可用)。
|
||||||
|
|
||||||
|
## 复测记录(2026-11-22 第二轮,commit `99bd109`)
|
||||||
|
|
||||||
|
P0 修复(`f4d1200`)合入后的全量复测。自动化检查逐层执行,真实 Halo 联调在既有
|
||||||
|
一次性冒烟实例(8099)上完成。
|
||||||
|
|
||||||
|
```text
|
||||||
|
Commit: 99bd109 (master,工作区干净,仅文档)
|
||||||
|
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 冒烟实例,H2 内置库)
|
||||||
|
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
|
||||||
|
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、
|
||||||
|
npm 11.22.0(UI 子项目实际使用 npm,无 pnpmCheck 任务,
|
||||||
|
等效检查为 :ui:testFrontend + :ui:buildFrontend,已接入 check)
|
||||||
|
Commands run: ./gradlew test --rerun、./gradlew :ui:check --rerun、
|
||||||
|
./gradlew check、./gradlew clean build、
|
||||||
|
./gradlew haloServer(失败,见 Known limitations);
|
||||||
|
联调冒烟:真实登录/登出/查询/导出/告警测试端点调用
|
||||||
|
Automated checks: PASS(后端 270/270,0 失败 0 跳过;UI vitest 69/69;
|
||||||
|
vue-tsc 类型检查与 vite 构建通过;check 与 clean build 通过)
|
||||||
|
Roles and dependency states: 本轮仅 admin;无权限路径以匿名会话验证(查询端点 302 拒绝)。
|
||||||
|
多角色矩阵由上一轮(34764c7/f4d1200 报告)覆盖
|
||||||
|
Manual paths checked: 插件自重启恢复(实例 18:45 重启后插件自动 STARTED);
|
||||||
|
失败登录→login-failure 记录(attemptedUsername=admin,302);
|
||||||
|
成功登录→login 记录;登出→logout 记录(302→/login?logout);
|
||||||
|
登出后查询会话权限即时回收;无效分页参数(page=-1&size=0)
|
||||||
|
归一化不 500;导出 CSV 表头与数据完整;告警测试端点对
|
||||||
|
环回地址返回结构化失败(OutboundUrlGuard 拦截);
|
||||||
|
服务端日志 0 ERROR
|
||||||
|
Known limitations: DevTools haloServer/pullHaloImage 因本机无 Docker 失败
|
||||||
|
(java.nio.file.NoSuchFileException: \\.\pipe\docker_engine),
|
||||||
|
联调以独立 JAR 实例替代完成;Windows 上升级 API 因 JAR
|
||||||
|
文件锁仍需停服换 JAR(上轮已记录的环境限制)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 联调冒烟结果明细(对照 plugin-testing.md 检查清单)
|
||||||
|
|
||||||
|
| 检查项 | 实测 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 插件能够启动、日志无未处理错误 | 重启后自动 STARTED;`halo-restart2.log` 0 条 ERROR | 通过 |
|
||||||
|
| 登录/登出审计(P0 修复路径) | 失败登录记 `login-failure`(attemptedUsername=admin)、成功登录记 `login`、登出记 `logout`(302) | 通过 |
|
||||||
|
| 操作者归属语义 | 认证端点记录统一 `username=unknown` + `attemptedUsername`(链首无认证上下文,`AuthEndpointAuditWebFilter` Javadoc 声明的设计行为,非缺陷) | 符合设计 |
|
||||||
|
| API 成功路径 | query(115→121 条,分页/排序正常)、export(200,29KB CSV) | 通过 |
|
||||||
|
| 无权限路径 | 匿名访问 query 端点被 302 重定向拒绝,登出后原会话权限即时失效 | 通过 |
|
||||||
|
| 无效输入 | `page=-1&size=0` 被归一化处理(无 500) | 通过 |
|
||||||
|
| 依赖失败路径 | `POST alerts/-/test`:webhook 指向环回地址被 OutboundUrlGuard 拒绝,返回结构化 `success:false` + 原因 | 通过 |
|
||||||
|
| 配置/重启生效 | 实例 18:45 重启后插件自动恢复 STARTED,历史审计数据保留(累计 121 条) | 通过 |
|
||||||
|
|
||||||
|
> 本轮新增核对项:GET /login 页面访问也产生 `login`(HTTP 200)记录——属
|
||||||
|
> `isAuthEndpoint` 设计内覆盖(失败回显 `?error=...` 会被标注登录失败),非噪声缺陷。
|
||||||
|
|
||||||
|
## 复测记录(2026-11-22 第三轮,commit `fd3ea71`)
|
||||||
|
|
||||||
|
按 [plugin-testing.md](./plugin-testing.md) 分层流程的第三次全量复测。源码自 `99bd109`
|
||||||
|
以来仅有文档改动,本轮同时验证自动化管线、JAR 制品、真实 Halo 联调与多角色权限。
|
||||||
|
|
||||||
|
```text
|
||||||
|
Commit: fd3ea71 (master,工作区干净,仅文档改动)
|
||||||
|
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 冒烟实例,H2 内置库,
|
||||||
|
一次性数据目录,与生产数据无任何关联)
|
||||||
|
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
|
||||||
|
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、
|
||||||
|
npm 11.17.0(UI 子项目实际使用 npm,无 pnpmCheck 任务,
|
||||||
|
等效检查为 :ui:testFrontend + :ui:buildFrontend)、
|
||||||
|
pnpm 11.22.0 已安装但未被本项目使用
|
||||||
|
Commands run: ./gradlew test --rerun、./gradlew :ui:testFrontend
|
||||||
|
:ui:buildFrontend --rerun、./gradlew check、
|
||||||
|
./gradlew clean build;
|
||||||
|
联调:实例重启恢复、RSA 加密登录(失败+成功)、登出、
|
||||||
|
query/export、匿名与 auditor3 权限矩阵、无效分页参数、
|
||||||
|
告警测试端点(环回拒绝)、停用→启用往返
|
||||||
|
Automated checks: PASS(后端 26 类/270 全过,0 失败 0 跳过;UI vitest 69/69;
|
||||||
|
vue-tsc 类型检查与 vite 构建通过;check 与 clean build 通过)
|
||||||
|
Roles and dependency states: admin(全量权限)与 auditor3(仅 role-template-audit-view,
|
||||||
|
verbs get/list)实测;无权限路径另以匿名会话验证
|
||||||
|
Manual paths checked: 重启后插件自动 STARTED 且历史数据保留(121→167 条);
|
||||||
|
失败登录(含 403 CSRF 拦截与 302 invalid-credential 两类)
|
||||||
|
→login-failure(attemptedUsername=admin);
|
||||||
|
成功登录→login(302→/uc);GET /logout 确认页→logout(200,
|
||||||
|
设计内);POST /logout→logout(302→/login?logout)且原会话
|
||||||
|
权限即时回收;匿名 query 302 拒绝;auditor3 矩阵 5/5
|
||||||
|
(query 200 / export 200 / POST test 403 / DELETE 403 /
|
||||||
|
越权 GET users 403);page=-1&size=0 归一化不 500;
|
||||||
|
导出 CSV 200(35KB,表头+数据完整);告警测试端点对环回
|
||||||
|
地址返回结构化 success:false;停用→query 404→启用→
|
||||||
|
STARTED→query 200;Console bundle 静态资源(入口 JS/CSS)
|
||||||
|
经 /plugins/{name}/assets/console/ 正常下发;
|
||||||
|
服务端日志 0 ERROR
|
||||||
|
Known limitations: DevTools haloServer 因本机无 Docker 不可用(同前两轮);
|
||||||
|
Webhook 公网投递、卸载测试、spec.requires 下探 2.26.0
|
||||||
|
仍未执行(见"未覆盖项");Windows 升级 API JAR 文件锁
|
||||||
|
环境限制未变(本轮未再触发升级)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 联调冒烟结果明细(对照 plugin-testing.md 检查清单)
|
||||||
|
|
||||||
|
| 检查项 | 实测 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 插件能够启动、日志无未处理错误 | 重启后自动 STARTED;`halo-round3.log` 0 条 ERROR | 通过 |
|
||||||
|
| 登录/登出审计(P0 修复路径回归) | 失败登录两类(403 CSRF 拦截、302 invalid-credential)均记 `login-failure`(attemptedUsername=admin);成功登录记 `login`(302→/uc);POST /logout 记 `logout`(302→/login?logout),GET /logout 确认页也记 `logout`(200,`isAuthEndpoint` 设计内) | 通过 |
|
||||||
|
| 操作者归属语义 | 认证端点记录统一 `username=unknown` + `attemptedUsername`(链首无认证上下文,设计行为,非缺陷) | 符合设计 |
|
||||||
|
| API 成功路径 | query(分页/筛选正常,总数 167 持续增长)、export(200,35KB CSV,UTF-8 BOM+中文表头) | 通过 |
|
||||||
|
| 无权限路径 | 匿名 query 302 重定向拒绝;auditor3 越权 GET users 403 | 通过 |
|
||||||
|
| 多角色权限矩阵(auditor3,仅 role-template-audit-view) | query 200 / export 200 / POST alerts test 403 / DELETE auditlog 403 / 越权探测 403,**5/5 符合预期**;角色绑定跨重启持久生效 | 通过 |
|
||||||
|
| 无效输入 | `page=-1&size=0` 归一化处理,无 500 | 通过 |
|
||||||
|
| 依赖失败路径 | `POST alerts/-/test` webhook 指向环回地址被 OutboundUrlGuard 拒绝,返回结构化 `success:false` + 中文原因 | 通过 |
|
||||||
|
| 登录失败告警生产路径 | 失败登录后 `AlertWebhookSender` 实际发起投递(日志 2 条 WARN),因配置的 webhook 为环回地址被出站防护拦截——回调链路真实生效,仅受测试配置所限未送达 | 通过 |
|
||||||
|
| 配置/重启生效 | 实例重启后告警 webhook 配置(上轮残留的环回地址)仍生效并触发投递尝试;角色绑定、启用状态持久化恢复 | 通过 |
|
||||||
|
| 生命周期:停用/启用往返 | 停用→phase DISABLED、query 端点 404 下线;启用→phase STARTED、query 恢复 200;历史数据完整保留 | 通过 |
|
||||||
|
| Console 入口资源 | `ui-plugin.json` 与 hash 文件名入口 JS(21,356B)、CSS(7,375B)经 `/plugins/operation-audit/assets/console/` 正常下发 | 通过 |
|
||||||
|
|
||||||
|
### 本轮联调协议要点(影响可复现性,记录备查)
|
||||||
|
|
||||||
|
- **登录协议**:Halo 2.26 的 `POST /login` 要求密码经登录页内嵌 RSA 公钥
|
||||||
|
(jsencrypt,PKCS#1 v1.5)加密后提交;明文密码提交必然返回
|
||||||
|
`invalid-credential`(服务端解密失败),并非密码错误。
|
||||||
|
- **CSRF 豁免范围**:仅 `/api/**`、`/apis/**`、`/actuator/**`、`/system/setup`
|
||||||
|
豁免;`/login`、`/logout` 均要求 CSRF。表单流程必须提交页面渲染的
|
||||||
|
XOR 编码 `_csrf` 隐藏域值(将 `XSRF-TOKEN` cookie 值直接以 `X-XSRF-TOKEN`
|
||||||
|
头回传**不能**通过校验);`GET /logout` 返回含 `_csrf` 的确认表单,POST
|
||||||
|
/logout 应以该值提交。
|
||||||
|
- Console bundle 静态资源路径为 `/plugins/{name}/assets/console/...`,
|
||||||
|
入口文件名为 vite 产物 hash 名(以 `ui-plugin.json` 的 `entry` 为准)。
|
||||||
|
- API 层面 403 为纯文本 `Access Denied`(Spring 默认 AccessDeniedHandler),
|
||||||
|
无结构化响应体,前端需自行处理展示。
|
||||||
|
|
||||||
|
## 复测记录(2026-11-22 第四轮:发布验收补测,commit `81693e4`/`44eca75`)
|
||||||
|
|
||||||
|
发布验收清单 [plugin-release-checklist.md](./plugin-release-checklist.md) 确认报告的 P1/P2
|
||||||
|
待办补测。本轮覆盖:0.1.0-SNAPSHOT→0.1.0 正式版升级、**卸载(uninstall)生命周期**、
|
||||||
|
卸载后重装闭环,另补齐 manifest 元数据与 `ui/` 输出迁移。
|
||||||
|
|
||||||
|
```text
|
||||||
|
Commit: 81693e4(UI ui/ 迁移+manifest 元数据)/ 44eca75(CI/CD 工作流)
|
||||||
|
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 烟测实例,H2 内置库)
|
||||||
|
与 2.26.0(最低版本下探一次性全新实例,见下节);
|
||||||
|
数据目录均为一次性目录,与生产数据无任何关联
|
||||||
|
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
|
||||||
|
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、npm
|
||||||
|
Automated checks: PASS(clean build -Pversion=0.1.0 全绿;后端+UI 检查同 check)
|
||||||
|
Manual paths checked: 正式版升级(upgrade API,0.1.0-SNAPSHOT→0.1.0,历史 169 条
|
||||||
|
数据保留);卸载全流程(对齐 Console"卸载并删除配置"路径:
|
||||||
|
停用→DELETE Plugin CR→删 Setting/ConfigMap);卸载后核对
|
||||||
|
(CR/JAR/Setting/ConfigMap/RoleTemplate 清理、RoleBindings
|
||||||
|
残留、auditlog 端点 404、日志 0 ERROR);重启后无插件残留;
|
||||||
|
重装 0.1.0(install API→enable→STARTED,审计数据 169→172
|
||||||
|
条完整回归,pf4j disabled.txt 残留被 Halo 自动清除)
|
||||||
|
Known limitations: 2.26.0 最低版本下探已于本节补充执行并通过;Windows 升级 JAR
|
||||||
|
文件锁环境限制未变(本轮 upgrade API 实测正常,旧 JAR 未被锁)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 卸载(uninstall)生命周期核对(对照 plugin-testing.md 第 6 步)
|
||||||
|
|
||||||
|
**卸载前快照**(Halo 2.26.1,0.1.0 STARTED):
|
||||||
|
|
||||||
|
| 资源 | 状态 |
|
||||||
|
| --- | --- |
|
||||||
|
| Plugin CR `operation-audit`(0.1.0,STARTED,169 条审计数据) | ✅ |
|
||||||
|
| Setting `operation-audit-settings` / ConfigMap `operation-audit-configmap` | ✅ 200 |
|
||||||
|
| RoleTemplate `role-template-audit-view` | ✅ 200 |
|
||||||
|
| RoleBindings(auditor3 等 2 个绑定 role-template-audit-view) | ✅ 200 |
|
||||||
|
| JAR `plugins/operation-audit-0.1.0.jar` | ✅ 存在 |
|
||||||
|
|
||||||
|
**卸载操作**(对齐 Console「卸载并删除配置」分支,经查证 Halo 2.26.1 源码
|
||||||
|
`use-plugin.ts` + `PluginReconciler#cleanupResources`):
|
||||||
|
|
||||||
|
1. `PUT /apis/api.console.halo.run/v1alpha1/plugins/operation-audit/plugin-state`(enable=false)→ 200;
|
||||||
|
2. `DELETE /apis/plugin.halo.run/v1alpha1/plugins/operation-audit` → 200
|
||||||
|
(finalizer `plugin-protection` 异步清理,约 24s 完成);
|
||||||
|
3. `DELETE /api/v1alpha1/settings/operation-audit-settings` → 200;
|
||||||
|
4. `DELETE /api/v1alpha1/configmaps/operation-audit-configmap` → 200。
|
||||||
|
|
||||||
|
**卸载后核对**:
|
||||||
|
|
||||||
|
| 核对项 | 结果 | 判定 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Plugin CR(GET) | 404 | ✅ 已删除(finalizer 清理完成) |
|
||||||
|
| JAR(workdir/plugins) | 文件已删除 | ✅ reconciler 清理 |
|
||||||
|
| Setting / ConfigMap | 404 | ✅ 已删除 |
|
||||||
|
| RoleTemplate `role-template-audit-view` | 404 | ✅ 已随插件卸载清理 |
|
||||||
|
| RoleBindings(auditor3 等) | **残留 2 个** | ⚠️ Halo 不清理宿主侧 RoleBinding;RoleTemplate 已删,绑定无实际授权效果,但管理端可见孤儿绑定 |
|
||||||
|
| AuditLog 查询端点 | 404 | ✅ 随插件下线(扩展模型 scheme 注销) |
|
||||||
|
| **审计数据(H2 内)** | 保留 | ✅ Halo 不删除插件自定义扩展数据;卸载后不可见、重装后回归 |
|
||||||
|
| 重启 Halo 后 | 无插件加载、日志 0 ERROR、无残留 JAR | ✅ |
|
||||||
|
| **重装 0.1.0**(install API → enable) | STARTED;审计数据 169→172 条完整回归;**停用期间 pf4j `disabled.txt` 写入的 `operation-audit` 残留被 Halo 启动插件时自动清除** | ✅ 闭环 |
|
||||||
|
|
||||||
|
**卸载结论**:Halo 2.26.1 卸载语义下,本插件卸载行为符合预期——运行时资源
|
||||||
|
(JAR)释放、预置资源(Setting/ConfigMap/RoleTemplate)清理、审计数据保留
|
||||||
|
(重装后回归),无不可恢复的破坏性影响;唯一残留是宿主侧 RoleBinding 孤儿绑定
|
||||||
|
(Halo 平台行为,非本插件可管理范围,重启不影响其他功能,可接受并记录)。
|
||||||
|
|
||||||
|
### 2.26.0 最低版本下探实测(官方发布 JAR,一次性全新实例)
|
||||||
|
|
||||||
|
对应验收清单第 7 步"在声明范围内的最低 Halo 版本上重复关键路径"。制品为同一次
|
||||||
|
干净构建的 `plugin-operation-audit-0.1.0.jar`(SHA-256 见发布证据块);Halo 2.26.0
|
||||||
|
官方独立 JAR(GitHub release 资产,`sha256sum` 与官方 `halo-2.26.0.jar.sha256`
|
||||||
|
逐字符一致),一次性数据目录 `workdir-260`(未初始化生产数据,测试后已停用丢弃)。
|
||||||
|
|
||||||
|
| 检查项 | 实测 | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 系统初始化 | `POST /system/setup`(form-urlencoded,含 siteTitle/externalUrl) | 302 ✅ |
|
||||||
|
| admin 登录 | RSA + `_csrf` 表单契约(同 2.26.1) | 302 ✅ |
|
||||||
|
| 插件安装 | install API 上传 0.1.0 JAR | 200 ✅ |
|
||||||
|
| 插件启用 | CR phase | **STARTED** ✅ |
|
||||||
|
| 审计捕获 | install/enable/update 自身操作入库 | ✅(total=1 起) |
|
||||||
|
| 登录成功审计 | 语义动作 `login` | ✅ |
|
||||||
|
| **登录失败审计** | 错误密码 → 401 JSON(**2.26.0 与 2.26.1 行为不同:2.26.1 为 302→error 参数**),仍被认证端点过滤器捕获 | 语义动作 **`login-failure`** ✅ |
|
||||||
|
| 查询端点 | `GET auditlogs/-/query` | 200 ✅ |
|
||||||
|
| CSV 导出 | `GET auditlogs/-/export` | 200(339B,UTF-8 BOM)✅ |
|
||||||
|
| 匿名拒绝 | 无会话 GET query | 302 重定向 ✅ |
|
||||||
|
| **`ui/` ESM bundle** | `GET /plugins/operation-audit/assets/ui/ui-plugin.json` | 200 ✅(ui/ 迁移产物在 2.26.0 正常下发) |
|
||||||
|
| 实例日志 | 全程 | **0 ERROR** ✅ |
|
||||||
|
|
||||||
|
**结论**:插件在声明最低版本 Halo 2.26.0 上安装、启用、捕获、查询、导出、
|
||||||
|
权限拒绝与 UI 资源下发全部正常;2.26.1(此前三轮联调平台)为当前版本复验。
|
||||||
|
`spec.requires >=2.26.0` 的实测验证完成。
|
||||||
|
|
||||||
|
## 附:测试环境残留与清理
|
||||||
|
|
||||||
|
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / Sm0keTest2026,
|
||||||
|
数据目录 `C:/Users/Windows11/.halo-smoke-test/workdir`,可丢弃,与生产数据无任何关联);
|
||||||
|
- 第三轮联调中将 auditor3 密码重置为 `AuditR3.2026`(供只读角色矩阵复测),
|
||||||
|
残留测试用户 auditor3(role-template-audit-view)保留于实例中;
|
||||||
|
- 已恢复干净版插件 JAR 并确认无诊断日志残留(重启后 0 条 AUDIT-DIAG);
|
||||||
|
- 源码工作区干净,仅新增截图证据目录 `gui-test-screenshots/`(未纳入版本控制)。
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# 仓库根目录不是 Gradle 构建根:插件项目位于 plugin-operation-audit/ 子目录。
|
||||||
|
# Halo 官方可复用插件 CI/CD 工作流(halo-sigs/reusable-workflows)从仓库根执行
|
||||||
|
# ./gradlew clean build,此脚本将调用转发到子项目的 Gradle wrapper。
|
||||||
|
# 本地等价命令:./gradlew clean build -p plugin-operation-audit
|
||||||
|
exec "$(dirname "$0")/plugin-operation-audit/gradlew" "$@"
|
||||||
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
@echo off
|
||||||
|
rem 仓库根目录不是 Gradle 构建根:插件项目位于 plugin-operation-audit\ 子目录。
|
||||||
|
rem Halo 官方可复用插件 CI/CD 工作流(halo-sigs/reusable-workflows)从仓库根执行
|
||||||
|
rem ./gradlew clean build,此脚本将调用转发到子项目的 Gradle wrapper。
|
||||||
|
rem 本地等价命令:gradlew.bat clean build -p plugin-operation-audit
|
||||||
|
"%~dp0plugin-operation-audit\gradlew.bat" %*
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 162 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
@@ -126,11 +126,18 @@ Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配
|
|||||||
- 审计写入失败静默降级为运行日志,不阻塞业务操作。
|
- 审计写入失败静默降级为运行日志,不阻塞业务操作。
|
||||||
- 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置):
|
- 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置):
|
||||||
反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。
|
反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。
|
||||||
|
- **Windows 升级注意事项**:插件运行期间其 JAR 被进程锁定(Windows 文件锁),
|
||||||
|
`upgrade` API 报 500(`FileSystemException: 另一个程序正在使用此文件`),停用插件后
|
||||||
|
句柄也不释放。Windows 站点升级本插件需停服换 JAR 后重启;Linux/macOS 无此限制。
|
||||||
|
|
||||||
## 技术说明
|
## 技术说明
|
||||||
|
|
||||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经 `AfterSecurityWebFilter` 扩展点(认证之后,
|
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||||
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。
|
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||||
|
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||||
|
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||||
|
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||||
|
Extension + 索引查询,全程响应式非阻塞。
|
||||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||||
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
|
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
|
||||||
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求
|
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求
|
||||||
|
|||||||
@@ -38,14 +38,17 @@ test {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 将 ui 子项目构建产物打包进插件 jar 的 console/ 目录(Console 前端入口由 ui-plugin.json 清单声明)
|
// 将 ui 子项目构建产物打包进插件 jar 的 ui/ 目录(Console 前端入口由 ui-plugin.json 清单声明)。
|
||||||
|
// 目标 Halo >=2.25.0 时 ui/ 是官方规范输出位置;console/ 为旧项目兼容回退,本插件不再使用。
|
||||||
tasks.register('processUiResources', Copy) {
|
tasks.register('processUiResources', Copy) {
|
||||||
from project(':ui').layout.buildDirectory.dir('dist')
|
from project(':ui').layout.buildDirectory.dir('dist')
|
||||||
into layout.buildDirectory.dir('resources/main/console')
|
into layout.buildDirectory.dir('resources/main/ui')
|
||||||
dependsOn project(':ui').tasks.named('assemble')
|
dependsOn project(':ui').tasks.named('assemble')
|
||||||
shouldRunAfter tasks.named('processResources')
|
shouldRunAfter tasks.named('processResources')
|
||||||
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar
|
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar;
|
||||||
|
// 同时清掉旧构建可能残留的 console/ 目录,防止过期产物被打进 jar
|
||||||
doFirst {
|
doFirst {
|
||||||
|
delete layout.buildDirectory.dir('resources/main/ui')
|
||||||
delete layout.buildDirectory.dir('resources/main/console')
|
delete layout.buildDirectory.dir('resources/main/console')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-6
@@ -15,8 +15,10 @@ import run.halo.operationaudit.audit.RequestSnapshot;
|
|||||||
* 推送一次 JSON 告警。
|
* 推送一次 JSON 告警。
|
||||||
*
|
*
|
||||||
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
||||||
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
|
* 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入——
|
||||||
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
|
* 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分,
|
||||||
|
* 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值);
|
||||||
|
* 窗口过期同样重开,无失败时不累计。
|
||||||
*
|
*
|
||||||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||||||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||||||
@@ -40,15 +42,17 @@ public class LoginFailureAlertService {
|
|||||||
int failureCount;
|
int failureCount;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
|
* 登录结果回调:仅处理 POST /login 请求(成功清零计数,失败累计告警)。
|
||||||
* 任何失败静默降级,不影响调用方。
|
* 成败由调用方(捕获过滤器)经 {@code LoginOutcome} 判定后传入,本服务不做
|
||||||
|
* 状态码推断。任何失败静默降级,不影响调用方。
|
||||||
*
|
*
|
||||||
|
* @param success 登录是否成功(表单登录 302 重定向目标含 error 参数或
|
||||||
|
* 响应 4xx/5xx 为失败;2xx 与成功重定向为成功)
|
||||||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||||||
* 提取失败为 null)
|
* 提取失败为 null)
|
||||||
*/
|
*/
|
||||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
|
public void onLoginResult(RequestSnapshot snapshot, boolean success,
|
||||||
String attemptedUsername) {
|
String attemptedUsername) {
|
||||||
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
|
|
||||||
settingProvider.get().subscribe(
|
settingProvider.get().subscribe(
|
||||||
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
|
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
|
||||||
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
||||||
|
|||||||
+7
-4
@@ -103,8 +103,11 @@ public class AuditLogCsvExporter {
|
|||||||
private String toCsvLine(AuditLog log) {
|
private String toCsvLine(AuditLog log) {
|
||||||
var spec = log.getSpec();
|
var spec = log.getSpec();
|
||||||
var statusCode = spec.getStatusCode();
|
var statusCode = spec.getStatusCode();
|
||||||
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
|
// 结果语义与前端一致:登录失败标注(HTTP 状态码可能为 200/302——失败回显页
|
||||||
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
|
// 渲染/失败重定向)一律失败,其余 2xx/3xx 成功
|
||||||
|
var failedLogin = OperationDescription.LOGIN_FAILURE_ACTION.equals(spec.getAction());
|
||||||
|
var success = !failedLogin && statusCode != null && statusCode >= 200
|
||||||
|
&& statusCode < 400;
|
||||||
return String.join(",",
|
return String.join(",",
|
||||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||||
escape(spec.getUsername()),
|
escape(spec.getUsername()),
|
||||||
@@ -113,8 +116,8 @@ public class AuditLogCsvExporter {
|
|||||||
escape(spec.getResourceType()),
|
escape(spec.getResourceType()),
|
||||||
escape(spec.getResourceName()),
|
escape(spec.getResourceName()),
|
||||||
escape(spec.getPath()),
|
escape(spec.getPath()),
|
||||||
escape(OperationDescription.describe(
|
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||||
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
escape(OperationDescription.describe(spec)),
|
||||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||||
escape(success ? "成功" : "失败"),
|
escape(success ? "成功" : "失败"),
|
||||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||||
|
|||||||
+9
-3
@@ -56,16 +56,22 @@ final class AuditLogFilters {
|
|||||||
Queries.contains("spec.path", kw)));
|
Queries.contains("spec.path", kw)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||||
|
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||||
|
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||||
var resultFilter = params.getFirst("result");
|
var resultFilter = params.getFirst("result");
|
||||||
if (StringUtils.hasText(resultFilter)) {
|
if (StringUtils.hasText(resultFilter)) {
|
||||||
|
var loginFailure = Queries.equal("spec.action",
|
||||||
|
OperationDescription.LOGIN_FAILURE_ACTION);
|
||||||
switch (resultFilter.trim().toLowerCase()) {
|
switch (resultFilter.trim().toLowerCase()) {
|
||||||
case "success" -> {
|
case "success" -> {
|
||||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||||
|
conditions.add(Queries.not(loginFailure));
|
||||||
}
|
}
|
||||||
case "failure" -> conditions.add(
|
case "failure" -> conditions.add(Queries.or(
|
||||||
Queries.greaterThan("spec.statusCode", "400", true));
|
Queries.greaterThan("spec.statusCode", "400", true),
|
||||||
|
loginFailure));
|
||||||
default -> throw new IllegalArgumentException(
|
default -> throw new IllegalArgumentException(
|
||||||
"Invalid result, expect success or failure: " + resultFilter);
|
"Invalid result, expect success or failure: " + resultFilter);
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-8
@@ -38,9 +38,13 @@ public class AuditRecorder {
|
|||||||
*
|
*
|
||||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||||
|
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
|
||||||
|
* 302 重定向且目标含 error 参数)或失败回显
|
||||||
|
* (GET /login?error=...,HTTP 200),语义动作标注
|
||||||
|
* login-failure;其余请求为 false
|
||||||
*/
|
*/
|
||||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||||
String username, String attemptedUsername) {
|
String username, String attemptedUsername, boolean loginFailed) {
|
||||||
settingProvider.get().subscribe(
|
settingProvider.get().subscribe(
|
||||||
settings -> {
|
settings -> {
|
||||||
if (!settings.enabledOrDefault()) {
|
if (!settings.enabledOrDefault()) {
|
||||||
@@ -48,19 +52,20 @@ public class AuditRecorder {
|
|||||||
snapshot.getMethod(), snapshot.getFullPath());
|
snapshot.getMethod(), snapshot.getFullPath());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||||
},
|
},
|
||||||
e -> {
|
e -> {
|
||||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||||
String username, String attemptedUsername) {
|
String username, String attemptedUsername, boolean loginFailed) {
|
||||||
try {
|
try {
|
||||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
|
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername,
|
||||||
|
loginFailed);
|
||||||
client.create(auditLog)
|
client.create(auditLog)
|
||||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||||
@@ -147,7 +152,7 @@ public class AuditRecorder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||||
String username, String attemptedUsername) {
|
String username, String attemptedUsername, boolean loginFailed) {
|
||||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||||
|
|
||||||
var spec = new AuditLogSpec();
|
var spec = new AuditLogSpec();
|
||||||
@@ -156,11 +161,15 @@ public class AuditRecorder {
|
|||||||
spec.setAttemptedUsername(attemptedUsername);
|
spec.setAttemptedUsername(attemptedUsername);
|
||||||
spec.setMethod(snapshot.getMethod());
|
spec.setMethod(snapshot.getMethod());
|
||||||
spec.setResourceType(resolved.resourceType());
|
spec.setResourceType(resolved.resourceType());
|
||||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
|
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
|
||||||
spec.setAction(OperationDescription.actionOf(
|
// 登录失败(POST /login 失败或 GET /login?error=... 失败回显)标注
|
||||||
|
// login-failure——回显页 HTTP 200 无法由路径重新推导,必须落库标注
|
||||||
|
spec.setAction(loginFailed ? OperationDescription.LOGIN_FAILURE_ACTION
|
||||||
|
: OperationDescription.actionOf(
|
||||||
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
||||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||||
spec.setPath(snapshot.getFullPath());
|
spec.setPath(snapshot.getFullPath());
|
||||||
|
// 状态码如实记录(失败回显页为 200、表单登录失败为 302),登录成败看语义动作标注
|
||||||
spec.setStatusCode(statusCode);
|
spec.setStatusCode(statusCode);
|
||||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||||
spec.setUserAgent(snapshot.getUserAgent());
|
spec.setUserAgent(snapshot.getUserAgent());
|
||||||
|
|||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||||
|
import static run.halo.operationaudit.audit.CaptureRule.isLoginAttempt;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
import org.springframework.web.server.WebFilter;
|
||||||
|
import org.springframework.web.server.WebFilterChain;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import run.halo.app.security.BeforeSecurityWebFilter;
|
||||||
|
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 认证端点({@code /login}、{@code /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||||
|
*
|
||||||
|
* <p>以 {@link BeforeSecurityWebFilter} 扩展点注册:位于 Security 过滤链最前
|
||||||
|
* ({@code SecurityWebFiltersOrder.FIRST})。原先认证端点由
|
||||||
|
* {@code AfterSecurityWebFilter} 扩展点注册的 {@link OperationAuditWebFilter} 捕获,
|
||||||
|
* 但该扩展点位于认证环节之后——表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
|
||||||
|
* 请求后直接完成 302 响应、不再向下游传递,POST /login 与 POST /logout 永远到不了
|
||||||
|
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证端点整体
|
||||||
|
* 移交本过滤器,在 Security 链之前承接捕获与记录。
|
||||||
|
*
|
||||||
|
* <p>操作者归属:Security 链最前无认证上下文(SecurityContext 由链内更晚位置的
|
||||||
|
* ReactorContextWebFilter 写入订阅上下文,对链首过滤器不可见),统一记
|
||||||
|
* {@link AuditLogSpec#UNKNOWN_USERNAME 未知用户}(既有兜底路径);登录尝试的账号
|
||||||
|
* 由 {@link LoginAttemptCapture} 从请求体白名单提取,落库 {@code spec.attemptedUsername}
|
||||||
|
* 并进入告警负载(功能评审 P0-1),账号归属信息不受影响。
|
||||||
|
*
|
||||||
|
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||||
|
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||||
|
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||||
|
* {@code error} 参数区分,不能只看状态码)。
|
||||||
|
*
|
||||||
|
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||||
|
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||||
|
* 与筛选;HTTP 状态码仍如实记录。
|
||||||
|
*
|
||||||
|
* <p>任何失败均静默降级(记录器与告警服务内部兜底),绝不影响登录主流程(设计原则 4)。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||||
|
|
||||||
|
private final AuditRecorder recorder;
|
||||||
|
private final HttpWriteMarker writeMarker;
|
||||||
|
private final LoginAttemptCapture loginAttemptCapture;
|
||||||
|
private final LoginFailureAlertService loginFailureAlertService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||||
|
var request = exchange.getRequest();
|
||||||
|
var path = request.getPath().value();
|
||||||
|
var method = request.getMethod().name();
|
||||||
|
if (!isAuthEndpoint(path)) {
|
||||||
|
// 非 /login、/logout 一律原样透传:不触碰请求体、不读会话,零附加开销
|
||||||
|
return chain.filter(exchange);
|
||||||
|
}
|
||||||
|
writeMarker.onRequestStart(request);
|
||||||
|
var snapshot = RequestSnapshot.of(request);
|
||||||
|
var loginAttempt = new LoginAttempt();
|
||||||
|
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||||
|
// 登出与登录页 GET 原样透传
|
||||||
|
var bodyPrepared = isLoginAttempt(path, method)
|
||||||
|
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||||
|
: Mono.just(exchange);
|
||||||
|
return bodyPrepared
|
||||||
|
.flatMap(chain::filter)
|
||||||
|
.doFinally(signal -> {
|
||||||
|
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)) {
|
||||||
|
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||||
|
// 成功清零计数、失败累计,独立于审计记录
|
||||||
|
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
|
||||||
|
loginAttempt.getAttemptedUsername());
|
||||||
|
}
|
||||||
|
recorder.record(snapshot, null, statusCode,
|
||||||
|
AuditLogSpec.UNKNOWN_USERNAME,
|
||||||
|
loginAttempt.getAttemptedUsername(), loginFailed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Integer statusOf(ServerWebExchange exchange) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-10
@@ -6,9 +6,14 @@ import java.util.Set;
|
|||||||
* 捕获规则(纯函数,技术方案 D1):
|
* 捕获规则(纯函数,技术方案 D1):
|
||||||
*
|
*
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>{@code POST/PUT/DELETE/PATCH} + 路径前缀 {@code /apis/}</li>
|
* <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
|
||||||
* <li>或路径精确匹配 {@code /login}、{@code /logout}(登录端点不在 /apis/** 下,
|
* 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
|
||||||
* 是“一条通用规则覆盖全部管理面操作”的唯一必要例外,需在产品文档同步注明)</li>
|
* 可获得认证用户上下文);</li>
|
||||||
|
* <li>认证端点 {@code /login}、{@code /logout} 精确匹配({@link #isAuthEndpoint},
|
||||||
|
* 由 {@link AuthEndpointAuditWebFilter} 消费)——登录端点不在 /apis/** 下,且
|
||||||
|
* 表单登录/登出过滤器命中请求后直接完成响应、不再向下游传递,链尾的
|
||||||
|
* AfterSecurityWebFilter 永远看不到(P0 缺陷实测),因此必须在 Security 链之前
|
||||||
|
* 独立捕获。</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||||
@@ -25,26 +30,29 @@ public final class CaptureRule {
|
|||||||
private CaptureRule() {
|
private CaptureRule() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 是否命中捕获规则。path 为不含查询串的请求路径。 */
|
/**
|
||||||
|
* 是否命中捕获规则。path 为不含查询串的请求路径。
|
||||||
|
*
|
||||||
|
* <p>仅覆盖 {@code /apis/**} 写操作;认证端点由 {@link #isAuthEndpoint} 单独判定、
|
||||||
|
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
|
||||||
|
* 互不重叠,不会重复记录。
|
||||||
|
*/
|
||||||
public static boolean shouldCapture(String path, String method) {
|
public static boolean shouldCapture(String path, String method) {
|
||||||
if (isAuthEndpoint(path)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (path == null || !path.startsWith(APIS_PREFIX)) {
|
if (path == null || !path.startsWith(APIS_PREFIX)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return method != null && WRITE_METHODS.contains(method);
|
return method != null && WRITE_METHODS.contains(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 是否为登录/登出端点。 */
|
/** 是否为登录/登出端点(由 {@link AuthEndpointAuditWebFilter} 捕获)。 */
|
||||||
public static boolean isAuthEndpoint(String path) {
|
public static boolean isAuthEndpoint(String path) {
|
||||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||||
* 登录失败告警的触发条件——2xx 为登录成功,其余为失败;
|
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||||
* 登录页 GET 与登出不算。
|
* 302 重定向,不能只看状态码);登录页 GET 与登出不算。
|
||||||
*/
|
*/
|
||||||
public static boolean isLoginAttempt(String path, String method) {
|
public static boolean isLoginAttempt(String path, String method) {
|
||||||
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
||||||
|
|||||||
+53
-46
@@ -3,8 +3,8 @@ package run.halo.operationaudit.audit;
|
|||||||
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import java.net.URLDecoder;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.core.io.buffer.DataBuffer;
|
import org.springframework.core.io.buffer.DataBuffer;
|
||||||
@@ -20,20 +20,27 @@ import run.halo.app.extension.Unstructured;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
||||||
* 登录端点非注册模型,与 {@link ChangeCaptureManager} 的 JSON 缓存逻辑分开,
|
* 登录端点非注册模型,为登录端点单独提取尝试的用户名。
|
||||||
* 为登录端点单独补一条请求体读取:缓存请求体(下游可重复读)并提取尝试的用户名。
|
|
||||||
*
|
*
|
||||||
* <p>提取规则(安全边界):
|
* <p>提取规则(安全边界):
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
||||||
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
||||||
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
||||||
* <li>请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存,
|
* <li>超长用户名({@value #MAX_USERNAME_LENGTH} 字符以上)视为扫描载荷,不提取。</li>
|
||||||
* 与字段级变更捕获同款边界(分块传输/超限一律不读,仅不提取用户名)。</li>
|
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
|
* <p>表单形态({@code application/x-www-form-urlencoded}):经
|
||||||
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
|
* {@link ServerWebExchange#getFormData()} 读取——该 Mono 由
|
||||||
|
* {@code DefaultServerWebExchange} 在构造时创建并 {@code cache()},与下游 CSRF 过滤器、
|
||||||
|
* 表单登录转换器共享同一份解析结果。<b>绝不缓存原始请求体并装饰 exchange</b>:
|
||||||
|
* 装饰后的 exchange 会将 {@code getFormData()} 代理回原始 exchange、解析已被消费的
|
||||||
|
* 原始 body,导致下游 CSRF 读不到 {@code _csrf} 参数而拒绝登录(真实环境回归实证,
|
||||||
|
* 登录页表单提交整体失效)。JSON 形态则缓存原始请求体并装饰(下游无表单语义、
|
||||||
|
* 登录转换器不读 JSON 体,装饰使其可重复读)。
|
||||||
|
*
|
||||||
|
* <p>JSON 形态经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存;
|
||||||
|
* 分块传输/超限一律不读。任何解析异常均静默降级为不提取(返回 null),
|
||||||
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
|
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
|
||||||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||||||
*/
|
*/
|
||||||
@@ -41,23 +48,39 @@ import run.halo.app.extension.Unstructured;
|
|||||||
@Component
|
@Component
|
||||||
public class LoginAttemptCapture {
|
public class LoginAttemptCapture {
|
||||||
|
|
||||||
/** 登录请求体缓存上限(字节):登录表单极小,上限远小于字段级变更捕获。 */
|
/** JSON 请求体缓存上限(字节):登录请求体极小,上限远小于字段级变更捕获。 */
|
||||||
static final int MAX_BODY_BYTES = 64 * 1024;
|
static final int MAX_BODY_BYTES = 64 * 1024;
|
||||||
|
|
||||||
|
/** 提取的用户名长度上限:超过视为扫描载荷,不提取(保证记录与告警负载卫生)。 */
|
||||||
|
static final int MAX_USERNAME_LENGTH = 256;
|
||||||
|
|
||||||
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
|
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
|
||||||
static final Set<String> USERNAME_FIELDS = Set.of("username");
|
static final Set<String> USERNAME_FIELDS = Set.of("username");
|
||||||
|
|
||||||
private static final String USERNAME_FIELD = "username";
|
private static final String USERNAME_FIELD = "username";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 为登录请求缓存请求体并提取尝试的用户名。返回(可能包装了缓存请求体的)交换对象
|
* 为登录请求提取尝试的用户名。返回交换对象供后续链路继续处理;返回的 Mono
|
||||||
* 供后续链路继续处理;返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange。
|
* 永不报错、永不为空:任何失败均回退原 exchange。
|
||||||
*/
|
*/
|
||||||
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, LoginAttempt attempt) {
|
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, LoginAttempt attempt) {
|
||||||
var contentType = exchange.getRequest().getHeaders().getContentType();
|
var contentType = exchange.getRequest().getHeaders().getContentType();
|
||||||
if (!supported(contentType)) {
|
if (!supported(contentType)) {
|
||||||
return Mono.just(exchange);
|
return Mono.just(exchange);
|
||||||
}
|
}
|
||||||
|
if (isForm(contentType)) {
|
||||||
|
return exchange.getFormData()
|
||||||
|
.map(form -> {
|
||||||
|
attempt.setAttemptedUsername(usernameOfFormValues(form.get(USERNAME_FIELD)));
|
||||||
|
return exchange;
|
||||||
|
})
|
||||||
|
.defaultIfEmpty(exchange)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.warn("Failed to capture login attempt form for username extraction", e);
|
||||||
|
return Mono.just(exchange);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// JSON 形态:缓存原始请求体(装饰后可重复读)并提取顶层 username 字段
|
||||||
var contentLength = exchange.getRequest().getHeaders().getContentLength();
|
var contentLength = exchange.getRequest().getHeaders().getContentLength();
|
||||||
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
||||||
// 分块传输(无 Content-Length)或超限:不读请求体,避免中断流式请求
|
// 分块传输(无 Content-Length)或超限:不读请求体,避免中断流式请求
|
||||||
@@ -68,7 +91,7 @@ public class LoginAttemptCapture {
|
|||||||
var bytes = new byte[joined.readableByteCount()];
|
var bytes = new byte[joined.readableByteCount()];
|
||||||
joined.read(bytes);
|
joined.read(bytes);
|
||||||
DataBufferUtils.release(joined);
|
DataBufferUtils.release(joined);
|
||||||
attempt.setAttemptedUsername(extract(bytes, contentType));
|
attempt.setAttemptedUsername(extractJson(bytes));
|
||||||
return decorate(exchange, bytes);
|
return decorate(exchange, bytes);
|
||||||
})
|
})
|
||||||
.defaultIfEmpty(exchange)
|
.defaultIfEmpty(exchange)
|
||||||
@@ -83,16 +106,16 @@ public class LoginAttemptCapture {
|
|||||||
if (contentType == null) {
|
if (contentType == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|
return isForm(contentType) || ChangeCaptureManager.isJson(contentType);
|
||||||
|| ChangeCaptureManager.isJson(contentType);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
|
private static boolean isForm(MediaType contentType) {
|
||||||
private static String extract(byte[] bytes, MediaType contentType) {
|
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED);
|
||||||
try {
|
|
||||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
|
|
||||||
return usernameOfForm(new String(bytes, StandardCharsets.UTF_8));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** JSON 体提取:仅取顶层白名单字段的标量值;任何异常静默返回 null。 */
|
||||||
|
private static String extractJson(byte[] bytes) {
|
||||||
|
try {
|
||||||
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
|
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// 解析异常静默:不提取,不影响登录主流程
|
// 解析异常静默:不提取,不影响登录主流程
|
||||||
@@ -101,28 +124,18 @@ public class LoginAttemptCapture {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
|
* 表单字段提取:仅取白名单字段的值(同名多值取最后一个,与逐字段解析语义一致);
|
||||||
|
* 超长值视为扫描载荷不提取。
|
||||||
*/
|
*/
|
||||||
static String usernameOfForm(String body) {
|
static String usernameOfFormValues(List<String> values) {
|
||||||
if (body == null || body.isBlank()) {
|
if (values == null || values.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
try {
|
var found = values.get(values.size() - 1);
|
||||||
String found = null;
|
if (!StringUtils.hasText(found) || found.length() > MAX_USERNAME_LENGTH) {
|
||||||
for (var pair : body.split("&")) {
|
|
||||||
var idx = pair.indexOf('=');
|
|
||||||
var name = safeDecode(idx < 0 ? pair : pair.substring(0, idx));
|
|
||||||
if (!USERNAME_FIELDS.contains(name)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
var value = safeDecode(idx < 0 ? "" : pair.substring(idx + 1));
|
|
||||||
found = maskIfSensitive(name, value);
|
|
||||||
}
|
|
||||||
return StringUtils.hasText(found) ? found : null;
|
|
||||||
} catch (Exception e) {
|
|
||||||
// 表单解析异常静默:不提取,不影响登录主流程
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
return maskIfSensitive(USERNAME_FIELD, found);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
||||||
@@ -135,7 +148,10 @@ public class LoginAttemptCapture {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
var text = value.asText();
|
var text = value.asText();
|
||||||
return StringUtils.hasText(text) ? maskIfSensitive(USERNAME_FIELD, text) : null;
|
if (!StringUtils.hasText(text) || text.length() > MAX_USERNAME_LENGTH) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return maskIfSensitive(USERNAME_FIELD, text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -147,16 +163,7 @@ public class LoginAttemptCapture {
|
|||||||
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
|
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** URL 编码解码失败(如裸 %)回退原值,尽力提取、绝不抛出。 */
|
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游可重复读。 */
|
||||||
private static String safeDecode(String value) {
|
|
||||||
try {
|
|
||||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游登录处理可正常读取。 */
|
|
||||||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||||||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录结果判定(纯函数):Halo 2.26 登录端点的成功/失败在 HTTP 层并非「非 2xx 即失败」——
|
||||||
|
* 表单提交的成功与失败都以 302 重定向收尾(成功 → {@code /uc} 或 2FA 页;失败 →
|
||||||
|
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
|
||||||
|
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
|
||||||
|
* 因此登录结果须结合重定向目标判定,不能只看状态码。
|
||||||
|
*/
|
||||||
|
public final class LoginOutcome {
|
||||||
|
|
||||||
|
private LoginOutcome() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST {@code /login} 的登录结果判定(Halo 2.26 登录端点契约):
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
|
||||||
|
* <li>3xx → 重定向目标查询串含 {@code error} 参数 → 失败(表单登录失败统一重定向
|
||||||
|
* 到 {@code /login?error=invalid-credential&method=...} 等,含无值的
|
||||||
|
* {@code /login?error&method=...});其余重定向目标(成功 → {@code /uc}、
|
||||||
|
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
|
||||||
|
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public static boolean isFailure(Integer statusCode, URI location) {
|
||||||
|
if (statusCode == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (statusCode >= 200 && statusCode < 300) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (statusCode >= 300 && statusCode < 400) {
|
||||||
|
return location != null && 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) {
|
||||||
|
if (query == null || query.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Arrays.stream(query.split("&"))
|
||||||
|
.map(pair -> {
|
||||||
|
var idx = pair.indexOf('=');
|
||||||
|
return idx < 0 ? pair : pair.substring(0, idx);
|
||||||
|
})
|
||||||
|
.anyMatch("error"::equals);
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-48
@@ -3,7 +3,6 @@ package run.halo.operationaudit.audit;
|
|||||||
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContext;
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@@ -13,13 +12,15 @@ import org.springframework.web.server.WebFilterChain;
|
|||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
import reactor.util.context.ContextView;
|
import reactor.util.context.ContextView;
|
||||||
import run.halo.app.security.AfterSecurityWebFilter;
|
import run.halo.app.security.AfterSecurityWebFilter;
|
||||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 审计捕获过滤器(技术方案 D1 / 5.1)。
|
* 审计捕获过滤器(技术方案 D1 / 5.1),仅负责 {@code /apis/**} 写操作。
|
||||||
*
|
*
|
||||||
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
|
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
|
||||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。
|
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。认证端点
|
||||||
|
* ({@code /login}、{@code /logout})不在此过滤器捕获——表单登录/登出过滤器命中请求后
|
||||||
|
* 直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到(P0 缺陷实测);
|
||||||
|
* 详见 {@link AuthEndpointAuditWebFilter}。
|
||||||
*
|
*
|
||||||
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
|
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
|
||||||
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
||||||
@@ -29,15 +30,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
|||||||
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
||||||
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
||||||
*
|
*
|
||||||
* <p>系统内部变更(产品设计 V2):所有写方法请求(含未被捕获规则命中的 {@code /api/**}
|
* <p>系统内部变更(产品设计 V2):未被捕获规则命中的写方法请求({@code /api/**}
|
||||||
* 核心模型与登录端点)均经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
* 核心模型)同样经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||||
*
|
|
||||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
|
||||||
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
|
|
||||||
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
|
|
||||||
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
|
|
||||||
* {@code spec.attemptedUsername} 并进入告警负载。
|
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -49,8 +44,6 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
private final AuditRecorder recorder;
|
private final AuditRecorder recorder;
|
||||||
private final ChangeCaptureManager captureManager;
|
private final ChangeCaptureManager captureManager;
|
||||||
private final HttpWriteMarker writeMarker;
|
private final HttpWriteMarker writeMarker;
|
||||||
private final LoginAttemptCapture loginAttemptCapture;
|
|
||||||
private final LoginFailureAlertService loginFailureAlertService;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||||
@@ -58,7 +51,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
var path = request.getPath().value();
|
var path = request.getPath().value();
|
||||||
var method = request.getMethod().name();
|
var method = request.getMethod().name();
|
||||||
if (!shouldCapture(path, method)) {
|
if (!shouldCapture(path, method)) {
|
||||||
// 未命中捕获规则的写方法请求(/api/** 核心模型、登录端点等)不记录,
|
// 未命中捕获规则的写方法请求(/api/** 核心模型等)不记录,
|
||||||
// 但仍登记标记:请求期触发的资源变更由该请求归属
|
// 但仍登记标记:请求期触发的资源变更由该请求归属
|
||||||
if (CaptureRule.WRITE_METHODS.contains(method)) {
|
if (CaptureRule.WRITE_METHODS.contains(method)) {
|
||||||
writeMarker.onRequestStart(request);
|
writeMarker.onRequestStart(request);
|
||||||
@@ -70,29 +63,17 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
writeMarker.onRequestStart(request);
|
writeMarker.onRequestStart(request);
|
||||||
var snapshot = RequestSnapshot.of(request);
|
var snapshot = RequestSnapshot.of(request);
|
||||||
var capture = new ChangeCapture();
|
var capture = new ChangeCapture();
|
||||||
var loginAttempt = new LoginAttempt();
|
return captureManager.prepare(exchange, snapshot, capture)
|
||||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
.flatMap(chain::filter)
|
||||||
// 其余请求原样透传
|
|
||||||
var bodyPrepared = CaptureRule.isLoginAttempt(path, method)
|
|
||||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
|
||||||
: Mono.just(exchange);
|
|
||||||
return bodyPrepared
|
|
||||||
.flatMap(prepared -> captureManager.prepare(prepared, snapshot, capture))
|
|
||||||
.flatMap(prepared -> chain.filter(prepared))
|
|
||||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||||
signal -> {
|
signal -> {
|
||||||
writeMarker.onRequestComplete(request);
|
writeMarker.onRequestComplete(request);
|
||||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
var statusCode = statusOf(exchange);
|
||||||
// 2xx 清零计数、其余累计,独立于下方审计记录决策
|
operatorOf(ctx).subscribe(
|
||||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
|
||||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
|
|
||||||
loginAttempt.getAttemptedUsername());
|
|
||||||
}
|
|
||||||
operatorOf(ctx, path).subscribe(
|
|
||||||
username -> {
|
username -> {
|
||||||
if (shouldRecord(path, username)) {
|
if (shouldRecord(username)) {
|
||||||
recorder.record(snapshot, capture, statusOf(exchange), username,
|
recorder.record(snapshot, capture, statusCode, username,
|
||||||
loginAttempt.getAttemptedUsername());
|
null, false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||||
@@ -102,10 +83,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
/**
|
/**
|
||||||
* 从订阅上下文解析操作者用户名。
|
* 从订阅上下文解析操作者用户名。
|
||||||
*
|
*
|
||||||
* <p>上下文中无 SecurityContext(匿名请求)→ 空用户名;登录端点的匿名请求记“未知用户”。
|
* <p>上下文中无 SecurityContext 或认证无用户名 → 记“未知用户”占位。
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static Mono<String> operatorOf(ContextView ctx, String path) {
|
private static Mono<String> operatorOf(ContextView ctx) {
|
||||||
return ctx.getOrEmpty(SecurityContext.class)
|
return ctx.getOrEmpty(SecurityContext.class)
|
||||||
.map(value -> ((Mono<SecurityContext>) value)
|
.map(value -> ((Mono<SecurityContext>) value)
|
||||||
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
|
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
|
||||||
@@ -116,13 +97,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录决策(技术方案 D1):匿名判断在记录时做——
|
* 记录决策(技术方案 D1):匿名判断在记录时做——认证后仍为匿名主体
|
||||||
* {@code /apis/**} 下认证后仍为匿名主体(401/403 场景)的请求跳过不记。
|
* (401/403 场景)的请求跳过不记。
|
||||||
*/
|
*/
|
||||||
private static boolean shouldRecord(String path, String username) {
|
private static boolean shouldRecord(String username) {
|
||||||
if (CaptureRule.isAuthEndpoint(path)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
|
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
|
||||||
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
|
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
|
||||||
}
|
}
|
||||||
@@ -131,10 +109,4 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
|||||||
var status = exchange.getResponse().getStatusCode();
|
var status = exchange.getResponse().getStatusCode();
|
||||||
return status != null ? status.value() : 0;
|
return status != null ? status.value() : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
|
|
||||||
static boolean isAnonymous(Authentication authentication) {
|
|
||||||
return authentication == null || !StringUtils.hasText(authentication.getName())
|
|
||||||
|| ANONYMOUS_USER.equals(authentication.getName());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+21
@@ -64,9 +64,17 @@ final class OperationDescription {
|
|||||||
Map.entry("password", "password"),
|
Map.entry("password", "password"),
|
||||||
Map.entry("resetpassword", "resetpassword"));
|
Map.entry("resetpassword", "resetpassword"));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||||
|
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||||
|
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||||
|
*/
|
||||||
|
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||||
|
|
||||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||||
Map.entry("login", "登录"),
|
Map.entry("login", "登录"),
|
||||||
|
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||||
Map.entry("logout", "登出"),
|
Map.entry("logout", "登出"),
|
||||||
Map.entry("auth", "认证操作"),
|
Map.entry("auth", "认证操作"),
|
||||||
Map.entry("password", "修改密码"),
|
Map.entry("password", "修改密码"),
|
||||||
@@ -149,6 +157,19 @@ final class OperationDescription {
|
|||||||
return method + resourceLabel(resourceType);
|
return method + resourceLabel(resourceType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||||
|
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||||
|
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||||
|
*/
|
||||||
|
static String describe(AuditLogSpec spec) {
|
||||||
|
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||||
|
if (phrase != null) {
|
||||||
|
return phrase;
|
||||||
|
}
|
||||||
|
return describe(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||||
|
}
|
||||||
|
|
||||||
private static String resourceLabel(String resourceType) {
|
private static String resourceLabel(String resourceType) {
|
||||||
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
|
||||||
|
<!-- 操作审计插件 logo:审计清单(带勾选记录的文档) -->
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||||
|
<stop offset="0" stop-color="#4f6ef7"/>
|
||||||
|
<stop offset="1" stop-color="#2743c8"/>
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<rect x="4" y="4" width="120" height="120" rx="28" fill="url(#bg)"/>
|
||||||
|
<!-- 文档主体 -->
|
||||||
|
<rect x="34" y="30" width="60" height="68" rx="10" fill="#ffffff" opacity="0.96"/>
|
||||||
|
<!-- 顶部夹子 -->
|
||||||
|
<rect x="50" y="22" width="28" height="14" rx="7" fill="#dbe3ff"/>
|
||||||
|
<!-- 记录行:条目 + 勾选 -->
|
||||||
|
<circle cx="48" cy="52" r="5" fill="#2743c8"/>
|
||||||
|
<rect x="58" y="49" width="26" height="6" rx="3" fill="#b9c4f5"/>
|
||||||
|
<circle cx="48" cy="68" r="5" fill="#2743c8"/>
|
||||||
|
<rect x="58" y="65" width="26" height="6" rx="3" fill="#b9c4f5"/>
|
||||||
|
<path d="M43 85 l6 7 l12 -14" stroke="#2743c8" stroke-width="6" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
<rect x="64" y="82" width="20" height="6" rx="3" fill="#b9c4f5"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -7,9 +7,15 @@ spec:
|
|||||||
requires: ">=2.26.0"
|
requires: ">=2.26.0"
|
||||||
author:
|
author:
|
||||||
name: Guichumo
|
name: Guichumo
|
||||||
|
website: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||||
|
logo: logo.svg
|
||||||
|
homepage: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||||
|
repo: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||||
|
issues: http://101.43.163.221:3000/836061373/halo-ops-audit/issues
|
||||||
displayName: "操作审计"
|
displayName: "操作审计"
|
||||||
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
|
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
|
||||||
settingName: operation-audit-settings
|
settingName: operation-audit-settings
|
||||||
configMapName: operation-audit-configmap
|
configMapName: operation-audit-configmap
|
||||||
license:
|
license:
|
||||||
- name: "GPL-3.0"
|
- name: "GPL-3.0"
|
||||||
|
url: "https://www.gnu.org/licenses/gpl-3.0.html"
|
||||||
|
|||||||
+17
-15
@@ -167,22 +167,24 @@ class LoginFailureAlertServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldTreat3xxAsFailure() {
|
void shouldCountFailureFromCallbackFlag() {
|
||||||
|
// 状态码→成败的解释已上移到 LoginOutcome(表单登录成败均为 302 重定向),
|
||||||
|
// 服务只按回调布尔计数:false 计失败
|
||||||
enableAlerts(1, 5);
|
enableAlerts(1, 5);
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 302, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldTreat2xxAsSuccess() {
|
void shouldResetCounterOnSuccessCallback() {
|
||||||
enableAlerts(1, 5);
|
enableAlerts(1, 5);
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 200, null);
|
service.onLoginResult(snapshot, true, null);
|
||||||
service.onLoginResult(snapshot, 204, null);
|
service.onLoginResult(snapshot, true, null);
|
||||||
|
|
||||||
verify(sender, never()).send(any(), any());
|
verify(sender, never()).send(any(), any());
|
||||||
}
|
}
|
||||||
@@ -192,7 +194,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
enableAlerts(1, 5);
|
enableAlerts(1, 5);
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||||
}
|
}
|
||||||
@@ -203,7 +205,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
enableAlerts(1, 5);
|
enableAlerts(1, 5);
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 401, "admin");
|
service.onLoginResult(snapshot, false, "admin");
|
||||||
|
|
||||||
var payload = capturedPayload();
|
var payload = capturedPayload();
|
||||||
assertThat((String) payload.get("content")).contains("尝试的账号:admin");
|
assertThat((String) payload.get("content")).contains("尝试的账号:admin");
|
||||||
@@ -216,7 +218,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
enableAlerts(1, 5);
|
enableAlerts(1, 5);
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
var payload = capturedPayload();
|
var payload = capturedPayload();
|
||||||
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
|
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
|
||||||
@@ -231,8 +233,8 @@ class LoginFailureAlertServiceTest {
|
|||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
|
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
verify(sender, never()).send(any(), any());
|
verify(sender, never()).send(any(), any());
|
||||||
assertThat(service.failureCount).isZero();
|
assertThat(service.failureCount).isZero();
|
||||||
@@ -247,8 +249,8 @@ class LoginFailureAlertServiceTest {
|
|||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
// 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
|
// 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
verify(sender, never()).send(any(), any());
|
verify(sender, never()).send(any(), any());
|
||||||
assertThat(service.failureCount).isZero();
|
assertThat(service.failureCount).isZero();
|
||||||
@@ -259,7 +261,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||||
var snapshot = loginSnapshot();
|
var snapshot = loginSnapshot();
|
||||||
|
|
||||||
assertThatCode(() -> service.onLoginResult(snapshot, 401, null))
|
assertThatCode(() -> service.onLoginResult(snapshot, false, null))
|
||||||
.doesNotThrowAnyException();
|
.doesNotThrowAnyException();
|
||||||
|
|
||||||
verify(sender, never()).send(any(), any());
|
verify(sender, never()).send(any(), any());
|
||||||
@@ -271,7 +273,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
doThrow(new IllegalStateException("webhook broken"))
|
doThrow(new IllegalStateException("webhook broken"))
|
||||||
.when(sender).send(any(), any());
|
.when(sender).send(any(), any());
|
||||||
|
|
||||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401, null))
|
assertThatCode(() -> service.onLoginResult(loginSnapshot(), false, null))
|
||||||
.doesNotThrowAnyException();
|
.doesNotThrowAnyException();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,7 +284,7 @@ class LoginFailureAlertServiceTest {
|
|||||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
service.onLoginResult(snapshot, 401, null);
|
service.onLoginResult(snapshot, false, null);
|
||||||
|
|
||||||
var payload = capturedPayload();
|
var payload = capturedPayload();
|
||||||
assertThat((String) payload.get("content")).doesNotContain("()");
|
assertThat((String) payload.get("content")).doesNotContain("()");
|
||||||
|
|||||||
+26
@@ -114,6 +114,32 @@ class AuditExportEndpointTest {
|
|||||||
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
|
||||||
|
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页
|
||||||
|
// (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」;
|
||||||
|
// 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」
|
||||||
|
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");
|
||||||
|
failedFormLogin.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||||
|
var failureEcho = auditLog("auditlog-2", time.plusSeconds(60), "unknown", null, "GET",
|
||||||
|
"auth", null, "/login?error=invalid-credential&method=local", 200, "119.53.161.18",
|
||||||
|
"Mozilla/5.0");
|
||||||
|
failureEcho.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||||
|
stubSinglePage(List.of(failedFormLogin, failureEcho));
|
||||||
|
|
||||||
|
var body = exportAndGetBody(EXPORT_URI);
|
||||||
|
|
||||||
|
var lines = body.split("\r\n");
|
||||||
|
assertThat(lines).hasSize(3);
|
||||||
|
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||||
|
+ ",unknown,admin,POST,auth,,/login,登录失败,,失败,302,119.53.161.18,Mozilla/5.0");
|
||||||
|
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||||
|
+ ",unknown,,GET,auth,,/login?error=invalid-credential&method=local"
|
||||||
|
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||||
|
|||||||
+307
@@ -0,0 +1,307 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
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.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.timeout;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
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;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||||
|
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.authentication.ReactiveAuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
||||||
|
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
|
||||||
|
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.User;
|
||||||
|
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||||
|
import org.springframework.security.web.server.WebFilterChainProxy;
|
||||||
|
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler;
|
||||||
|
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
|
||||||
|
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
import org.springframework.web.server.WebFilter;
|
||||||
|
import org.springframework.web.server.WebFilterChain;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 真实 Spring Security 过滤链集成测试(P0 修复回归防线)。
|
||||||
|
*
|
||||||
|
* <p>组件隔离测试(单元测试)无法发现的问题:表单登录/登出过滤器命中请求后直接完成
|
||||||
|
* 302 响应、不再向下游传递。本测试按 Halo 真实组装方式(源码级验证
|
||||||
|
* {@code SecurityWebFiltersConfigurer})构建 {@link SecurityWebFilterChain}:
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link AuthEndpointAuditWebFilter} 注册于 {@link SecurityWebFiltersOrder#FIRST}
|
||||||
|
* (对应插件 {@code BeforeSecurityWebFilter} 扩展点);</li>
|
||||||
|
* <li>表单登录在 FORM_LOGIN、登出在 LOGOUT(命中即终止响应,模拟 Halo 行为);</li>
|
||||||
|
* <li>认证上下文注入过滤器模拟 ReactorContextWebFilter 的上下文写入;</li>
|
||||||
|
* <li>{@link OperationAuditWebFilter} 注册于 {@link SecurityWebFiltersOrder#LAST}
|
||||||
|
* (对应插件 {@code AfterSecurityWebFilter} 扩展点)。</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>核心断言:POST /login(成败)、POST /logout 在真实链上均产生审计记录并回调
|
||||||
|
* 登录失败告警;{@code /apis/**} 写操作仍由链尾过滤器记录且操作者来自认证上下文。
|
||||||
|
*
|
||||||
|
* <p>验证时序:真实链存在线程切换(Security 链内过滤器切换调度器),且 Reactor 的
|
||||||
|
* {@code doFinally} 回调在完成信号向下游传播之后执行——{@code verifyComplete()} 返回时
|
||||||
|
* 记录可能尚未落库。生产路径为 fire-and-forget(记录器自行订阅),故本测试统一以
|
||||||
|
* Mockito {@code timeout()} 等待回调完成后再断言,与生产行为一致。
|
||||||
|
*/
|
||||||
|
class AuditFilterChainIntegrationTest {
|
||||||
|
|
||||||
|
/** doFinally 回调为响应式异步执行,断言等待上限(毫秒)。 */
|
||||||
|
private static final long CALLBACK_TIMEOUT_MS = 5_000;
|
||||||
|
|
||||||
|
private static final String LOGIN_FORM = "username=admin&password=right-password";
|
||||||
|
|
||||||
|
private AuditRecorder recorder;
|
||||||
|
private ChangeCaptureManager captureManager;
|
||||||
|
private HttpWriteMarker writeMarker;
|
||||||
|
private LoginFailureAlertService loginFailureAlertService;
|
||||||
|
private WebFilterChainProxy proxy;
|
||||||
|
|
||||||
|
/** 终止型外层 chain:模拟 Security 链之后的业务处理(正常 200 响应)。 */
|
||||||
|
private static final WebFilterChainStub OUTER_CHAIN = new WebFilterChainStub();
|
||||||
|
|
||||||
|
private static final class WebFilterChainStub implements WebFilterChain {
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange) {
|
||||||
|
exchange.getResponse().setStatusCode(HttpStatus.OK);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
recorder = mock(AuditRecorder.class);
|
||||||
|
captureManager = mock(ChangeCaptureManager.class);
|
||||||
|
writeMarker = mock(HttpWriteMarker.class);
|
||||||
|
loginFailureAlertService = mock(LoginFailureAlertService.class);
|
||||||
|
proxy = buildChain(csrf -> csrf.disable());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 Halo 真实组装方式构建过滤链代理。csrfCustomizer 由测试决定 CSRF 配置
|
||||||
|
* (禁用,或启用并指定仓库——用于验证表单参数通道)。
|
||||||
|
*/
|
||||||
|
private WebFilterChainProxy buildChain(
|
||||||
|
org.springframework.security.config.Customizer<ServerHttpSecurity.CsrfSpec> csrfCustomizer) {
|
||||||
|
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||||
|
any(ChangeCapture.class)))
|
||||||
|
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
||||||
|
|
||||||
|
var authEndpointFilter = new AuthEndpointAuditWebFilter(recorder, writeMarker,
|
||||||
|
new LoginAttemptCapture(), loginFailureAlertService);
|
||||||
|
var apisFilter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
|
||||||
|
|
||||||
|
// 表单登录认证管理器:right-password 成功,其余凭据失败(模拟 Halo 真实成败分流)
|
||||||
|
ReactiveAuthenticationManager authenticationManager = authentication -> {
|
||||||
|
var credentials = String.valueOf(authentication.getCredentials());
|
||||||
|
if ("right-password".equals(credentials)) {
|
||||||
|
var authenticated = UsernamePasswordAuthenticationToken.authenticated(
|
||||||
|
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||||
|
List.of(() -> "ROLE_ADMIN"));
|
||||||
|
return Mono.just(authenticated);
|
||||||
|
}
|
||||||
|
return Mono.error(new BadCredentialsException("invalid credential"));
|
||||||
|
};
|
||||||
|
|
||||||
|
var http = ServerHttpSecurity.http();
|
||||||
|
http.securityMatcher(ServerWebExchangeMatchers.anyExchange());
|
||||||
|
http.csrf(csrfCustomizer);
|
||||||
|
http.authorizeExchange(exchanges -> exchanges.anyExchange().permitAll());
|
||||||
|
// 模拟 ReactorContextWebFilter:认证后的请求向下游写入 SecurityContext,
|
||||||
|
// 使链尾过滤器可解析操作者(Halo 真实链由 ReactorContextWebFilter 完成)
|
||||||
|
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||||
|
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||||
|
List.of(() -> "ROLE_ADMIN"));
|
||||||
|
WebFilter contextFilter = (exchange, chain) -> chain.filter(exchange)
|
||||||
|
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
|
||||||
|
http.addFilterAt(contextFilter, SecurityWebFiltersOrder.AUTHENTICATION);
|
||||||
|
http.formLogin(login -> login
|
||||||
|
.authenticationManager(authenticationManager)
|
||||||
|
// 与 Halo 登录端点契约一致:表单登录成败均为 302 重定向
|
||||||
|
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/uc"))
|
||||||
|
.authenticationFailureHandler(new RedirectServerAuthenticationFailureHandler(
|
||||||
|
"/login?error=invalid-credential&method=local")));
|
||||||
|
http.logout(logout -> logout
|
||||||
|
.logoutHandler((exchange, auth) -> Mono.empty())
|
||||||
|
.logoutSuccessHandler((webFilterExchange, auth) -> {
|
||||||
|
var response = webFilterExchange.getExchange().getResponse();
|
||||||
|
response.setStatusCode(HttpStatus.FOUND);
|
||||||
|
response.getHeaders().setLocation(URI.create("/login?logout"));
|
||||||
|
return response.setComplete();
|
||||||
|
}));
|
||||||
|
// P0 修复核心:认证端点捕获过滤器位于链首,先于表单登录/登出终止过滤器
|
||||||
|
http.addFilterAt(authEndpointFilter, SecurityWebFiltersOrder.FIRST);
|
||||||
|
http.addFilterAt(apisFilter, SecurityWebFiltersOrder.LAST);
|
||||||
|
|
||||||
|
SecurityWebFilterChain securityChain = http.build();
|
||||||
|
return new WebFilterChainProxy(securityChain);
|
||||||
|
}
|
||||||
|
|
||||||
|
private MockServerWebExchange loginExchange(String password, String username) {
|
||||||
|
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
|
||||||
|
void shouldRecordFormLoginSuccessThroughRealChain() {
|
||||||
|
// P0 缺陷核心回归:POST /login 成功(表单登录过滤器直接 302 完成响应,
|
||||||
|
// 不向下游传递)仍必须产生审计记录
|
||||||
|
var exchange = loginExchange("right-password", "admin");
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
|
||||||
|
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
|
||||||
|
// 告警回调先于记录(同一回调体内),记录已到位则告警必然已回调
|
||||||
|
verify(loginFailureAlertService, timeout(CALLBACK_TIMEOUT_MS))
|
||||||
|
.onLoginResult(any(RequestSnapshot.class), eq(true), eq("admin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordFormLoginFailureThroughRealChain() {
|
||||||
|
var exchange = loginExchange("wrong", "admin");
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
|
||||||
|
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(true));
|
||||||
|
verify(loginFailureAlertService, timeout(CALLBACK_TIMEOUT_MS))
|
||||||
|
.onLoginResult(any(RequestSnapshot.class), eq(false), eq("admin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordLogoutThroughRealChain() {
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/logout")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
|
||||||
|
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||||
|
// 登出不是登录尝试:记录回调完成后告警仍零调用
|
||||||
|
verify(loginFailureAlertService, never())
|
||||||
|
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordLoginPageVisitExactlyOnceThroughRealChain() {
|
||||||
|
// GET /login 会流经全链(无终止过滤器命中):必须仅由链首过滤器记录一次,
|
||||||
|
// 链尾过滤器不得重复记录(两个过滤器按 CaptureRule 分治、互不重叠)
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.get("/login")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
|
||||||
|
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordApisWriteByLastPositionFilterWithAuthenticatedOperator() {
|
||||||
|
// /apis/** 捕获保持 AfterSecurityWebFilter(链尾)注册:操作者来自认证上下文
|
||||||
|
// (链尾过滤器经操作者独立订阅解析用户名,同样以 timeout 等待)
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
ArgumentCaptor<RequestSnapshot> captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(captor.capture(),
|
||||||
|
any(ChangeCapture.class), eq(200), eq("admin"), isNull(), eq(false));
|
||||||
|
assertThat(captor.getValue().getPath())
|
||||||
|
.isEqualTo("/apis/api.content.halo.run/v1alpha1/posts");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mustNotBreakCsrfFormParamChannelForLoginRequests() {
|
||||||
|
// 真实环境回归实证(登录保护):认证端点过滤器若缓存原始请求体并装饰 exchange,
|
||||||
|
// 下游 CSRF 过滤器经 getFormData() 代理到原始 exchange、解析已被消费的 body,
|
||||||
|
// 读不到 _csrf 表单参数而拒绝全部登录(403 Access Denied,登录页整体失效)。
|
||||||
|
// 修复后的提取走 getFormData() 共享缓存,本测试以启用 CSRF + 表单参数令牌的
|
||||||
|
// 真实链锁死该通道:CSRF 必须放行、表单登录必须继续执行。
|
||||||
|
var csrfToken = new org.springframework.security.web.server.csrf.DefaultCsrfToken(
|
||||||
|
"X-CSRF-TOKEN", "_csrf", "test-csrf-token");
|
||||||
|
var csrfProxy = buildChain(csrf -> csrf
|
||||||
|
// SS 7.1 默认 handler 为 XOR 解码(Halo 沿用默认,表单值即编码后的令牌);
|
||||||
|
// 本测试聚焦表单参数通道本身,改用原始值比较的 handler 以隔离编码因素
|
||||||
|
.csrfTokenRequestHandler(
|
||||||
|
new org.springframework.security.web.server.csrf.ServerCsrfTokenRequestAttributeHandler())
|
||||||
|
.csrfTokenRepository(new org.springframework.security.web.server.csrf.ServerCsrfTokenRepository() {
|
||||||
|
@Override
|
||||||
|
public Mono<org.springframework.security.web.server.csrf.CsrfToken> generateToken(
|
||||||
|
ServerWebExchange exchange) {
|
||||||
|
return Mono.just(csrfToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> saveToken(ServerWebExchange exchange,
|
||||||
|
org.springframework.security.web.server.csrf.CsrfToken token) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<org.springframework.security.web.server.csrf.CsrfToken> loadToken(
|
||||||
|
ServerWebExchange exchange) {
|
||||||
|
return Mono.just(csrfToken);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
var body = "username=admin&password=right-password&_csrf=test-csrf-token";
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/login")
|
||||||
|
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||||
|
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||||
|
.body(body));
|
||||||
|
|
||||||
|
csrfProxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
// CSRF 参数通道可用(未 403)且登录已执行:成功重定向
|
||||||
|
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
|
||||||
|
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordLogoutExactlyOnceThroughRealChain() {
|
||||||
|
// 认证端点移交链首过滤器后,链尾过滤器对认证端点零记录(分治不重叠):
|
||||||
|
// POST /logout 终止于 LOGOUT 过滤器,全链仅产生一条记录
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/logout")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||||
|
|
||||||
|
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
|
||||||
|
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-2
@@ -106,10 +106,30 @@ class AuditQueryEndpointTest {
|
|||||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||||
var condition = captor.getValue().toCondition().toString();
|
var condition = captor.getValue().toCondition().toString();
|
||||||
// failure = statusCode >= 400(无上界)
|
// failure = statusCode >= 400(无上界)或语义动作标注 login-failure
|
||||||
|
// (登录失败的 HTTP 状态码可能为 200/302)
|
||||||
assertThat(condition)
|
assertThat(condition)
|
||||||
.contains("spec.statusCode")
|
.contains("spec.statusCode")
|
||||||
.contains("400");
|
.contains("400")
|
||||||
|
.contains("spec.action")
|
||||||
|
.contains("login-failure");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldApplySuccessResultFilterExcludingLoginFailure() {
|
||||||
|
webClient.get()
|
||||||
|
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=success")
|
||||||
|
.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();
|
||||||
|
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
|
||||||
|
assertThat(condition)
|
||||||
|
.contains("spec.statusCode")
|
||||||
|
.contains("spec.action")
|
||||||
|
.contains("login-failure");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+59
-12
@@ -55,7 +55,7 @@ class AuditRecorderTest {
|
|||||||
.header("User-Agent", "UA-1")
|
.header("User-Agent", "UA-1")
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null);
|
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null, false);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
@@ -78,14 +78,15 @@ class AuditRecorderTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null);
|
// XHR/JSON 登录失败(401):过滤器判定 loginFailed=true,动作标注登录失败
|
||||||
|
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null, true);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
assertThat(captor.getValue().getSpec().getUsername())
|
assertThat(captor.getValue().getSpec().getUsername())
|
||||||
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
|
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
|
||||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
|
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login-failure");
|
||||||
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,21 +94,21 @@ class AuditRecorderTest {
|
|||||||
void shouldRecordAttemptedUsernameForLoginAttempt() {
|
void shouldRecordAttemptedUsernameForLoginAttempt() {
|
||||||
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
|
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
|
||||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
|
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
|
||||||
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan");
|
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan", true);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
var spec = captor.getValue().getSpec();
|
var spec = captor.getValue().getSpec();
|
||||||
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||||
assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan");
|
assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan");
|
||||||
assertThat(spec.getAction()).isEqualTo("login");
|
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldAnnotateSubActionSemanticAction() {
|
void shouldAnnotateSubActionSemanticAction() {
|
||||||
recorder.record(RequestSnapshot.of(MockServerHttpRequest
|
recorder.record(RequestSnapshot.of(MockServerHttpRequest
|
||||||
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
|
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
|
||||||
.build()), new ChangeCapture(), 200, "admin", null);
|
.build()), new ChangeCapture(), 200, "admin", null, false);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
@@ -115,13 +116,59 @@ class AuditRecorderTest {
|
|||||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts");
|
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 登录失败标注(LoginOutcome + 语义动作 login-failure) =====
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
|
||||||
|
// 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true,
|
||||||
|
// 语义动作标注 login-failure;状态码仍如实记录 302
|
||||||
|
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||||
|
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||||
|
|
||||||
|
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(302);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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);
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldKeepLoginActionOnSuccessfulLogin() {
|
||||||
|
// 表单登录成功(302 → /uc):语义动作仍为 login,不标注登录失败
|
||||||
|
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||||
|
AuditLogSpec.UNKNOWN_USERNAME, null, false);
|
||||||
|
|
||||||
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
|
verify(client).create(captor.capture());
|
||||||
|
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldSkipRecordingWhenAuditDisabled() {
|
void shouldSkipRecordingWhenAuditDisabled() {
|
||||||
when(settingProvider.get())
|
when(settingProvider.get())
|
||||||
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
|
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
|
||||||
|
|
||||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
||||||
200, "admin", null);
|
200, "admin", null, false);
|
||||||
|
|
||||||
verify(client, never()).create(any(AuditLog.class));
|
verify(client, never()).create(any(AuditLog.class));
|
||||||
}
|
}
|
||||||
@@ -131,7 +178,7 @@ class AuditRecorderTest {
|
|||||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||||
|
|
||||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||||
new ChangeCapture(), 200, "admin", null)).doesNotThrowAnyException();
|
new ChangeCapture(), 200, "admin", null, false)).doesNotThrowAnyException();
|
||||||
|
|
||||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||||
verify(client).create(any(AuditLog.class));
|
verify(client).create(any(AuditLog.class));
|
||||||
@@ -143,7 +190,7 @@ class AuditRecorderTest {
|
|||||||
new IllegalStateException("storage unavailable")));
|
new IllegalStateException("storage unavailable")));
|
||||||
|
|
||||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||||
new ChangeCapture(), 500, "admin", null)).doesNotThrowAnyException();
|
new ChangeCapture(), 500, "admin", null, false)).doesNotThrowAnyException();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -161,7 +208,7 @@ class AuditRecorderTest {
|
|||||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
recorder.record(snapshot, capture, 200, "admin", null);
|
recorder.record(snapshot, capture, 200, "admin", null, false);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
@@ -186,7 +233,7 @@ class AuditRecorderTest {
|
|||||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
recorder.record(snapshot, capture, 403, "admin", null);
|
recorder.record(snapshot, capture, 403, "admin", null, false);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
@@ -197,7 +244,7 @@ class AuditRecorderTest {
|
|||||||
@Test
|
@Test
|
||||||
void shouldNotRecordChangesWhenContextMissing() {
|
void shouldNotRecordChangesWhenContextMissing() {
|
||||||
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
||||||
new ChangeCapture(), 200, "admin", null);
|
new ChangeCapture(), 200, "admin", null, false);
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||||
verify(client).create(captor.capture());
|
verify(client).create(captor.capture());
|
||||||
|
|||||||
+195
@@ -0,0 +1,195 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
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.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||||
|
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
import org.springframework.web.server.WebFilterChain;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.test.StepVerifier;
|
||||||
|
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 认证端点捕获过滤器行为测试(P0 修复):POST /login、POST /logout 必须产生审计记录
|
||||||
|
* (真实环境中表单登录/登出过滤器在链尾过滤器之前直接完成响应,因此由本过滤器在
|
||||||
|
* Security 链之前承接)。操作者统一为未知用户,登录尝试账号由请求体白名单提取;
|
||||||
|
* 登录失败告警回调仅发生在 POST /login;非认证端点请求一律透传、零副作用。
|
||||||
|
*/
|
||||||
|
class AuthEndpointAuditWebFilterTest {
|
||||||
|
|
||||||
|
private AuditRecorder recorder;
|
||||||
|
private HttpWriteMarker writeMarker;
|
||||||
|
private LoginFailureAlertService loginFailureAlertService;
|
||||||
|
private AuthEndpointAuditWebFilter filter;
|
||||||
|
|
||||||
|
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||||
|
private static final WebFilterChainStub CHAIN = new WebFilterChainStub();
|
||||||
|
|
||||||
|
private static final class WebFilterChainStub implements WebFilterChain {
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange) {
|
||||||
|
exchange.getResponse().setStatusCode(HttpStatus.OK);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 终止型 chain:模拟 302 重定向响应(Halo 表单登录/登出契约)后完成。 */
|
||||||
|
private static final class RedirectWebFilterChainStub implements WebFilterChain {
|
||||||
|
private final URI location;
|
||||||
|
|
||||||
|
private RedirectWebFilterChainStub(URI location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange) {
|
||||||
|
exchange.getResponse().setStatusCode(HttpStatus.FOUND);
|
||||||
|
exchange.getResponse().getHeaders().setLocation(location);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
recorder = mock(AuditRecorder.class);
|
||||||
|
writeMarker = mock(HttpWriteMarker.class);
|
||||||
|
loginFailureAlertService = mock(LoginFailureAlertService.class);
|
||||||
|
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
|
||||||
|
filter = new AuthEndpointAuditWebFilter(recorder, writeMarker,
|
||||||
|
new LoginAttemptCapture(), loginFailureAlertService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordFormLoginSuccessWithAttemptedUsername() {
|
||||||
|
// P0 缺陷回归测试核心断言:POST /login 成功(302 → /uc)必须产生审计记录
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/login")
|
||||||
|
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||||
|
.contentLength("username=admin&password=secret".getBytes(StandardCharsets.UTF_8).length)
|
||||||
|
.body("username=admin&password=secret"));
|
||||||
|
|
||||||
|
StepVerifier.create(filter.filter(exchange,
|
||||||
|
new RedirectWebFilterChainStub(URI.create("/uc")))).verifyComplete();
|
||||||
|
|
||||||
|
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||||
|
verify(recorder).record(captor.capture(), isNull(), eq(302),
|
||||||
|
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
|
||||||
|
assertThat(captor.getValue().getPath()).isEqualTo("/login");
|
||||||
|
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true),
|
||||||
|
eq("admin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordFormLoginFailureAndAlert() {
|
||||||
|
// 表单登录失败:302 → /login?error=invalid-credential&method=local,
|
||||||
|
// 与成功重定向同状态码,必须按 Location 目标判定(LoginOutcome)
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/login")
|
||||||
|
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||||
|
.contentLength("username=bob&password=wrong".getBytes(StandardCharsets.UTF_8).length)
|
||||||
|
.body("username=bob&password=wrong"));
|
||||||
|
|
||||||
|
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
|
||||||
|
URI.create("/login?error=invalid-credential&method=local")))).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 shouldRecordLogoutWithoutAlert() {
|
||||||
|
// 登出请求必须产生记录(P0 缺陷回归),但不是登录尝试、不触发告警回调
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/logout")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
StepVerifier.create(filter.filter(exchange,
|
||||||
|
new RedirectWebFilterChainStub(URI.create("/login?logout")))).verifyComplete();
|
||||||
|
|
||||||
|
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
|
||||||
|
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||||
|
verify(loginFailureAlertService, never())
|
||||||
|
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordLoginPageVisitWithoutFailureMark() {
|
||||||
|
// 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.get("/login")
|
||||||
|
.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(loginFailureAlertService, never())
|
||||||
|
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRecordLoginPageErrorEchoAsLoginFailure() {
|
||||||
|
// 登录失败回显:GET /login?error=... 页面渲染 HTTP 200,标注登录失败,
|
||||||
|
// 但不是登录尝试、不触发告警
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.get("/login?error=invalid-credential&method=local")
|
||||||
|
.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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldMarkWriteLifecycleForAuthEndpoints() {
|
||||||
|
// 与原捕获分支行为对齐:认证端点请求登记 HTTP 写标记(内部变更归属)
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/login")
|
||||||
|
.build());
|
||||||
|
|
||||||
|
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
|
verify(writeMarker).onRequestStart(any());
|
||||||
|
verify(writeMarker).onRequestComplete(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldPassThroughNonAuthEndpointsWithoutSideEffects() {
|
||||||
|
// 非 /login、/logout 一律透传:不记录、不登记标记、不回调告警
|
||||||
|
var apis = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
||||||
|
.build());
|
||||||
|
StepVerifier.create(filter.filter(apis, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
|
var other = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.get("/console/")
|
||||||
|
.build());
|
||||||
|
StepVerifier.create(filter.filter(other, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-4
@@ -28,10 +28,12 @@ class CaptureRuleTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldCaptureAuthEndpointsRegardlessOfMethod() {
|
void shouldNotCaptureAuthEndpointsInApisRule() {
|
||||||
assertThat(shouldCapture("/login", "POST")).isTrue();
|
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 独立捕获(isAuthEndpoint),
|
||||||
assertThat(shouldCapture("/login", "GET")).isTrue();
|
// 通用规则不再包含,两个过滤器按规则分治、互不重叠
|
||||||
assertThat(shouldCapture("/logout", "POST")).isTrue();
|
assertThat(shouldCapture("/login", "POST")).isFalse();
|
||||||
|
assertThat(shouldCapture("/login", "GET")).isFalse();
|
||||||
|
assertThat(shouldCapture("/logout", "POST")).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+72
-44
@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||||
@@ -12,13 +13,14 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.test.StepVerifier;
|
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.test.StepVerifier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单体解析(成功/无 username/异常静默)、
|
* 登录尝试用户名提取测试(功能评审 P0-1):表单经 {@code getFormData()} 提取
|
||||||
* JSON 体提取、字段白名单(密码绝不提取)、请求体缓存后下游可重复读、
|
* (与下游 CSRF/登录转换器共享缓存解析结果,不消费原始 body——真实环境回归实证:
|
||||||
* 分块/超限/不支持形态降级为原 exchange。
|
* 缓存原始 body 会让下游 CSRF 读不到 _csrf 参数而拒绝登录)、JSON 体缓存提取、
|
||||||
|
* 字段白名单(密码绝不提取)、超长用户名不提取、不支持形态降级为原 exchange。
|
||||||
*/
|
*/
|
||||||
class LoginAttemptCaptureTest {
|
class LoginAttemptCaptureTest {
|
||||||
|
|
||||||
@@ -54,7 +56,7 @@ class LoginAttemptCaptureTest {
|
|||||||
return attempt;
|
return attempt;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 表单体解析 =====
|
// ===== 表单提取(经 getFormData 共享缓存,不消费原始 body) =====
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExtractUsernameFromFormBody() {
|
void shouldExtractUsernameFromFormBody() {
|
||||||
@@ -86,22 +88,64 @@ class LoginAttemptCaptureTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldFallbackToRawValueOnMalformedEncoding() {
|
void shouldNotTouchRawBodyForFormRequests() {
|
||||||
// 裸 % 等非法编码:解码失败回退原值,尽力提取且绝不抛出
|
// 表单形态绝不缓存原始 body / 装饰 exchange:prepare 后 exchange 原样透传,
|
||||||
var attempt = prepare(formExchange("username=bad%zz&password=x"));
|
// 下游(CSRF 过滤器、表单登录转换器)经同一份 getFormData 缓存读取表单
|
||||||
|
var exchange = formExchange("username=admin&password=secret");
|
||||||
|
|
||||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("bad%zz");
|
var attempt = new LoginAttempt();
|
||||||
|
var prepared = capture.prepare(exchange, attempt).block();
|
||||||
|
|
||||||
|
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||||
|
assertThat(prepared).isSameAs(exchange);
|
||||||
|
// 共享缓存可重复订阅:模拟下游 CSRF 过滤器与登录转换器先后读取
|
||||||
|
var first = exchange.getFormData().block();
|
||||||
|
var second = exchange.getFormData().block();
|
||||||
|
assertThat(first).isSameAs(second);
|
||||||
|
assertThat(first.getFirst("username")).isEqualTo("admin");
|
||||||
|
assertThat(first.getFirst("password")).isEqualTo("secret");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExtractSilentlyFromGarbageBody() {
|
void shouldExtractFromChunkedFormBody() {
|
||||||
// 解析异常静默:任何畸形输入都不抛出、不提取
|
// 分块传输(无 Content-Length):getFormData 为标准解析路径,正常提取
|
||||||
var attempt = prepare(formExchange("&&&"));
|
var request = MockServerHttpRequest.post("http://localhost/login")
|
||||||
|
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||||
|
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
||||||
|
.wrap("username=admin".getBytes(StandardCharsets.UTF_8))));
|
||||||
|
var exchange = MockServerWebExchange.from(request);
|
||||||
|
|
||||||
|
var attempt = new LoginAttempt();
|
||||||
|
var prepared = capture.prepare(exchange, attempt).block();
|
||||||
|
|
||||||
|
assertThat(prepared).isSameAs(exchange);
|
||||||
|
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldSkipOversizedUsernameValue() {
|
||||||
|
// 超长用户名视为扫描载荷:不提取(保证记录与告警负载卫生)
|
||||||
|
var longName = "a".repeat(LoginAttemptCapture.MAX_USERNAME_LENGTH + 1);
|
||||||
|
var attempt = prepare(formExchange("username=" + longName + "&password=x"));
|
||||||
|
|
||||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== JSON 体提取 =====
|
@Test
|
||||||
|
void shouldPassthroughEmptyFormBody() {
|
||||||
|
// 空表单体:getFormData 完成为空,defaultIfEmpty 兜底透传(prepare 永不为空)
|
||||||
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("http://localhost/login")
|
||||||
|
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
|
||||||
|
|
||||||
|
var attempt = new LoginAttempt();
|
||||||
|
var prepared = capture.prepare(exchange, attempt).block();
|
||||||
|
|
||||||
|
assertThat(prepared).isSameAs(exchange);
|
||||||
|
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== JSON 体提取(缓存原始 body,装饰后可重复读) =====
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExtractUsernameFromJsonBody() {
|
void shouldExtractUsernameFromJsonBody() {
|
||||||
@@ -117,18 +161,16 @@ class LoginAttemptCaptureTest {
|
|||||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 请求体缓存与下游可重复读 =====
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldKeepBodyReadableDownstream() {
|
void shouldKeepJsonBodyReadableDownstream() {
|
||||||
var body = "username=admin&password=secret";
|
var body = "{\"username\":\"admin\",\"password\":\"secret\"}";
|
||||||
var exchange = formExchange(body);
|
var exchange = jsonExchange(body);
|
||||||
|
|
||||||
var attempt = new LoginAttempt();
|
var attempt = new LoginAttempt();
|
||||||
var prepared = capture.prepare(exchange, attempt).block();
|
var prepared = capture.prepare(exchange, attempt).block();
|
||||||
|
|
||||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||||
// 装饰后的请求可重复读(每次订阅独立 buffer),登录处理可正常读取表单
|
// 装饰后的请求可重复读(每次订阅独立 buffer)
|
||||||
assertThat(prepared).isNotSameAs(exchange);
|
assertThat(prepared).isNotSameAs(exchange);
|
||||||
var first = prepared.getRequest().getBody()
|
var first = prepared.getRequest().getBody()
|
||||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||||
@@ -158,27 +200,12 @@ class LoginAttemptCaptureTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldPassthroughChunkedBodyWithoutContentLength() {
|
void shouldPassthroughOversizedJsonBody() {
|
||||||
var request = MockServerHttpRequest.post("http://localhost/login")
|
var oversized = "{\"username\":\"" + "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES)
|
||||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
+ "\"}";
|
||||||
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
|
||||||
.wrap("username=admin".getBytes(StandardCharsets.UTF_8))));
|
|
||||||
var exchange = MockServerWebExchange.from(request);
|
|
||||||
|
|
||||||
var attempt = new LoginAttempt();
|
|
||||||
var prepared = capture.prepare(exchange, attempt).block();
|
|
||||||
|
|
||||||
// 分块传输(无 Content-Length):不读请求体,避免中断流式请求
|
|
||||||
assertThat(prepared).isSameAs(exchange);
|
|
||||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldPassthroughOversizedBody() {
|
|
||||||
var oversized = "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES + 1);
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
.post("http://localhost/login")
|
.post("http://localhost/login")
|
||||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.contentLength(oversized.length())
|
.contentLength(oversized.length())
|
||||||
.body(oversized));
|
.body(oversized));
|
||||||
|
|
||||||
@@ -190,10 +217,10 @@ class LoginAttemptCaptureTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldPassthroughEmptyBody() {
|
void shouldPassthroughEmptyJsonBody() {
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
.post("http://localhost/login")
|
.post("http://localhost/login")
|
||||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
|
.contentType(MediaType.APPLICATION_JSON));
|
||||||
|
|
||||||
var attempt = new LoginAttempt();
|
var attempt = new LoginAttempt();
|
||||||
var prepared = capture.prepare(exchange, attempt).block();
|
var prepared = capture.prepare(exchange, attempt).block();
|
||||||
@@ -228,13 +255,14 @@ class LoginAttemptCaptureTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExtractLastUsernameWhenDuplicated() {
|
void shouldExtractLastUsernameWhenDuplicated() {
|
||||||
assertThat(LoginAttemptCapture.usernameOfForm("username=first&username=second"))
|
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of("first", "second")))
|
||||||
.isEqualTo("second");
|
.isEqualTo("second");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldReturnNullForBlankFormBody() {
|
void shouldReturnNullForMissingOrBlankFormValues() {
|
||||||
assertThat(LoginAttemptCapture.usernameOfForm(null)).isNull();
|
assertThat(LoginAttemptCapture.usernameOfFormValues(null)).isNull();
|
||||||
assertThat(LoginAttemptCapture.usernameOfForm(" ")).isNull();
|
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of())).isNull();
|
||||||
|
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of(" "))).isNull();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为
|
||||||
|
* 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON
|
||||||
|
* 请求以 200/401 区分成败,成败判定必须结合重定向目标。
|
||||||
|
*/
|
||||||
|
class LoginOutcomeTest {
|
||||||
|
|
||||||
|
// ===== POST /login:状态码 + 重定向目标 =====
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void xhrSuccessIsNotFailure() {
|
||||||
|
// XHR/JSON 登录成功:200 + 主体 JSON
|
||||||
|
assertThat(LoginOutcome.isFailure(200, null)).isFalse();
|
||||||
|
assertThat(LoginOutcome.isFailure(204, null)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void xhrFailureIsFailure() {
|
||||||
|
// XHR/JSON 登录失败:401 + JSON 错误体
|
||||||
|
assertThat(LoginOutcome.isFailure(401, null)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formSuccessRedirectIsNotFailure() {
|
||||||
|
// 表单登录成功:302 → /uc(无 error 参数)
|
||||||
|
assertThat(LoginOutcome.isFailure(302, URI.create("/uc"))).isFalse();
|
||||||
|
// 两步验证:302 → /challenges/two-factor/totp
|
||||||
|
assertThat(LoginOutcome.isFailure(302,
|
||||||
|
URI.create("/challenges/two-factor/totp"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formFailureRedirectWithErrorParamIsFailure() {
|
||||||
|
// 表单登录失败:302 → /login?error=invalid-credential&method=local
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void redirectWithoutLocationIsNotFailure() {
|
||||||
|
// 3xx 但缺失 Location(无法确认失败):按成功处理,不凭空判失败
|
||||||
|
assertThat(LoginOutcome.isFailure(302, null)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void missingOrZeroStatusIsFailure() {
|
||||||
|
// 状态码缺失(响应未写出)按失败处理,宁可多告警不漏报
|
||||||
|
assertThat(LoginOutcome.isFailure(null, null)).isTrue();
|
||||||
|
assertThat(LoginOutcome.isFailure(0, 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-136
@@ -2,19 +2,19 @@ package run.halo.operationaudit.audit;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.ArgumentMatchers.isNull;
|
import static org.mockito.ArgumentMatchers.isNull;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
@@ -23,21 +23,21 @@ import org.springframework.security.core.userdetails.User;
|
|||||||
import org.springframework.web.server.ServerWebExchange;
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
import reactor.test.StepVerifier;
|
import reactor.test.StepVerifier;
|
||||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
* {@code /apis/**} 捕获过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||||
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
||||||
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。
|
*
|
||||||
* 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。
|
* <p>认证端点({@code /login}、{@code /logout})不在本过滤器职责内(P0 修复:它们由
|
||||||
|
* {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,此处透传不记录),
|
||||||
|
* 其行为见 {@link AuthEndpointAuditWebFilterTest} 与过滤链集成测试。
|
||||||
*/
|
*/
|
||||||
class OperationAuditWebFilterTest {
|
class OperationAuditWebFilterTest {
|
||||||
|
|
||||||
private AuditRecorder recorder;
|
private AuditRecorder recorder;
|
||||||
private ChangeCaptureManager captureManager;
|
private ChangeCaptureManager captureManager;
|
||||||
private HttpWriteMarker writeMarker;
|
private HttpWriteMarker writeMarker;
|
||||||
private LoginFailureAlertService loginFailureAlertService;
|
|
||||||
private OperationAuditWebFilter filter;
|
private OperationAuditWebFilter filter;
|
||||||
|
|
||||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||||
@@ -52,34 +52,15 @@ class OperationAuditWebFilterTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 终止型 chain:模拟异常响应(指定状态码)后完成。 */
|
|
||||||
private static final class FailingWebFilterChainStub implements
|
|
||||||
org.springframework.web.server.WebFilterChain {
|
|
||||||
private final org.springframework.http.HttpStatus status;
|
|
||||||
|
|
||||||
private FailingWebFilterChainStub(org.springframework.http.HttpStatus status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange) {
|
|
||||||
exchange.getResponse().setStatusCode(status);
|
|
||||||
return Mono.empty();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
recorder = mock(AuditRecorder.class);
|
recorder = mock(AuditRecorder.class);
|
||||||
captureManager = mock(ChangeCaptureManager.class);
|
captureManager = mock(ChangeCaptureManager.class);
|
||||||
writeMarker = mock(HttpWriteMarker.class);
|
writeMarker = mock(HttpWriteMarker.class);
|
||||||
loginFailureAlertService = mock(LoginFailureAlertService.class);
|
|
||||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||||
any(ChangeCapture.class)))
|
any(ChangeCapture.class)))
|
||||||
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
||||||
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
|
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
|
||||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker,
|
|
||||||
new LoginAttemptCapture(), loginFailureAlertService);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -97,7 +78,7 @@ class OperationAuditWebFilterTest {
|
|||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
|
|
||||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||||
eq("admin"), isNull());
|
eq("admin"), isNull(), eq(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -108,38 +89,27 @@ class OperationAuditWebFilterTest {
|
|||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldRecordLoginFailureAsUnknownUser() {
|
void shouldPassThroughAuthEndpointsWithoutRecording() {
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 在 Security 链之前捕获,
|
||||||
|
// 本过滤器不再记录;写方法请求(POST /login、POST /logout)仍按统一语义
|
||||||
|
// 登记内部变更归属标记(真实链上 POST 请求到不了链尾,GET 由透传处理)
|
||||||
|
var login = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
.post("/login")
|
.post("/login")
|
||||||
.build());
|
.build());
|
||||||
|
StepVerifier.create(filter.filter(login, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
var logout = MockServerWebExchange.from(MockServerHttpRequest
|
||||||
|
.post("/logout")
|
||||||
|
.build());
|
||||||
|
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录
|
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
verify(writeMarker, times(2)).onRequestStart(any());
|
||||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull());
|
verify(writeMarker, times(2)).onRequestComplete(any());
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldRecordAndAlertAttemptedUsernameOnLoginAttempt() {
|
|
||||||
// 登录尝试用户名(功能评审 P0-1):表单体中的 username 白名单提取,
|
|
||||||
// 随告警回调与审计记录透传;密码等其余字段绝不提取
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/login")
|
|
||||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
|
||||||
.contentLength("username=admin&password=secret".getBytes(StandardCharsets.UTF_8).length)
|
|
||||||
.body("username=admin&password=secret"));
|
|
||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
|
||||||
|
|
||||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
|
||||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"));
|
|
||||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
|
|
||||||
eq("admin"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -151,7 +121,7 @@ class OperationAuditWebFilterTest {
|
|||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||||
|
|
||||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -168,28 +138,7 @@ class OperationAuditWebFilterTest {
|
|||||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
|
|
||||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldCaptureLogoutAsAuth() {
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/logout")
|
|
||||||
.build());
|
|
||||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
|
||||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
|
||||||
List.of(() -> "ROLE_ADMIN"));
|
|
||||||
|
|
||||||
StepVerifier.create(
|
|
||||||
filter.filter(exchange, CHAIN)
|
|
||||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
|
||||||
.verifyComplete();
|
|
||||||
|
|
||||||
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
|
||||||
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"),
|
|
||||||
isNull());
|
|
||||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
|
||||||
.isEqualTo("auth");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -219,7 +168,7 @@ class OperationAuditWebFilterTest {
|
|||||||
|
|
||||||
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
||||||
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
||||||
eq("admin"), isNull());
|
eq("admin"), isNull(), eq(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -246,7 +195,7 @@ class OperationAuditWebFilterTest {
|
|||||||
|
|
||||||
verify(writeMarker).onRequestStart(any());
|
verify(writeMarker).onRequestStart(any());
|
||||||
verify(writeMarker).onRequestComplete(any());
|
verify(writeMarker).onRequestComplete(any());
|
||||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -260,62 +209,4 @@ class OperationAuditWebFilterTest {
|
|||||||
verify(writeMarker, never()).onRequestStart(any());
|
verify(writeMarker, never()).onRequestStart(any());
|
||||||
verify(writeMarker, never()).onRequestComplete(any());
|
verify(writeMarker, never()).onRequestComplete(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 登录失败告警(产品设计 V2「告警通知」) =====
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldNotifyLoginResultOnLoginAttempt() {
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/login")
|
|
||||||
.build());
|
|
||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
|
||||||
|
|
||||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
|
|
||||||
isNull());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldNotifyLoginFailureStatusOnFailedLogin() {
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/login")
|
|
||||||
.build());
|
|
||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange,
|
|
||||||
new FailingWebFilterChainStub(org.springframework.http.HttpStatus.UNAUTHORIZED)))
|
|
||||||
.verifyComplete();
|
|
||||||
|
|
||||||
// 非常响应(401)同样回调,由告警服务按失败累计
|
|
||||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401),
|
|
||||||
isNull());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldNotNotifyLoginResultForLoginPageOrLogout() {
|
|
||||||
// 登录页 GET 与登出不是登录尝试
|
|
||||||
var loginPage = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.get("/login")
|
|
||||||
.build());
|
|
||||||
StepVerifier.create(filter.filter(loginPage, CHAIN)).verifyComplete();
|
|
||||||
|
|
||||||
var logout = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/logout")
|
|
||||||
.build());
|
|
||||||
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
|
|
||||||
|
|
||||||
verify(loginFailureAlertService, never())
|
|
||||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void shouldNotNotifyLoginResultForApisRequests() {
|
|
||||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
|
||||||
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
|
||||||
.build());
|
|
||||||
|
|
||||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
|
||||||
|
|
||||||
verify(loginFailureAlertService, never())
|
|
||||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+29
@@ -197,6 +197,9 @@ class OperationDescriptionTest {
|
|||||||
@Test
|
@Test
|
||||||
void shouldDescribeFromActionKey() {
|
void shouldDescribeFromActionKey() {
|
||||||
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
||||||
|
// 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显)
|
||||||
|
assertThat(OperationDescription.describeAction("login-failure", "auth"))
|
||||||
|
.isEqualTo("登录失败");
|
||||||
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
||||||
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
||||||
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
||||||
@@ -215,4 +218,30 @@ class OperationDescriptionTest {
|
|||||||
assertThat(OperationDescription.describeAction(null, "posts")).isNull();
|
assertThat(OperationDescription.describeAction(null, "posts")).isNull();
|
||||||
assertThat(OperationDescription.describeAction("bogus", "posts")).isNull();
|
assertThat(OperationDescription.describeAction("bogus", "posts")).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldDescribeSpecPreferingStoredAction() {
|
||||||
|
// 落库语义动作优先:登录失败标注(回显页 HTTP 200 无法由路径重新推导出失败)
|
||||||
|
var spec = new AuditLogSpec();
|
||||||
|
spec.setMethod("GET");
|
||||||
|
spec.setResourceType("auth");
|
||||||
|
spec.setPath("/login?error=invalid-credential&method=local");
|
||||||
|
spec.setAction("login-failure");
|
||||||
|
assertThat(OperationDescription.describe(spec)).isEqualTo("登录失败");
|
||||||
|
|
||||||
|
// 无标注(历史记录)回退 method/path 现场推导
|
||||||
|
var legacy = new AuditLogSpec();
|
||||||
|
legacy.setMethod("POST");
|
||||||
|
legacy.setResourceType("auth");
|
||||||
|
legacy.setPath("/login");
|
||||||
|
assertThat(OperationDescription.describe(legacy)).isEqualTo("登录");
|
||||||
|
|
||||||
|
// 落库标注未识别时同样回退现场推导
|
||||||
|
var bogus = new AuditLogSpec();
|
||||||
|
bogus.setMethod("PUT");
|
||||||
|
bogus.setResourceType("posts");
|
||||||
|
bogus.setPath("/apis/content.halo.run/v1alpha1/posts/abc");
|
||||||
|
bogus.setAction("bogus");
|
||||||
|
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import {
|
|||||||
deriveAction,
|
deriveAction,
|
||||||
describeOperation,
|
describeOperation,
|
||||||
displayUsername,
|
displayUsername,
|
||||||
|
isLoginFailure,
|
||||||
|
resultBadge,
|
||||||
SEMANTIC_ACTIONS,
|
SEMANTIC_ACTIONS,
|
||||||
SYSTEM_USERNAME,
|
SYSTEM_USERNAME,
|
||||||
UNKNOWN_USERNAME,
|
UNKNOWN_USERNAME,
|
||||||
@@ -153,6 +155,19 @@ describe('deriveAction 语义动作推导', () => {
|
|||||||
expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth')
|
expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('登录失败回显(GET /login?error=...)推导为 login-failure', () => {
|
||||||
|
// 登录失败后 Halo 重定向到带 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?errors=1')).toBe('login')
|
||||||
|
})
|
||||||
|
|
||||||
it('子动作段优先于 HTTP 方法', () => {
|
it('子动作段优先于 HTTP 方法', () => {
|
||||||
expect(deriveAction('PUT', 'posts',
|
expect(deriveAction('PUT', 'posts',
|
||||||
'/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish')).toBe('publish')
|
'/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish')).toBe('publish')
|
||||||
@@ -219,6 +234,101 @@ describe('describeOperation 落库标注优先', () => {
|
|||||||
action: 'bogus',
|
action: 'bogus',
|
||||||
}))).toBe('修改文章')
|
}))).toBe('修改文章')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('登录失败标注(login-failure)描述为 登录失败', () => {
|
||||||
|
// 表单登录失败(POST /login,302)与失败回显页(GET /login?error=...,200)
|
||||||
|
// 均落库标注,描述为 登录失败 而非按路径推导出的 登录
|
||||||
|
expect(describeOperation(spec({
|
||||||
|
method: 'POST',
|
||||||
|
resourceType: 'auth',
|
||||||
|
path: '/login',
|
||||||
|
action: 'login-failure',
|
||||||
|
}))).toBe('登录失败')
|
||||||
|
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('登录失败')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('isLoginFailure / resultBadge 登录失败结果展示', () => {
|
||||||
|
it('落库标注 login-failure 判定为登录失败(HTTP 200/302 也可能是失败)', () => {
|
||||||
|
expect(isLoginFailure(spec({
|
||||||
|
method: 'POST',
|
||||||
|
resourceType: 'auth',
|
||||||
|
path: '/login',
|
||||||
|
statusCode: 302,
|
||||||
|
action: 'login-failure',
|
||||||
|
}))).toBe(true)
|
||||||
|
expect(isLoginFailure(spec({
|
||||||
|
method: 'GET',
|
||||||
|
resourceType: 'auth',
|
||||||
|
path: '/login?error=invalid-credential&method=local',
|
||||||
|
statusCode: 200,
|
||||||
|
action: 'login-failure',
|
||||||
|
}))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
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('登录失败记录结果徽标为红色 失败(不显示裸状态码)', () => {
|
||||||
|
// 失败回显页 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('非登录记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||||
|
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' })
|
||||||
|
expect(resultBadge(spec({ statusCode: 500 }))).toEqual({ text: '500', class: 'status-fail' })
|
||||||
|
expect(resultBadge(spec({ statusCode: undefined })))
|
||||||
|
.toEqual({ text: 'undefined', class: 'status-fail' })
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
||||||
@@ -231,9 +341,9 @@ describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('覆盖全部可落库的语义动作键(view 不会被捕获规则记录,除外)', () => {
|
it('覆盖全部可落库的语义动作键(view 不会被捕获规则记录,除外)', () => {
|
||||||
// 全量枚举:登录/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并)
|
// 全量枚举:登录/登录失败/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并)
|
||||||
const storable = new Set([
|
const storable = new Set([
|
||||||
'login', 'logout', 'auth',
|
'login', 'login-failure', 'logout', 'auth',
|
||||||
'create', 'update', 'delete',
|
'create', 'update', 'delete',
|
||||||
'publish', 'unpublish', 'recycle', 'restore', 'enable', 'disable',
|
'publish', 'unpublish', 'recycle', 'restore', 'enable', 'disable',
|
||||||
'upgrade', 'uninstall', 'reload', 'reply', 'recalculate',
|
'upgrade', 'uninstall', 'reload', 'reply', 'recalculate',
|
||||||
|
|||||||
@@ -104,9 +104,13 @@ const SEGMENT_ACTIONS: Record<string, string> = {
|
|||||||
resetpassword: 'resetpassword',
|
resetpassword: 'resetpassword',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 登录失败语义动作键(与后端 OperationDescription.LOGIN_FAILURE_ACTION 同步)。 */
|
||||||
|
const LOGIN_FAILURE_ACTION = 'login-failure'
|
||||||
|
|
||||||
/** 语义动作键 → 完整短语(不拼资源名)。 */
|
/** 语义动作键 → 完整短语(不拼资源名)。 */
|
||||||
const ACTION_PHRASES: Record<string, string> = {
|
const ACTION_PHRASES: Record<string, string> = {
|
||||||
login: '登录',
|
login: '登录',
|
||||||
|
[LOGIN_FAILURE_ACTION]: '登录失败',
|
||||||
logout: '登出',
|
logout: '登出',
|
||||||
auth: '认证操作',
|
auth: '认证操作',
|
||||||
password: '修改密码',
|
password: '修改密码',
|
||||||
@@ -138,6 +142,7 @@ const ACTION_VERBS: Record<string, string> = {
|
|||||||
*/
|
*/
|
||||||
export const SEMANTIC_ACTIONS: Array<{ value: string; label: string }> = [
|
export const SEMANTIC_ACTIONS: Array<{ value: string; label: string }> = [
|
||||||
{ value: 'login', label: '登录' },
|
{ value: 'login', label: '登录' },
|
||||||
|
{ value: 'login-failure', label: '登录失败' },
|
||||||
{ value: 'logout', label: '登出' },
|
{ value: 'logout', label: '登出' },
|
||||||
{ value: 'auth', label: '认证操作' },
|
{ value: 'auth', label: '认证操作' },
|
||||||
{ value: 'create', label: '新建' },
|
{ value: 'create', label: '新建' },
|
||||||
@@ -167,10 +172,32 @@ function pathWithoutQuery(path?: string | null): string {
|
|||||||
return queryStart >= 0 ? path.slice(0, queryStart) : path
|
return queryStart >= 0 ? path.slice(0, queryStart) : path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询串是否含 error 参数(可为无值形式 error)。
|
||||||
|
* 登录失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||||
|
*/
|
||||||
|
function hasErrorParam(path?: string | null): boolean {
|
||||||
|
if (!path) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const queryStart = path.indexOf('?')
|
||||||
|
if (queryStart < 0) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
.slice(queryStart + 1)
|
||||||
|
.split('&')
|
||||||
|
.some((pair) => (pair.indexOf('=') < 0 ? pair : pair.slice(0, pair.indexOf('='))) === 'error')
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致):
|
* 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致):
|
||||||
* 登录/登出/认证操作由路径判定,子动作段优先于 HTTP 方法,其余方法归为
|
* 登录/登录失败/登出/认证操作由路径判定(GET /login?error=... 为登录失败回显),
|
||||||
* create/update/delete/view;无法识别返回 null。
|
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||||
|
* 无法识别返回 null。
|
||||||
|
*
|
||||||
|
* <p>历史局限:升级前落库的表单登录失败记录(POST /login,302)无法由路径重新
|
||||||
|
* 推导出失败,仍推导为 login;仅回显页(GET,error 参数在路径中)可现场推导。
|
||||||
*/
|
*/
|
||||||
export function deriveAction(
|
export function deriveAction(
|
||||||
method: string,
|
method: string,
|
||||||
@@ -179,7 +206,7 @@ export function deriveAction(
|
|||||||
): string | null {
|
): string | null {
|
||||||
const cleanPath = pathWithoutQuery(path)
|
const cleanPath = pathWithoutQuery(path)
|
||||||
if (cleanPath === '/login') {
|
if (cleanPath === '/login') {
|
||||||
return 'login'
|
return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login'
|
||||||
}
|
}
|
||||||
if (cleanPath === '/logout') {
|
if (cleanPath === '/logout') {
|
||||||
return 'logout'
|
return 'logout'
|
||||||
@@ -250,6 +277,39 @@ export function isSuccessful(statusCode?: number | null): boolean {
|
|||||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 结果徽标展示形态:文本与配色 class。 */
|
||||||
|
export interface ResultBadge {
|
||||||
|
text: string
|
||||||
|
class: 'status-ok' | 'status-fail'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结果列徽标(列表/详情共用):登录失败记录(语义动作 login-failure,HTTP 状态码可能
|
||||||
|
* 为 200/302——失败回显页渲染/表单登录失败重定向)显示「失败」而非裸状态码,避免
|
||||||
|
* 绿色 200/302 误读为登录成功;其余记录保持原状——按 HTTP 状态码展示
|
||||||
|
* (2xx/3xx 绿、其余红),与既有行为一致。
|
||||||
|
*/
|
||||||
|
export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||||
|
| 'action' | 'statusCode'>): ResultBadge {
|
||||||
|
if (isLoginFailure(spec)) {
|
||||||
|
return { text: '失败', class: 'status-fail' }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
text: String(spec.statusCode),
|
||||||
|
class: isSuccessful(spec.statusCode) ? 'status-ok' : 'status-fail',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否为登录失败记录:优先落库语义动作标注(spec.action,POST /login 失败与
|
||||||
|
* 失败回显均落库),历史记录回退由路径现场推导(仅回显页可推导)。
|
||||||
|
*/
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
||||||
const CHANGE_TYPE_LABELS: Record<string, string> = {
|
const CHANGE_TYPE_LABELS: Record<string, string> = {
|
||||||
ADDED: '新增',
|
ADDED: '新增',
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
describeOperation,
|
describeOperation,
|
||||||
displayUsername,
|
displayUsername,
|
||||||
formatTime,
|
formatTime,
|
||||||
|
isLoginFailure,
|
||||||
isSuccessful,
|
isSuccessful,
|
||||||
methodBadgeClass,
|
methodBadgeClass,
|
||||||
} from '@/utils/audit'
|
} from '@/utils/audit'
|
||||||
@@ -23,13 +24,28 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const close = () => emit('update:visible', false)
|
const close = () => emit('update:visible', false)
|
||||||
|
|
||||||
|
// 结果语义:登录失败记录(HTTP 状态码可能为 200/302)显示「登录失败」,
|
||||||
|
// 其余按 HTTP 状态码判定成败
|
||||||
const resultText = computed(() => {
|
const resultText = computed(() => {
|
||||||
if (!props.log) {
|
if (!props.log) {
|
||||||
return '-'
|
return '-'
|
||||||
}
|
}
|
||||||
|
if (isLoginFailure(props.log.spec)) {
|
||||||
|
return '登录失败'
|
||||||
|
}
|
||||||
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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'
|
||||||
|
})
|
||||||
|
|
||||||
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
||||||
const changes = computed(() => props.log?.spec.changes ?? [])
|
const changes = computed(() => props.log?.spec.changes ?? [])
|
||||||
|
|
||||||
@@ -105,10 +121,7 @@ const rawJson = computed(() =>
|
|||||||
<div class="detail-row">
|
<div class="detail-row">
|
||||||
<dt>结果</dt>
|
<dt>结果</dt>
|
||||||
<dd>
|
<dd>
|
||||||
<span
|
<span class="status-badge" :class="resultBadgeClass">
|
||||||
class="status-badge"
|
|
||||||
:class="isSuccessful(log.spec.statusCode) ? 'status-ok' : 'status-fail'"
|
|
||||||
>
|
|
||||||
{{ resultText }} · {{ log.spec.statusCode }}
|
{{ resultText }} · {{ log.spec.statusCode }}
|
||||||
</span>
|
</span>
|
||||||
</dd>
|
</dd>
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
// 移动端适配结构性回归测试:不渲染组件,仅检查 SFC 源码。
|
||||||
|
// 固定列宽列表合计约 69.5rem,窄屏(≤1023px:手机横竖屏 / 平板竖屏 / 半屏小窗口)
|
||||||
|
// 下必然超出视口:题头与数据行置于同一横向滚动容器(.audit-list)整体左右滑动,
|
||||||
|
// 列对齐关系与桌面一致;筛选栏窄屏 2 列(≤480px 手机竖屏单列)、分页条允许换行;
|
||||||
|
// ≥1024px 维持桌面布局不变。
|
||||||
|
// 特别注意:VEntity 是多根 Fragment 组件(tr + 可选 footer tr),其 <tr> 拿不到
|
||||||
|
// 本组件的 scoped 作用域 ID,所有锚定 .audit-row / 行内元素 :deep 的 scoped 规则
|
||||||
|
// 永远失配(历史上「隐藏题头 + 数据行纵向堆叠」方案因此整批失效——窄屏下字段
|
||||||
|
// 仍按固定列宽横排并被视口截断),行内样式必须锚定自身元素 .audit-list 穿透,
|
||||||
|
// 本测试防止该失效方案被重新引入。
|
||||||
|
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
|
||||||
|
|
||||||
|
const MOBILE_QUERY = '@media (max-width: 1023px)'
|
||||||
|
|
||||||
|
/** 提取 max-width: 1023px 媒体查询块全文(大括号配平)。 */
|
||||||
|
function mobileBlock(): string {
|
||||||
|
const start = sfc.indexOf(MOBILE_QUERY)
|
||||||
|
expect(start, `缺少 ${MOBILE_QUERY} 媒体查询`).toBeGreaterThan(-1)
|
||||||
|
let depth = 0
|
||||||
|
let end = -1
|
||||||
|
for (let i = sfc.indexOf('{', start); i < sfc.length; i++) {
|
||||||
|
if (sfc[i] === '{') depth++
|
||||||
|
else if (sfc[i] === '}') {
|
||||||
|
depth--
|
||||||
|
if (depth === 0) {
|
||||||
|
end = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sfc.slice(start, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在指定文本块内取某选择器的规则体(自 from 起首个匹配)。 */
|
||||||
|
function ruleIn(block: string, selector: string, from = 0): string {
|
||||||
|
const start = block.indexOf(`${selector} {`, from)
|
||||||
|
expect(start, `块中缺少 ${selector} 规则`).toBeGreaterThan(-1)
|
||||||
|
const end = block.indexOf('}', start)
|
||||||
|
return block.slice(start, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取全局(非媒体查询)样式中某选择器的规则体。 */
|
||||||
|
function styleRule(selector: string): string {
|
||||||
|
const start = sfc.indexOf(`${selector} {`)
|
||||||
|
expect(start, `缺少 ${selector} 样式规则`).toBeGreaterThan(-1)
|
||||||
|
const end = sfc.indexOf('}', start)
|
||||||
|
return sfc.slice(start, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AuditLogList 移动端适配', () => {
|
||||||
|
it('存在 ≤1023px 窄屏断点,且位于桌面规则之后(同特异性按顺序覆盖才生效)', () => {
|
||||||
|
const mediaStart = sfc.indexOf(MOBILE_QUERY)
|
||||||
|
const desktopGrid = sfc.indexOf('.filter-grid {')
|
||||||
|
expect(desktopGrid).toBeGreaterThan(-1)
|
||||||
|
expect(mediaStart).toBeGreaterThan(desktopGrid)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('窄屏筛选栏改为 2 列,操作按钮独占整行并拉伸铺满', () => {
|
||||||
|
const grid = ruleIn(mobileBlock(), '.filter-grid')
|
||||||
|
expect(grid).toMatch(/grid-template-columns:\s*repeat\(2,\s*minmax\(0,\s*1fr\)\)/)
|
||||||
|
const actions = ruleIn(mobileBlock(), '.filter-actions')
|
||||||
|
expect(actions).toMatch(/grid-column:\s*1\s*\/\s*-1/)
|
||||||
|
const stretch = ruleIn(mobileBlock(), '.filter-actions > :deep(*)')
|
||||||
|
expect(stretch).toMatch(/flex:\s*1/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('手机竖屏(≤480px)筛选栏单列,datetime-local 不被压扁', () => {
|
||||||
|
const start = sfc.indexOf('@media (max-width: 480px)')
|
||||||
|
expect(start, '缺少 ≤480px 单列断点').toBeGreaterThan(-1)
|
||||||
|
expect(sfc.slice(start)).toMatch(
|
||||||
|
/grid-template-columns:\s*minmax\(0,\s*1fr\)/,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('题头与数据行置于同一横向滚动容器(.audit-list overflow-x: auto)', () => {
|
||||||
|
// 模板顺序:.audit-list 包裹 .audit-header 与全部 VEntity 数据行,
|
||||||
|
// 滑动时题头与数据列保持对齐
|
||||||
|
const listStart = sfc.indexOf('<div class="audit-list">')
|
||||||
|
expect(listStart, '缺少 .audit-list 滚动容器').toBeGreaterThan(-1)
|
||||||
|
const headerStart = sfc.indexOf('<div class="audit-header">')
|
||||||
|
const entityStart = sfc.indexOf('<VEntity')
|
||||||
|
const listEnd = sfc.indexOf('</div>\n </template>', listStart)
|
||||||
|
expect(headerStart).toBeGreaterThan(listStart)
|
||||||
|
expect(entityStart).toBeGreaterThan(headerStart)
|
||||||
|
expect(listEnd).toBeGreaterThan(entityStart)
|
||||||
|
const rule = styleRule('.audit-list')
|
||||||
|
expect(rule).toMatch(/overflow-x:\s*auto/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('窄屏不隐藏列题头(题头随容器滑动,列对齐关系不变)', () => {
|
||||||
|
// 历史方案曾在窄屏 display: none 隐藏题头,导致用户失去列语义,防止回归
|
||||||
|
const headerRule = styleRule('.audit-header')
|
||||||
|
expect(headerRule).not.toMatch(/display:\s*none/)
|
||||||
|
expect(mobileBlock()).not.toContain('.audit-header')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('题头在滚动容器内随内容延伸且列宽不收缩(滑动后下划线不断裂、不与数据列错位)', () => {
|
||||||
|
const header = styleRule('.audit-header')
|
||||||
|
expect(header).toMatch(/min-width:\s*max-content/)
|
||||||
|
const col = styleRule('.header-col')
|
||||||
|
expect(col).toMatch(/flex-shrink:\s*0/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('数据行保持固定列宽表格形态,无失效的行内堆叠样式', () => {
|
||||||
|
// VEntity 的 <tr> 拿不到本组件 scoped 作用域 ID,锚定 .audit-row 的规则永远失配;
|
||||||
|
// 窄屏块内不得出现任何 entity 行内 :deep 规则,全文件不得再有 .audit-row 选择器
|
||||||
|
// (选择器须位于行首或上一规则之后,注释中的历史说明不受限)
|
||||||
|
expect(mobileBlock()).not.toContain('entity-')
|
||||||
|
expect(sfc).not.toMatch(/(?:^|[},;])\s*\.audit-row[\s:{]/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('行悬停手型经自身元素 .audit-list 穿透到 VEntity 行', () => {
|
||||||
|
const rule = styleRule('.audit-list :deep(.entity-wrapper)')
|
||||||
|
expect(rule).toMatch(/cursor:\s*pointer/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('窄屏分页条允许换行(总数与翻页控制器不横向溢出)', () => {
|
||||||
|
const rule = ruleIn(
|
||||||
|
mobileBlock(),
|
||||||
|
'.audit-pagination :deep(.pagination),\n .audit-pagination :deep(.pagination__controller)',
|
||||||
|
)
|
||||||
|
expect(rule).toMatch(/flex-wrap:\s*wrap/)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -24,9 +24,9 @@ import {
|
|||||||
describeOperation,
|
describeOperation,
|
||||||
displayUsername,
|
displayUsername,
|
||||||
formatTime,
|
formatTime,
|
||||||
isSuccessful,
|
|
||||||
localDateTimeToInstant,
|
localDateTimeToInstant,
|
||||||
methodBadgeClass,
|
methodBadgeClass,
|
||||||
|
resultBadge,
|
||||||
SEMANTIC_ACTIONS,
|
SEMANTIC_ACTIONS,
|
||||||
} from '@/utils/audit'
|
} from '@/utils/audit'
|
||||||
import AuditLogDetail from './AuditLogDetail.vue'
|
import AuditLogDetail from './AuditLogDetail.vue'
|
||||||
@@ -322,6 +322,12 @@ onMounted(fetchLogs)
|
|||||||
</template>
|
</template>
|
||||||
</VEmpty>
|
</VEmpty>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
|
<!-- 题头与数据行置于同一横向滚动容器:固定列宽合计约 69.5rem,
|
||||||
|
容器窄于列表(手机/竖屏平板/半屏窗口)时整体左右滑动看全六列,
|
||||||
|
列对齐关系与桌面完全一致;容器够宽时无溢出、无滚动条,桌面观感不变。
|
||||||
|
:deep 规则须锚定此容器(本组件自己的元素)才能穿透到 VEntity 行内,
|
||||||
|
VEntity 是多根 Fragment 组件,其 <tr> 拿不到本组件的 scoped 作用域 ID -->
|
||||||
|
<div class="audit-list">
|
||||||
<!-- 列题头:分组结构与内边距镜像 entity 行的两个 td,列宽与各 VEntityField 的 width 一一对应 -->
|
<!-- 列题头:分组结构与内边距镜像 entity 行的两个 td,列宽与各 VEntityField 的 width 一一对应 -->
|
||||||
<div class="audit-header">
|
<div class="audit-header">
|
||||||
<div class="header-start">
|
<div class="header-start">
|
||||||
@@ -338,7 +344,6 @@ onMounted(fetchLogs)
|
|||||||
<VEntity
|
<VEntity
|
||||||
v-for="log in logs"
|
v-for="log in logs"
|
||||||
:key="log.metadata.name"
|
:key="log.metadata.name"
|
||||||
class="audit-row"
|
|
||||||
@click="openDetail(log)"
|
@click="openDetail(log)"
|
||||||
>
|
>
|
||||||
<template #start>
|
<template #start>
|
||||||
@@ -382,21 +387,21 @@ onMounted(fetchLogs)
|
|||||||
</VEntityField>
|
</VEntityField>
|
||||||
</template>
|
</template>
|
||||||
<template #end>
|
<template #end>
|
||||||
<!-- 结果列:徽标经 #title 插槽渲染(当前版本组件在无 title 时
|
<!-- 结果列:登录失败记录(HTTP 200/302 也可能是失败,语义动作已标注)
|
||||||
不渲染 #extra,原先徽标实际不可见) -->
|
显示红色「失败」,避免绿色 200/302 误读为登录成功;
|
||||||
|
徽标经 #title 插槽渲染(当前版本组件在无 title 时不渲染 #extra,
|
||||||
|
原先徽标实际不可见) -->
|
||||||
<VEntityField width="4rem">
|
<VEntityField width="4rem">
|
||||||
<template #title>
|
<template #title>
|
||||||
<span
|
<span class="status-badge" :class="resultBadge(log.spec).class">
|
||||||
class="status-badge"
|
{{ resultBadge(log.spec).text }}
|
||||||
:class="isSuccessful(log.spec.statusCode) ? 'status-ok' : 'status-fail'"
|
|
||||||
>
|
|
||||||
{{ log.spec.statusCode }}
|
|
||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
</VEntityField>
|
</VEntityField>
|
||||||
<VEntityField :title="log.spec.remoteIp" width="9rem" />
|
<VEntityField :title="log.spec.remoteIp" width="9rem" />
|
||||||
</template>
|
</template>
|
||||||
</VEntity>
|
</VEntity>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
<!-- 分页条置于卡片内部末尾:白底铺满整行,与上方列表左右对齐 -->
|
<!-- 分页条置于卡片内部末尾:白底铺满整行,与上方列表左右对齐 -->
|
||||||
@@ -476,6 +481,14 @@ onMounted(fetchLogs)
|
|||||||
display: flex;
|
display: flex;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
/* 题头与数据行共用横向滚动容器(同官方 EntityList 的 w-full overflow-x-auto):
|
||||||
|
固定列宽合计约 69.5rem,容器更窄(手机/竖屏平板/半屏窗口)时整体左右滑动;
|
||||||
|
容器够宽时不产生滚动条,桌面观感不变。
|
||||||
|
VEntity 行内样式一律经此自身元素 :deep 穿透:VEntity 是多根 Fragment 组件,
|
||||||
|
其 <tr> 拿不到本组件的 scoped 作用域 ID,锚定 .audit-row 的规则永远失配。 */
|
||||||
|
.audit-list {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
/* 列题头:VEntity 数据行由两个 td(entity-start-wrapper / entity-end-wrapper)组成,
|
/* 列题头:VEntity 数据行由两个 td(entity-start-wrapper / entity-end-wrapper)组成,
|
||||||
每个 td 自带 1rem 左右内边距,end 组紧跟 start 组之后(行宽由内容收缩,不铺满)。
|
每个 td 自带 1rem 左右内边距,end 组紧跟 start 组之后(行宽由内容收缩,不铺满)。
|
||||||
题头按同样结构分两组、各组自带 1rem 内边距,才能与数据列一一对齐;
|
题头按同样结构分两组、各组自带 1rem 内边距,才能与数据列一一对齐;
|
||||||
@@ -483,6 +496,9 @@ onMounted(fetchLogs)
|
|||||||
.audit-header {
|
.audit-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
/* 滚动容器内题头盒随内容延伸(否则下划线止于可视宽度,滑动后断裂);
|
||||||
|
容器更宽时仍为 100%,与桌面一致 */
|
||||||
|
min-width: max-content;
|
||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
border-bottom: 1px solid #eaecf0;
|
border-bottom: 1px solid #eaecf0;
|
||||||
}
|
}
|
||||||
@@ -500,6 +516,8 @@ onMounted(fetchLogs)
|
|||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
color: #666;
|
color: #666;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
/* 列宽不参与 flex 收缩:窄屏下题头盒宽由内容决定,避免被压缩与数据列错位 */
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
.col-username { width: 12rem; }
|
.col-username { width: 12rem; }
|
||||||
.col-method { width: 6rem; }
|
.col-method { width: 6rem; }
|
||||||
@@ -512,7 +530,9 @@ onMounted(fetchLogs)
|
|||||||
/* 错误提示位于白卡上方,与卡片留出间距 */
|
/* 错误提示位于白卡上方,与卡片留出间距 */
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
.audit-row {
|
/* 行悬停手型:VEntity 多根组件的 tr 无法携带本组件 scoped 作用域 ID,
|
||||||
|
规则须锚定自身元素 .audit-list 再 :deep 穿透到行 */
|
||||||
|
.audit-list :deep(.entity-wrapper) {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.row-sub {
|
.row-sub {
|
||||||
@@ -576,4 +596,41 @@ onMounted(fetchLogs)
|
|||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
border-top: 1px solid #eaecf0;
|
border-top: 1px solid #eaecf0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== 移动端适配(窄屏:手机 / 竖屏平板 / 半屏小窗口) =====
|
||||||
|
桌面布局的 9 列筛选行在窄屏下每列仅剩数十像素(标签逐字换行、
|
||||||
|
输入框被压扁),窄屏改为筛选 2 列(≤480px 手机竖屏单列)。
|
||||||
|
列表保持题头 + 固定列宽的表格形态,由 .audit-list 整体左右滑动看全六列,
|
||||||
|
列对齐与桌面一致。数据行纵向堆叠方案不可行:VEntity 是多根 Fragment
|
||||||
|
组件,其 <tr> 拿不到本组件的 scoped 作用域 ID,所有锚定 .audit-row 的
|
||||||
|
行内 :deep 规则均失配(历史方案因此整批失效),且堆叠后题头无从对齐。
|
||||||
|
≥1024px 维持桌面布局不变。
|
||||||
|
媒体查询置于文件末尾,同特异性规则按顺序覆盖桌面样式。 */
|
||||||
|
@media (max-width: 1023px) {
|
||||||
|
.audit-body {
|
||||||
|
padding: 0.75rem 0.75rem 1.5rem;
|
||||||
|
}
|
||||||
|
.filter-grid {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
.filter-actions {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
.filter-actions > :deep(*) {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
/* 分页条(总数 + 翻页/条数控制器)窄屏下换行铺开,不横向溢出 */
|
||||||
|
.audit-pagination :deep(.pagination),
|
||||||
|
.audit-pagination :deep(.pagination__controller) {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
/* 手机竖屏:单列筛选,datetime-local 等宽控件不再被压扁 */
|
||||||
|
.filter-grid {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { viteConfig } from '@halo-dev/ui-plugin-bundler-kit/vite'
|
import { viteConfig } from '@halo-dev/ui-plugin-bundler-kit/vite'
|
||||||
import { fileURLToPath, URL } from 'url'
|
import { fileURLToPath, URL } from 'url'
|
||||||
|
|
||||||
// 官方 ui-plugin-bundler-kit 负责外部化 vue / @halo-dev/* 依赖并输出 console/main.js
|
// 官方 ui-plugin-bundler-kit 负责外部化 vue / @halo-dev/* 依赖并输出 ESM 产物
|
||||||
|
// (requires >=2.26.0 触发 auto 判定,由 Gradle 打包进插件 jar 的 ui/ 目录)
|
||||||
export default viteConfig({
|
export default viteConfig({
|
||||||
vite: {
|
vite: {
|
||||||
resolve: {
|
resolve: {
|
||||||
|
|||||||
Reference in New Issue
Block a user