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:
2026-11-22 00:06:13 +08:00
parent cb86a3d305
commit 08e7bd8a12
16 changed files with 662 additions and 106 deletions
@@ -17,8 +17,8 @@ import run.halo.operationaudit.audit.RequestSnapshot;
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
*
* <p>登录失败暂无法得知尝试的用户名(产品设计已知局限,与登录记录一致),告警负载
* 仅含失败次数、窗口、最近一次来源 IP 与 User-Agent。
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
*
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
@@ -40,11 +40,15 @@ public class LoginFailureAlertService {
/**
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
* 任何失败静默降级,不影响调用方。
*
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
* 提取失败为 null)
*/
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode) {
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
String attemptedUsername) {
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
settingProvider.get().subscribe(
settings -> handle(settings, snapshot, success, Instant.now()),
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
e -> log.warn("Failed to load alert settings, skip login alert for {}",
snapshot.getFullPath(), e));
}
@@ -53,7 +57,8 @@ public class LoginFailureAlertService {
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。
* handle 包内可见以便测试直接驱动窗口推进。
*/
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success, Instant now) {
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
String attemptedUsername, Instant now) {
try {
if (!settings.enabledOrDefault()) {
return;
@@ -85,7 +90,7 @@ public class LoginFailureAlertService {
failureCount = 0;
}
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
snapshot.getRemoteIp(), snapshot.getUserAgent(), now));
snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
} catch (Exception e) {
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
log.warn("Failed to handle login failure alert for {}",
@@ -98,16 +103,19 @@ public class LoginFailureAlertService {
* data 供程序化消费方取结构化字段。
*/
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp,
String userAgent, Instant timestamp) {
String userAgent, String attemptedUsername, Instant timestamp) {
var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
+ remoteIp + (userAgent != null && !userAgent.isBlank()
? "(" + userAgent + ")" : "")
+ (attemptedUsername != null && !attemptedUsername.isBlank()
? ",尝试的账号:" + attemptedUsername : "")
+ "。可在 Console「操作审计」查看详情。";
var data = new LinkedHashMap<String, Object>();
data.put("failures", failures);
data.put("windowMinutes", windowMinutes);
data.put("remoteIp", remoteIp);
data.put("userAgent", userAgent);
data.put("attemptedUsername", attemptedUsername);
var payload = new LinkedHashMap<String, Object>();
payload.put("type", "login-failure");
payload.put("title", "操作审计告警:登录失败");
@@ -38,9 +38,12 @@ public class AuditLogCsvExporter {
/** 每批查询条数。 */
static final int EXPORT_BATCH_SIZE = 200;
/** CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要)。 */
/**
* CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要,
* "尝试用户"列为登录尝试的用户名,功能评审 P0-1)。
*/
private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
private static final DataBufferFactory BUFFER_FACTORY =
DefaultDataBufferFactory.sharedInstance;
@@ -105,6 +108,7 @@ public class AuditLogCsvExporter {
return String.join(",",
escape(formatTime(log.getMetadata().getCreationTimestamp())),
escape(spec.getUsername()),
escape(spec.getAttemptedUsername()),
escape(spec.getMethod()),
escape(spec.getResourceType()),
escape(spec.getResourceName()),
@@ -14,6 +14,14 @@ public class AuditLogSpec {
/** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */
private String username;
/**
* 登录尝试的用户名(功能评审 P0-1):仅 POST {@code /login} 请求从表单/JSON 请求体
* 白名单提取落库(密码等其余字段绝不提取);登录失败时操作者为
* {@link #UNKNOWN_USERNAME},本字段用于区分定向撞库与无差别扫描。
* 提取失败或非登录请求为 null;不建索引(无需按其筛选)。
*/
private String attemptedUsername;
/** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */
private String method;
@@ -35,9 +35,12 @@ public class AuditRecorder {
*
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
*
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
*/
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
settingProvider.get().subscribe(
settings -> {
if (!settings.enabledOrDefault()) {
@@ -45,19 +48,19 @@ public class AuditRecorder {
snapshot.getMethod(), snapshot.getFullPath());
return;
}
write(snapshot, capture, statusCode, username);
write(snapshot, capture, statusCode, username, attemptedUsername);
},
e -> {
log.warn("Failed to load audit settings, record with defaults for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e);
write(snapshot, capture, statusCode, username);
write(snapshot, capture, statusCode, username, attemptedUsername);
});
}
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
try {
var auditLog = assemble(snapshot, capture, statusCode, username);
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
client.create(auditLog)
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e));
@@ -144,11 +147,13 @@ public class AuditRecorder {
}
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
var resolved = ResourceResolver.resolve(snapshot.getPath());
var spec = new AuditLogSpec();
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
// 登录尝试用户名(功能评审 P0-1):仅登录请求由捕获器提取,其余请求为 null
spec.setAttemptedUsername(attemptedUsername);
spec.setMethod(snapshot.getMethod());
spec.setResourceType(resolved.resourceType());
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
@@ -366,8 +366,11 @@ final class ChangeDiffEngine {
out.add(entry);
}
/** 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。 */
private static boolean isSensitiveField(String field) {
/**
* 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。
* 包内可见:登录尝试用户名提取({@link LoginAttemptCapture})兜底复用同一规则。
*/
static boolean isSensitiveField(String field) {
for (var segment : field.split("\\.")) {
if (SENSITIVE_FIELD.matcher(segment).find()) {
return true;
@@ -0,0 +1,16 @@
package run.halo.operationaudit.audit;
import lombok.Getter;
import lombok.Setter;
/**
* 登录尝试上下文(功能评审 P0-1):请求期由 {@link LoginAttemptCapture} 一次性提取
* 尝试的用户名,响应完成后由捕获过滤器消费(落库 {@code spec.attemptedUsername} 与
* 告警负载)。非登录请求或提取失败时保持 null。
*/
public class LoginAttempt {
@Getter
@Setter
private volatile String attemptedUsername;
}
@@ -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();
}
}
@@ -35,7 +35,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
*
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
* Webhook;与审计开关相互独立。
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
* {@code spec.attemptedUsername} 并进入告警负载。
*/
@Component
@RequiredArgsConstructor
@@ -47,6 +49,7 @@ 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
@@ -67,7 +70,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
writeMarker.onRequestStart(request);
var snapshot = RequestSnapshot.of(request);
var capture = new ChangeCapture();
return captureManager.prepare(exchange, snapshot, capture)
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))
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
signal -> {
@@ -75,12 +85,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
// 2xx 清零计数、其余累计,独立于下方审计记录决策
if (CaptureRule.isLoginAttempt(path, method)) {
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange));
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
loginAttempt.getAttemptedUsername());
}
operatorOf(ctx, path).subscribe(
username -> {
if (shouldRecord(path, username)) {
recorder.record(snapshot, capture, statusOf(exchange), username);
recorder.record(snapshot, capture, statusOf(exchange), username,
loginAttempt.getAttemptedUsername());
}
},
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });