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} 的请求体为表单形态、 * 登录端点非注册模型,为登录端点单独提取尝试的用户名。 * *

提取规则(安全边界): *

* *

表单形态({@code application/x-www-form-urlencoded}):经 * {@link ServerWebExchange#getFormData()} 读取——该 Mono 由 * {@code DefaultServerWebExchange} 在构造时创建并 {@code cache()},与下游 CSRF 过滤器、 * 表单登录转换器共享同一份解析结果。绝不缓存原始请求体并装饰 exchange: * 装饰后的 exchange 会将 {@code getFormData()} 代理回原始 exchange、解析已被消费的 * 原始 body,导致下游 CSRF 读不到 {@code _csrf} 参数而拒绝登录(真实环境回归实证, * 登录页表单提交整体失效)。JSON 形态则缓存原始请求体并装饰(下游无表单语义、 * 登录转换器不读 JSON 体,装饰使其可重复读)。 * *

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 USERNAME_FIELDS = Set.of("username"); private static final String USERNAME_FIELD = "username"; /** * 为登录请求提取尝试的用户名。返回交换对象供后续链路继续处理;返回的 Mono * 永不报错、永不为空:任何失败均回退原 exchange。 */ public Mono 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 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 getBody() { return Flux.defer( () -> Mono.just(exchange.getResponse().bufferFactory().wrap(body))); } }; return exchange.mutate().request(decorated).build(); } }