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
@@ -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):
*
* <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);
}
@@ -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
@@ -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());
}
}