Compare commits
10
Commits
34764c7641
..
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d05d63b8e | ||
|
|
753de51f7b | ||
|
|
44eca75e6e | ||
|
|
81693e4778 | ||
|
|
b6a21dfaa7 | ||
|
|
1987412e07 | ||
|
|
fd3ea71e31 | ||
|
|
99bd109e80 | ||
|
|
f4d1200d46 | ||
|
|
cc2c618fe7 |
@@ -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
|
||||
@@ -31,7 +31,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
||||
### 4.1 操作记录(核心)
|
||||
|
||||
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
|
||||
> 注:登录端点不在 `/apis/**` 下,捕获规则将其作为唯一必要例外精确匹配 `/login`、`/logout`(技术方案 D1)。
|
||||
> 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获 `/login`、`/logout`(技术方案 D1)。
|
||||
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
|
||||
- 每条记录字段:
|
||||
|
||||
@@ -104,7 +104,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
## 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
|
||||
- 捕获通道:`AfterSecurityWebFilter` 扩展点——位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码
|
||||
- 捕获通道:双过滤器分治——`/apis/**` 写操作由 `AfterSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码);认证端点 `/login`、`/logout` 由 `BeforeSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最前,先于表单登录/登出终止过滤器,操作者记"未知用户")。P0 缺陷实证:链尾过滤器永远看不到表单登录/登出请求(命中即 302 终止,不向下游传递),认证端点必须在链首承接
|
||||
- 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行
|
||||
- 存储:自定义 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)(事件监听与稳定性模式)
|
||||
|
||||
@@ -59,8 +59,8 @@
|
||||
|
||||
### 3.4 WebFlux 响应式(第 6 条)
|
||||
|
||||
- 全链路响应式:`AfterSecurityWebFilter` 扩展点、`ReactiveExtensionClient`、
|
||||
出站用 `WebClient`、定时清理用 Reactor 调度(未用 `@Scheduled`)。
|
||||
- 全链路响应式:`AfterSecurityWebFilter`/`BeforeSecurityWebFilter` 扩展点、
|
||||
`ReactiveExtensionClient`、出站用 `WebClient`、定时清理用 Reactor 调度(未用 `@Scheduled`)。
|
||||
- 未发现 `.block()` / `RestTemplate` / 阻塞 IO;仅有的 `synchronized`
|
||||
(`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 上不得阻塞主流程;自用量级无需队列 |
|
||||
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
| 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 |
|
||||
| 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 |
|
||||
| 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 |
|
||||
| 捕获通道 | `AfterSecurityWebFilter` 扩展点(实现 `WebFilter`,注册在 Security 链之后) | 产品文档第 8 节已源码级验证 |
|
||||
| 捕获通道 | `AfterSecurityWebFilter` + `BeforeSecurityWebFilter` 扩展点(实现 `WebFilter`,分别注册在 Security 链最后与最前) | 产品文档第 8 节已源码级验证;P0 缺陷实证双通道必要性 |
|
||||
| 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 |
|
||||
| Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 |
|
||||
| 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 |
|
||||
@@ -57,7 +57,8 @@ plugin-operation-audit/
|
||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||
│ │ │ ├── OperationAuditWebFilter.java
|
||||
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证端点捕获(BeforeSecurityWebFilter,链首)
|
||||
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
|
||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||
│ │ └── housekeeping/
|
||||
│ │ └── RetentionCleaner.java # 定时清理
|
||||
@@ -78,14 +79,17 @@ plugin-operation-audit/
|
||||
|
||||
## 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`,纯函数):
|
||||
- `POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`
|
||||
- 或路径精确匹配 `/login`、`/logout`
|
||||
- 匿名判断**不在请求期做,而在记录时做**:登录请求开始时用户必然匿名,只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致。
|
||||
- 该规则是产品设计"一条通用规则覆盖全部管理面操作"的唯一必要例外(登录端点不在 `/apis/**` 下),需在产品文档中同步注明。
|
||||
- `shouldCapture`:`POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`(链尾过滤器消费)
|
||||
- `isAuthEndpoint`:路径精确匹配 `/login`、`/logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录
|
||||
- 操作者归属:`/apis/**` 请求从认证上下文解析;认证端点在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
|
||||
- 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证端点记录不判匿名。
|
||||
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录且链尾过滤器不重复记录。
|
||||
|
||||
### D2 审计写入:响应式直写
|
||||
|
||||
|
||||
@@ -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 配置):
|
||||
反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。
|
||||
- **Windows 升级注意事项**:插件运行期间其 JAR 被进程锁定(Windows 文件锁),
|
||||
`upgrade` API 报 500(`FileSystemException: 另一个程序正在使用此文件`),停用插件后
|
||||
句柄也不释放。Windows 站点升级本插件需停服换 JAR 后重启;Linux/macOS 无此限制。
|
||||
|
||||
## 技术说明
|
||||
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经 `AfterSecurityWebFilter` 扩展点(认证之后,
|
||||
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||
Extension + 索引查询,全程响应式非阻塞。
|
||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
|
||||
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;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) {
|
||||
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')
|
||||
shouldRunAfter tasks.named('processResources')
|
||||
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar
|
||||
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar;
|
||||
// 同时清掉旧构建可能残留的 console/ 目录,防止过期产物被打进 jar
|
||||
doFirst {
|
||||
delete layout.buildDirectory.dir('resources/main/ui')
|
||||
delete layout.buildDirectory.dir('resources/main/console')
|
||||
}
|
||||
}
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+16
-8
@@ -6,9 +6,14 @@ import java.util.Set;
|
||||
* 捕获规则(纯函数,技术方案 D1):
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code POST/PUT/DELETE/PATCH} + 路径前缀 {@code /apis/}</li>
|
||||
* <li>或路径精确匹配 {@code /login}、{@code /logout}(登录端点不在 /apis/** 下,
|
||||
* 是“一条通用规则覆盖全部管理面操作”的唯一必要例外,需在产品文档同步注明)</li>
|
||||
* <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
|
||||
* 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
|
||||
* 可获得认证用户上下文);</li>
|
||||
* <li>认证端点 {@code /login}、{@code /logout} 精确匹配({@link #isAuthEndpoint},
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 消费)——登录端点不在 /apis/** 下,且
|
||||
* 表单登录/登出过滤器命中请求后直接完成响应、不再向下游传递,链尾的
|
||||
* AfterSecurityWebFilter 永远看不到(P0 缺陷实测),因此必须在 Security 链之前
|
||||
* 独立捕获。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||
@@ -25,18 +30,21 @@ public final class CaptureRule {
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
/** 是否命中捕获规则。path 为不含查询串的请求路径。 */
|
||||
/**
|
||||
* 是否命中捕获规则。path 为不含查询串的请求路径。
|
||||
*
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证端点由 {@link #isAuthEndpoint} 单独判定、
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
|
||||
* 互不重叠,不会重复记录。
|
||||
*/
|
||||
public static boolean shouldCapture(String path, String method) {
|
||||
if (isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
if (path == null || !path.startsWith(APIS_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
return method != null && WRITE_METHODS.contains(method);
|
||||
}
|
||||
|
||||
/** 是否为登录/登出端点。 */
|
||||
/** 是否为登录/登出端点(由 {@link AuthEndpointAuditWebFilter} 捕获)。 */
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
|
||||
+53
-46
@@ -3,8 +3,8 @@ package run.halo.operationaudit.audit;
|
||||
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
@@ -20,20 +20,27 @@ import run.halo.app.extension.Unstructured;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
||||
* 登录端点非注册模型,与 {@link ChangeCaptureManager} 的 JSON 缓存逻辑分开,
|
||||
* 为登录端点单独补一条请求体读取:缓存请求体(下游可重复读)并提取尝试的用户名。
|
||||
* 登录端点非注册模型,为登录端点单独提取尝试的用户名。
|
||||
*
|
||||
* <p>提取规则(安全边界):
|
||||
* <ul>
|
||||
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
||||
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
||||
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
||||
* <li>请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存,
|
||||
* 与字段级变更捕获同款边界(分块传输/超限一律不读,仅不提取用户名)。</li>
|
||||
* <li>超长用户名({@value #MAX_USERNAME_LENGTH} 字符以上)视为扫描载荷,不提取。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
|
||||
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
|
||||
* <p>表单形态({@code application/x-www-form-urlencoded}):经
|
||||
* {@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},与审计开关、
|
||||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||||
*/
|
||||
@@ -41,23 +48,39 @@ import run.halo.app.extension.Unstructured;
|
||||
@Component
|
||||
public class LoginAttemptCapture {
|
||||
|
||||
/** 登录请求体缓存上限(字节):登录表单极小,上限远小于字段级变更捕获。 */
|
||||
/** JSON 请求体缓存上限(字节):登录请求体极小,上限远小于字段级变更捕获。 */
|
||||
static final int MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
/** 提取的用户名长度上限:超过视为扫描载荷,不提取(保证记录与告警负载卫生)。 */
|
||||
static final int MAX_USERNAME_LENGTH = 256;
|
||||
|
||||
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
|
||||
static final Set<String> USERNAME_FIELDS = Set.of("username");
|
||||
|
||||
private static final String USERNAME_FIELD = "username";
|
||||
|
||||
/**
|
||||
* 为登录请求缓存请求体并提取尝试的用户名。返回(可能包装了缓存请求体的)交换对象
|
||||
* 供后续链路继续处理;返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange。
|
||||
* 为登录请求提取尝试的用户名。返回交换对象供后续链路继续处理;返回的 Mono
|
||||
* 永不报错、永不为空:任何失败均回退原 exchange。
|
||||
*/
|
||||
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, LoginAttempt attempt) {
|
||||
var contentType = exchange.getRequest().getHeaders().getContentType();
|
||||
if (!supported(contentType)) {
|
||||
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();
|
||||
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
||||
// 分块传输(无 Content-Length)或超限:不读请求体,避免中断流式请求
|
||||
@@ -68,7 +91,7 @@ public class LoginAttemptCapture {
|
||||
var bytes = new byte[joined.readableByteCount()];
|
||||
joined.read(bytes);
|
||||
DataBufferUtils.release(joined);
|
||||
attempt.setAttemptedUsername(extract(bytes, contentType));
|
||||
attempt.setAttemptedUsername(extractJson(bytes));
|
||||
return decorate(exchange, bytes);
|
||||
})
|
||||
.defaultIfEmpty(exchange)
|
||||
@@ -83,16 +106,16 @@ public class LoginAttemptCapture {
|
||||
if (contentType == null) {
|
||||
return false;
|
||||
}
|
||||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
|| ChangeCaptureManager.isJson(contentType);
|
||||
return isForm(contentType) || ChangeCaptureManager.isJson(contentType);
|
||||
}
|
||||
|
||||
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
|
||||
private static String extract(byte[] bytes, MediaType contentType) {
|
||||
private static boolean isForm(MediaType contentType) {
|
||||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
}
|
||||
|
||||
/** JSON 体提取:仅取顶层白名单字段的标量值;任何异常静默返回 null。 */
|
||||
private static String extractJson(byte[] bytes) {
|
||||
try {
|
||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
|
||||
return usernameOfForm(new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
|
||||
} catch (Exception e) {
|
||||
// 解析异常静默:不提取,不影响登录主流程
|
||||
@@ -101,28 +124,18 @@ public class LoginAttemptCapture {
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
|
||||
* 表单字段提取:仅取白名单字段的值(同名多值取最后一个,与逐字段解析语义一致);
|
||||
* 超长值视为扫描载荷不提取。
|
||||
*/
|
||||
static String usernameOfForm(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
static String usernameOfFormValues(List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String found = null;
|
||||
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) {
|
||||
// 表单解析异常静默:不提取,不影响登录主流程
|
||||
var found = values.get(values.size() - 1);
|
||||
if (!StringUtils.hasText(found) || found.length() > MAX_USERNAME_LENGTH) {
|
||||
return null;
|
||||
}
|
||||
return maskIfSensitive(USERNAME_FIELD, found);
|
||||
}
|
||||
|
||||
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
||||
@@ -135,7 +148,10 @@ public class LoginAttemptCapture {
|
||||
return null;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** URL 编码解码失败(如裸 %)回退原值,尽力提取、绝不抛出。 */
|
||||
private static String safeDecode(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游登录处理可正常读取。 */
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游可重复读。 */
|
||||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||
@Override
|
||||
|
||||
+18
-72
@@ -3,7 +3,6 @@ package run.halo.operationaudit.audit;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -13,13 +12,15 @@ import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.context.ContextView;
|
||||
import run.halo.app.security.AfterSecurityWebFilter;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1)。
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1),仅负责 {@code /apis/**} 写操作。
|
||||
*
|
||||
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
|
||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。
|
||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。认证端点
|
||||
* ({@code /login}、{@code /logout})不在此过滤器捕获——表单登录/登出过滤器命中请求后
|
||||
* 直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到(P0 缺陷实测);
|
||||
* 详见 {@link AuthEndpointAuditWebFilter}。
|
||||
*
|
||||
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
|
||||
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
||||
@@ -29,20 +30,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
||||
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
||||
*
|
||||
* <p>系统内部变更(产品设计 V2):所有写方法请求(含未被捕获规则命中的 {@code /api/**}
|
||||
* 核心模型与登录端点)均经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* <p>系统内部变更(产品设计 V2):未被捕获规则命中的写方法请求({@code /api/**}
|
||||
* 核心模型)同样经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||
* {@code error} 参数区分,不能只看状态码)。尝试的用户名(功能评审 P0-1)由
|
||||
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
|
||||
* {@code spec.attemptedUsername} 并进入告警负载。
|
||||
*
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||
* 与筛选;HTTP 状态码仍如实记录。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -54,8 +44,6 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
private final LoginAttemptCapture loginAttemptCapture;
|
||||
private final LoginFailureAlertService loginFailureAlertService;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
@@ -63,7 +51,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
var path = request.getPath().value();
|
||||
var method = request.getMethod().name();
|
||||
if (!shouldCapture(path, method)) {
|
||||
// 未命中捕获规则的写方法请求(/api/** 核心模型、登录端点等)不记录,
|
||||
// 未命中捕获规则的写方法请求(/api/** 核心模型等)不记录,
|
||||
// 但仍登记标记:请求期触发的资源变更由该请求归属
|
||||
if (CaptureRule.WRITE_METHODS.contains(method)) {
|
||||
writeMarker.onRequestStart(request);
|
||||
@@ -75,33 +63,17 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var capture = new ChangeCapture();
|
||||
var loginAttempt = new LoginAttempt();
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 其余请求原样透传
|
||||
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))
|
||||
return captureManager.prepare(exchange, snapshot, capture)
|
||||
.flatMap(chain::filter)
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
var statusCode = statusOf(exchange);
|
||||
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
|
||||
// 以重定向目标是否含 error 参数区分;GET /login?error=... 为失败回显
|
||||
var loginFailed = isLoginFailed(path, method, statusCode, exchange, snapshot);
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 成功清零计数、失败累计,独立于下方审计记录决策
|
||||
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
|
||||
loginAttempt.getAttemptedUsername());
|
||||
}
|
||||
operatorOf(ctx, path).subscribe(
|
||||
operatorOf(ctx).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
if (shouldRecord(username)) {
|
||||
recorder.record(snapshot, capture, statusCode, username,
|
||||
loginAttempt.getAttemptedUsername(), loginFailed);
|
||||
null, false);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||
@@ -111,10 +83,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
/**
|
||||
* 从订阅上下文解析操作者用户名。
|
||||
*
|
||||
* <p>上下文中无 SecurityContext(匿名请求)→ 空用户名;登录端点的匿名请求记“未知用户”。
|
||||
* <p>上下文中无 SecurityContext 或认证无用户名 → 记“未知用户”占位。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Mono<String> operatorOf(ContextView ctx, String path) {
|
||||
private static Mono<String> operatorOf(ContextView ctx) {
|
||||
return ctx.getOrEmpty(SecurityContext.class)
|
||||
.map(value -> ((Mono<SecurityContext>) value)
|
||||
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
|
||||
@@ -125,13 +97,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录决策(技术方案 D1):匿名判断在记录时做——
|
||||
* {@code /apis/**} 下认证后仍为匿名主体(401/403 场景)的请求跳过不记。
|
||||
* 记录决策(技术方案 D1):匿名判断在记录时做——认证后仍为匿名主体
|
||||
* (401/403 场景)的请求跳过不记。
|
||||
*/
|
||||
private static boolean shouldRecord(String path, String username) {
|
||||
if (CaptureRule.isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
private static boolean shouldRecord(String username) {
|
||||
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
|
||||
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
|
||||
}
|
||||
@@ -140,27 +109,4 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
var status = exchange.getResponse().getStatusCode();
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败判定(LoginOutcome):POST {@code /login} 按状态码 + 重定向目标判定
|
||||
* (表单登录成败均为 302,以 Location 是否含 {@code error} 参数区分);
|
||||
* 其余请求仅登录失败回显({@code GET /login?error=...},HTTP 200)判为失败。
|
||||
*/
|
||||
private static boolean isLoginFailed(String path, String method, Integer statusCode,
|
||||
ServerWebExchange exchange, RequestSnapshot snapshot) {
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
return LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
}
|
||||
if (CaptureRule.isAuthEndpoint(path) && "GET".equals(method)) {
|
||||
return LoginOutcome.isFailureEcho(snapshot.getFullPath());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
|
||||
static boolean isAnonymous(Authentication authentication) {
|
||||
return authentication == null || !StringUtils.hasText(authentication.getName())
|
||||
|| ANONYMOUS_USER.equals(authentication.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
author:
|
||||
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: "操作审计"
|
||||
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
|
||||
settingName: operation-audit-settings
|
||||
configMapName: operation-audit-configmap
|
||||
license:
|
||||
- name: "GPL-3.0"
|
||||
url: "https://www.gnu.org/licenses/gpl-3.0.html"
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+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
|
||||
void shouldCaptureAuthEndpointsRegardlessOfMethod() {
|
||||
assertThat(shouldCapture("/login", "POST")).isTrue();
|
||||
assertThat(shouldCapture("/login", "GET")).isTrue();
|
||||
assertThat(shouldCapture("/logout", "POST")).isTrue();
|
||||
void shouldNotCaptureAuthEndpointsInApisRule() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 独立捕获(isAuthEndpoint),
|
||||
// 通用规则不再包含,两个过滤器按规则分治、互不重叠
|
||||
assertThat(shouldCapture("/login", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/login", "GET")).isFalse();
|
||||
assertThat(shouldCapture("/logout", "POST")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+72
-44
@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.web.server.MockServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单体解析(成功/无 username/异常静默)、
|
||||
* JSON 体提取、字段白名单(密码绝不提取)、请求体缓存后下游可重复读、
|
||||
* 分块/超限/不支持形态降级为原 exchange。
|
||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单经 {@code getFormData()} 提取
|
||||
* (与下游 CSRF/登录转换器共享缓存解析结果,不消费原始 body——真实环境回归实证:
|
||||
* 缓存原始 body 会让下游 CSRF 读不到 _csrf 参数而拒绝登录)、JSON 体缓存提取、
|
||||
* 字段白名单(密码绝不提取)、超长用户名不提取、不支持形态降级为原 exchange。
|
||||
*/
|
||||
class LoginAttemptCaptureTest {
|
||||
|
||||
@@ -54,7 +56,7 @@ class LoginAttemptCaptureTest {
|
||||
return attempt;
|
||||
}
|
||||
|
||||
// ===== 表单体解析 =====
|
||||
// ===== 表单提取(经 getFormData 共享缓存,不消费原始 body) =====
|
||||
|
||||
@Test
|
||||
void shouldExtractUsernameFromFormBody() {
|
||||
@@ -86,22 +88,64 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToRawValueOnMalformedEncoding() {
|
||||
// 裸 % 等非法编码:解码失败回退原值,尽力提取且绝不抛出
|
||||
var attempt = prepare(formExchange("username=bad%zz&password=x"));
|
||||
void shouldNotTouchRawBodyForFormRequests() {
|
||||
// 表单形态绝不缓存原始 body / 装饰 exchange:prepare 后 exchange 原样透传,
|
||||
// 下游(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
|
||||
void shouldExtractSilentlyFromGarbageBody() {
|
||||
// 解析异常静默:任何畸形输入都不抛出、不提取
|
||||
var attempt = prepare(formExchange("&&&"));
|
||||
void shouldExtractFromChunkedFormBody() {
|
||||
// 分块传输(无 Content-Length):getFormData 为标准解析路径,正常提取
|
||||
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();
|
||||
}
|
||||
|
||||
// ===== 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
|
||||
void shouldExtractUsernameFromJsonBody() {
|
||||
@@ -117,18 +161,16 @@ class LoginAttemptCaptureTest {
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
// ===== 请求体缓存与下游可重复读 =====
|
||||
|
||||
@Test
|
||||
void shouldKeepBodyReadableDownstream() {
|
||||
var body = "username=admin&password=secret";
|
||||
var exchange = formExchange(body);
|
||||
void shouldKeepJsonBodyReadableDownstream() {
|
||||
var body = "{\"username\":\"admin\",\"password\":\"secret\"}";
|
||||
var exchange = jsonExchange(body);
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||
// 装饰后的请求可重复读(每次订阅独立 buffer),登录处理可正常读取表单
|
||||
// 装饰后的请求可重复读(每次订阅独立 buffer)
|
||||
assertThat(prepared).isNotSameAs(exchange);
|
||||
var first = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
@@ -158,27 +200,12 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughChunkedBodyWithoutContentLength() {
|
||||
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();
|
||||
|
||||
// 分块传输(无 Content-Length):不读请求体,避免中断流式请求
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughOversizedBody() {
|
||||
var oversized = "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES + 1);
|
||||
void shouldPassthroughOversizedJsonBody() {
|
||||
var oversized = "{\"username\":\"" + "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES)
|
||||
+ "\"}";
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(oversized.length())
|
||||
.body(oversized));
|
||||
|
||||
@@ -190,10 +217,10 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughEmptyBody() {
|
||||
void shouldPassthroughEmptyJsonBody() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
@@ -228,13 +255,14 @@ class LoginAttemptCaptureTest {
|
||||
|
||||
@Test
|
||||
void shouldExtractLastUsernameWhenDuplicated() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm("username=first&username=second"))
|
||||
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of("first", "second")))
|
||||
.isEqualTo("second");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForBlankFormBody() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(null)).isNull();
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(" ")).isNull();
|
||||
void shouldReturnNullForMissingOrBlankFormValues() {
|
||||
assertThat(LoginAttemptCapture.usernameOfFormValues(null)).isNull();
|
||||
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of())).isNull();
|
||||
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of(" "))).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
+20
-219
@@ -7,15 +7,14 @@ 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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
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.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
@@ -24,23 +23,21 @@ import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* {@code /apis/**} 捕获过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
||||
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(由 LoginOutcome 判定:
|
||||
* 表单登录成败均为 302 重定向,以 Location 是否含 error 参数区分;2xx 成功、其余失败)。
|
||||
* 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。
|
||||
* 登录失败标注:POST /login 失败与 GET /login?error=... 失败回显随记录标注 login-failure。
|
||||
*
|
||||
* <p>认证端点({@code /login}、{@code /logout})不在本过滤器职责内(P0 修复:它们由
|
||||
* {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,此处透传不记录),
|
||||
* 其行为见 {@link AuthEndpointAuditWebFilterTest} 与过滤链集成测试。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
private AuditRecorder recorder;
|
||||
private ChangeCaptureManager captureManager;
|
||||
private HttpWriteMarker writeMarker;
|
||||
private LoginFailureAlertService loginFailureAlertService;
|
||||
private OperationAuditWebFilter filter;
|
||||
|
||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||
@@ -55,54 +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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 终止型 chain:模拟 Halo 登录端点的 302 重定向响应(表单登录成败均为重定向,
|
||||
* 以 Location 目标是否含 error 参数区分成败)后完成。
|
||||
*/
|
||||
private static final class RedirectWebFilterChainStub implements
|
||||
org.springframework.web.server.WebFilterChain {
|
||||
private final java.net.URI location;
|
||||
|
||||
private RedirectWebFilterChainStub(java.net.URI location) {
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange) {
|
||||
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FOUND);
|
||||
exchange.getResponse().getHeaders().setLocation(location);
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
recorder = mock(AuditRecorder.class);
|
||||
captureManager = mock(ChangeCaptureManager.class);
|
||||
writeMarker = mock(HttpWriteMarker.class);
|
||||
loginFailureAlertService = mock(LoginFailureAlertService.class);
|
||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||
any(ChangeCapture.class)))
|
||||
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
||||
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
|
||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker,
|
||||
new LoginAttemptCapture(), loginFailureAlertService);
|
||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -135,34 +93,23 @@ class OperationAuditWebFilterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureAsUnknownUser() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
void shouldPassThroughAuthEndpointsWithoutRecording() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 在 Security 链之前捕获,
|
||||
// 本过滤器不再记录;写方法请求(POST /login、POST /logout)仍按统一语义
|
||||
// 登记内部变更归属标记(真实链上 POST 请求到不了链尾,GET 由透传处理)
|
||||
var login = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.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).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@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"), eq(false));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true),
|
||||
eq("admin"));
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, times(2)).onRequestStart(any());
|
||||
verify(writeMarker, times(2)).onRequestComplete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -194,27 +141,6 @@ class OperationAuditWebFilterTest {
|
||||
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(), eq(false));
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassCaptureContextToRecorder() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
@@ -283,129 +209,4 @@ class OperationAuditWebFilterTest {
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
verify(writeMarker, never()).onRequestComplete(any());
|
||||
}
|
||||
|
||||
// ===== 登录失败告警与登录结果判定(产品设计 V2「告警通知」/ LoginOutcome) =====
|
||||
|
||||
@Test
|
||||
void shouldNotifyLoginSuccessOnXhrLogin() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
// XHR/JSON 登录成功(200):回调成功,清零计数
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotifyLoginFailureOnUnauthorized() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new FailingWebFilterChainStub(org.springframework.http.HttpStatus.UNAUTHORIZED)))
|
||||
.verifyComplete();
|
||||
|
||||
// XHR/JSON 登录失败(401)同样回调,由告警服务按失败累计
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatFormFailureRedirectAsLoginFailure() {
|
||||
// 表单登录失败:302 → /login?error=invalid-credential&method=local,
|
||||
// 与成功重定向同状态码,必须按 Location 目标判定
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
|
||||
java.net.URI.create("/login?error=invalid-credential&method=local"))))
|
||||
.verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
|
||||
isNull());
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatFormSuccessRedirectAsLoginSuccess() {
|
||||
// 表单登录成功:302 → /uc(无 error 参数)——修复前会被 2xx 判定误计为失败
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new RedirectWebFilterChainStub(java.net.URI.create("/uc"))))
|
||||
.verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true),
|
||||
isNull());
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageErrorEchoAsLoginFailure() {
|
||||
// 登录失败回显:GET /login?error=invalid-credential 页面渲染 HTTP 200,
|
||||
// 审计记录标注登录失败(loginFailed=true),但不是登录尝试、不触发告警
|
||||
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), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordPlainLoginPageAsLoginWithoutFailureMark() {
|
||||
// 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@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), anyBoolean(), 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), anyBoolean(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { viteConfig } from '@halo-dev/ui-plugin-bundler-kit/vite'
|
||||
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({
|
||||
vite: {
|
||||
resolve: {
|
||||
|
||||
Reference in New Issue
Block a user