根因(测试报告 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 列表登录失败红色标注正常。
178 lines
8.0 KiB
Java
178 lines
8.0 KiB
Java
package run.halo.operationaudit.audit;
|
||
|
||
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
||
|
||
import com.fasterxml.jackson.databind.JsonNode;
|
||
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;
|
||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||
import org.springframework.http.MediaType;
|
||
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
|
||
import org.springframework.stereotype.Component;
|
||
import org.springframework.util.StringUtils;
|
||
import org.springframework.web.server.ServerWebExchange;
|
||
import reactor.core.publisher.Flux;
|
||
import reactor.core.publisher.Mono;
|
||
import run.halo.app.extension.Unstructured;
|
||
|
||
/**
|
||
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
||
* 登录端点非注册模型,为登录端点单独提取尝试的用户名。
|
||
*
|
||
* <p>提取规则(安全边界):
|
||
* <ul>
|
||
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
||
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
||
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
||
* <li>超长用户名({@value #MAX_USERNAME_LENGTH} 字符以上)视为扫描载荷,不提取。</li>
|
||
* </ul>
|
||
*
|
||
* <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},与审计开关、
|
||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||
*/
|
||
@Slf4j
|
||
@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。
|
||
*/
|
||
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)或超限:不读请求体,避免中断流式请求
|
||
return Mono.just(exchange);
|
||
}
|
||
return DataBufferUtils.join(exchange.getRequest().getBody(), MAX_BODY_BYTES)
|
||
.map(joined -> {
|
||
var bytes = new byte[joined.readableByteCount()];
|
||
joined.read(bytes);
|
||
DataBufferUtils.release(joined);
|
||
attempt.setAttemptedUsername(extractJson(bytes));
|
||
return decorate(exchange, bytes);
|
||
})
|
||
.defaultIfEmpty(exchange)
|
||
.onErrorResume(e -> {
|
||
log.warn("Failed to capture login attempt body for username extraction", e);
|
||
return Mono.just(exchange);
|
||
});
|
||
}
|
||
|
||
/** 支持提取的请求体形态:表单或 JSON(登录端点仅接受这两种)。 */
|
||
static boolean supported(MediaType contentType) {
|
||
if (contentType == null) {
|
||
return false;
|
||
}
|
||
return isForm(contentType) || ChangeCaptureManager.isJson(contentType);
|
||
}
|
||
|
||
private static boolean isForm(MediaType contentType) {
|
||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED);
|
||
}
|
||
|
||
/** JSON 体提取:仅取顶层白名单字段的标量值;任何异常静默返回 null。 */
|
||
private static String extractJson(byte[] bytes) {
|
||
try {
|
||
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
|
||
} catch (Exception e) {
|
||
// 解析异常静默:不提取,不影响登录主流程
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 表单字段提取:仅取白名单字段的值(同名多值取最后一个,与逐字段解析语义一致);
|
||
* 超长值视为扫描载荷不提取。
|
||
*/
|
||
static String usernameOfFormValues(List<String> values) {
|
||
if (values == null || values.isEmpty()) {
|
||
return null;
|
||
}
|
||
var found = values.get(values.size() - 1);
|
||
if (!StringUtils.hasText(found) || found.length() > MAX_USERNAME_LENGTH) {
|
||
return null;
|
||
}
|
||
return maskIfSensitive(USERNAME_FIELD, found);
|
||
}
|
||
|
||
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
||
static String usernameOfJson(JsonNode root) {
|
||
if (root == null || !root.isObject()) {
|
||
return null;
|
||
}
|
||
var value = root.path(USERNAME_FIELD);
|
||
if (!value.isValueNode()) {
|
||
return null;
|
||
}
|
||
var text = value.asText();
|
||
if (!StringUtils.hasText(text) || text.length() > MAX_USERNAME_LENGTH) {
|
||
return null;
|
||
}
|
||
return maskIfSensitive(USERNAME_FIELD, text);
|
||
}
|
||
|
||
/**
|
||
* 兜底脱敏:白名单保证仅提取 username,若未来白名单调整后字段名命中现有敏感字段
|
||
* 规则({@link ChangeDiffEngine}),提取值一律以 {@value ChangeDiffEngine#REDACTED_VALUE}
|
||
* 代替,密码/密钥绝不落库。
|
||
*/
|
||
static String maskIfSensitive(String fieldName, String value) {
|
||
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
|
||
}
|
||
|
||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游可重复读。 */
|
||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||
@Override
|
||
public Flux<DataBuffer> getBody() {
|
||
return Flux.defer(
|
||
() -> Mono.just(exchange.getResponse().bufferFactory().wrap(body)));
|
||
}
|
||
};
|
||
return exchange.mutate().request(decorated).build();
|
||
}
|
||
}
|