feat: 登录失败记录尝试的用户名(P0-1,告警/落库/CSV)
- 新增 LoginAttemptCapture:为登录端点单独缓存请求体(表单/JSON 双形态, Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制仅提取 username,兜底经现有敏感字段脱敏规则(ChangeDiffEngine)复核, 密码绝不提取落库;任何失败静默降级,不影响登录主流程 - AuditLogSpec 新增 spec.attemptedUsername(不建索引),AuditRecorder 透传落库 - 告警负载 data 新增 attemptedUsername,content 增加尝试的账号段 - CSV 导出新增"尝试用户"列(操作者之后) - 详情抽屉展示"尝试用户"(仅登录请求落库时显示) - 更新 README(功能/告警负载示例/已知局限移除对应条目/技术说明)
This commit is contained in:
+170
@@ -0,0 +1,170 @@
|
||||
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.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} 的请求体为表单形态、
|
||||
* 登录端点非注册模型,与 {@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>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
|
||||
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
|
||||
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
|
||||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class LoginAttemptCapture {
|
||||
|
||||
/** 登录请求体缓存上限(字节):登录表单极小,上限远小于字段级变更捕获。 */
|
||||
static final int MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
|
||||
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);
|
||||
}
|
||||
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(extract(bytes, contentType));
|
||||
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 contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
|| ChangeCaptureManager.isJson(contentType);
|
||||
}
|
||||
|
||||
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
|
||||
private static String extract(byte[] bytes, MediaType contentType) {
|
||||
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) {
|
||||
// 解析异常静默:不提取,不影响登录主流程
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
|
||||
*/
|
||||
static String usernameOfForm(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
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) {
|
||||
// 表单解析异常静默:不提取,不影响登录主流程
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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();
|
||||
return StringUtils.hasText(text) ? maskIfSensitive(USERNAME_FIELD, text) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 兜底脱敏:白名单保证仅提取 username,若未来白名单调整后字段名命中现有敏感字段
|
||||
* 规则({@link ChangeDiffEngine}),提取值一律以 {@value ChangeDiffEngine#REDACTED_VALUE}
|
||||
* 代替,密码/密钥绝不落库。
|
||||
*/
|
||||
static String maskIfSensitive(String fieldName, String value) {
|
||||
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),下游登录处理可正常读取。 */
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user