- 新增 LoginAttemptCapture:为登录端点单独缓存请求体(表单/JSON 双形态, Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制仅提取 username,兜底经现有敏感字段脱敏规则(ChangeDiffEngine)复核, 密码绝不提取落库;任何失败静默降级,不影响登录主流程 - AuditLogSpec 新增 spec.attemptedUsername(不建索引),AuditRecorder 透传落库 - 告警负载 data 新增 attemptedUsername,content 增加尝试的账号段 - CSV 导出新增"尝试用户"列(操作者之后) - 详情抽屉展示"尝试用户"(仅登录请求落库时显示) - 更新 README(功能/告警负载示例/已知局限移除对应条目/技术说明)
128 lines
5.7 KiB
Java
128 lines
5.7 KiB
Java
package run.halo.operationaudit.alert;
|
||
|
||
import java.time.Duration;
|
||
import java.time.Instant;
|
||
import java.util.LinkedHashMap;
|
||
import java.util.Map;
|
||
import lombok.RequiredArgsConstructor;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.stereotype.Component;
|
||
import run.halo.operationaudit.audit.RequestSnapshot;
|
||
|
||
/**
|
||
* 登录失败告警(产品设计 V2+「告警通知」):统计窗口内登录失败达到阈值时向 Webhook
|
||
* 推送一次 JSON 告警。
|
||
*
|
||
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
||
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
|
||
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
|
||
*
|
||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||
*
|
||
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
|
||
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
|
||
*/
|
||
@Slf4j
|
||
@Component
|
||
@RequiredArgsConstructor
|
||
public class LoginFailureAlertService {
|
||
|
||
private final AlertSettingProvider settingProvider;
|
||
private final AlertWebhookSender sender;
|
||
|
||
private final Object stateLock = new Object();
|
||
|
||
/** 阈值窗口状态(窗口起点与累计失败数);包内可见以便测试直接构造状态。 */
|
||
Instant windowStart;
|
||
int failureCount;
|
||
|
||
/**
|
||
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
|
||
* 任何失败静默降级,不影响调用方。
|
||
*
|
||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||
* 提取失败为 null)
|
||
*/
|
||
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, attemptedUsername, Instant.now()),
|
||
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
||
snapshot.getFullPath(), e));
|
||
}
|
||
|
||
/**
|
||
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。
|
||
* handle 包内可见以便测试直接驱动窗口推进。
|
||
*/
|
||
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
|
||
String attemptedUsername, Instant now) {
|
||
try {
|
||
if (!settings.enabledOrDefault()) {
|
||
return;
|
||
}
|
||
var url = settings.webhookUrlOrDefault();
|
||
if (url == null) {
|
||
return;
|
||
}
|
||
var window = Duration.ofMinutes(settings.windowMinutesOrDefault());
|
||
int failures;
|
||
synchronized (stateLock) {
|
||
if (success) {
|
||
// 登录成功立即清零:零星输错密码不应累积
|
||
windowStart = null;
|
||
failureCount = 0;
|
||
return;
|
||
}
|
||
if (windowStart == null || now.isAfter(windowStart.plus(window))) {
|
||
windowStart = now;
|
||
failureCount = 0;
|
||
}
|
||
failureCount++;
|
||
if (failureCount < settings.thresholdCountOrDefault()) {
|
||
return;
|
||
}
|
||
failures = failureCount;
|
||
// 达到阈值:触发告警并重开窗口,下次告警需再次达到阈值(防轰炸)
|
||
windowStart = now;
|
||
failureCount = 0;
|
||
}
|
||
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
|
||
snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
|
||
} catch (Exception e) {
|
||
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
|
||
log.warn("Failed to handle login failure alert for {}",
|
||
snapshot.getFullPath(), e);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 组装通用 JSON 告警负载:type/title/content 供消息类接收方直接展示,
|
||
* data 供程序化消费方取结构化字段。
|
||
*/
|
||
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp,
|
||
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", "操作审计告警:登录失败");
|
||
payload.put("content", content);
|
||
payload.put("timestamp", timestamp.toString());
|
||
payload.put("data", data);
|
||
return payload;
|
||
}
|
||
}
|