fix: P0 修复——认证端点改由 BeforeSecurityWebFilter 在 Security 链最前捕获

根因(测试报告 P0 实证):OperationAuditWebFilter 经 AfterSecurityWebFilter 注册于
Security 过滤链尾、认证环节之后,表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
POST /login、POST /logout 后直接完成 302 响应、不再向下游传递——链尾审计过滤器
永远看不到认证端点请求,登录/登出记录与登录失败告警生产路径均为死代码。

- 新增 AuthEndpointAuditWebFilter:BeforeSecurityWebFilter 扩展点(链首)承接
  /login、/logout 捕获,操作者记未知用户(链首无认证上下文),登录尝试账号、
  登录结果判定、失败告警回调随迁
- CaptureRule 分治:shouldCapture 仅覆盖 /apis/** 写操作,isAuthEndpoint 归链首
  过滤器,互不重叠不重复记录;OperationAuditWebFilter 移除认证端点死分支
- 修复 LoginAttemptCapture 表单提取通道:改经 getFormData() 共享缓存读取——原实现
  缓存原始请求体并装饰 exchange 后,下游 CSRF 过滤器经原始 exchange 解析已被消费
  的 body、读不到 _csrf 表单参数,真实 Halo 登录页表单提交整体 403(联调实证);
  JSON 形态仍走缓存+装饰(下游无表单语义),并增加用户名长度上限
- 新增真实 Spring Security 过滤链集成测试(按 Halo SecurityWebFiltersConfigurer
  组装:FIRST/FORM_LOGIN/AUTHENTICATION/LOGOUT/LAST):断言 POST /login 成败、
  POST /logout 必产生记录且链尾不重复记录;含启用 CSRF + 表单参数令牌的
  回归测试锁死 getFormData 通道;doFinally 晚于完成信号回调,断言统一
  以 Mockito timeout 等待
- 同步产品设计/技术方案/合规文档与 README(含 Windows JAR 锁定升级注意事项)

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