feat: 登录失败告警通知(阈值窗口统计 + Webhook JSON 推送)
- 新增 alert 包:AlertSettings(alerts 配置组,归一校验)、AlertSettingProvider (60s TTL 缓存,同审计设置模式)、LoginFailureAlertService(阈值窗口状态机: 达阈值告警一次并重开窗口防轰炸,登录成功立即清零,2xx 成功/其余失败)、 AlertWebhookSender(JSON POST fire-and-forget,10s 超时,失败不重试仅记日志) - 捕获过滤器挂钩:POST /login 请求结束经 CaptureRule.isLoginAttempt 回调告警服务, 独立于审计开关;登录页 GET 与登出不触发 - 设置新增「告警通知」表单组(开关默认关、Webhook 地址、触发阈值、统计窗口) - 测试 +32(共 188 全绿):设置归一与 TTL 缓存、阈值窗口推进/告警防轰炸/成功清零/ 3xx 失败归类/降级路径、JDK HttpServer 真实 HTTP 推送与非 2xx/非法 URL 静默降级、 过滤器告警回调与过滤器行为测试更新 - 文档同步:设计文档 §6 标注 V2 已实现并补 §7 局限,双 README 功能/设置/技术说明
This commit is contained in:
+53
@@ -0,0 +1,53 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Duration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.plugin.ReactiveSettingFetcher;
|
||||
|
||||
/**
|
||||
* 告警设置的短 TTL 缓存读取(与审计设置 {@code AuditSettingProvider} 同款模式,技术方案 D6)。
|
||||
*
|
||||
* <p>开关变更最多延迟 1 分钟生效——告警为旁路功能,可接受。读取失败或未配置时
|
||||
* 静默回退默认值(关闭告警),绝不影响登录与审计主流程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AlertSettingProvider {
|
||||
|
||||
/** 缓存有效期(与审计设置缓存一致)。 */
|
||||
public static final Duration TTL = Duration.ofSeconds(60);
|
||||
|
||||
private final ReactiveSettingFetcher fetcher;
|
||||
|
||||
/** TTL 缓存条目;包内可见以便测试构造过期条目。 */
|
||||
record CacheEntry(AlertSettings value, long expireAtNanos) {
|
||||
boolean expiredAt(long nowNanos) {
|
||||
return nowNanos >= expireAtNanos;
|
||||
}
|
||||
}
|
||||
|
||||
volatile CacheEntry cache;
|
||||
|
||||
/**
|
||||
* 获取当前告警设置(TTL 内直接命中缓存)。
|
||||
*
|
||||
* <p>返回的 Mono 永不为空、永不报错:任何异常均回退默认值(告警关闭)。
|
||||
*/
|
||||
public Mono<AlertSettings> get() {
|
||||
var entry = cache;
|
||||
if (entry != null && !entry.expiredAt(System.nanoTime())) {
|
||||
return Mono.just(entry.value());
|
||||
}
|
||||
return fetcher.fetch(AlertSettings.GROUP, AlertSettings.class)
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to load alert settings, fall back to defaults", e);
|
||||
return Mono.just(AlertSettings.defaults());
|
||||
})
|
||||
.defaultIfEmpty(AlertSettings.defaults())
|
||||
.doOnNext(value -> cache = new CacheEntry(value, System.nanoTime() + TTL.toNanos()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
/**
|
||||
* 告警通知设置(存储于插件 ConfigMap 的 {@code alerts} 组,独立于审计设置组)。
|
||||
*
|
||||
* <p>取值经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值;
|
||||
* Webhook 地址非 http(s) 或为空时归一为 null(调用方静默跳过发送)。
|
||||
*/
|
||||
public record AlertSettings(Boolean enabled, String webhookUrl, Integer thresholdCount,
|
||||
Integer windowMinutes) {
|
||||
|
||||
/** ConfigMap 中的配置组名(settings.yaml 的告警通知表单组)。 */
|
||||
public static final String GROUP = "alerts";
|
||||
|
||||
/** 告警开关默认值:默认关闭,配置 Webhook 后显式开启(告警属可选旁路功能)。 */
|
||||
public static final boolean DEFAULT_ENABLED = false;
|
||||
|
||||
/** 默认触发阈值:统计窗口内登录失败次数。 */
|
||||
public static final int DEFAULT_THRESHOLD_COUNT = 5;
|
||||
|
||||
/** 默认统计窗口(分钟)。 */
|
||||
public static final int DEFAULT_WINDOW_MINUTES = 5;
|
||||
|
||||
public boolean enabledOrDefault() {
|
||||
return enabled != null && enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一 Webhook 地址:空白或非 http(s) 开头返回 null(不可用,调用方静默跳过),
|
||||
* 其余去除首尾空白后返回。
|
||||
*/
|
||||
public String webhookUrlOrDefault() {
|
||||
if (webhookUrl == null) {
|
||||
return null;
|
||||
}
|
||||
var trimmed = webhookUrl.trim();
|
||||
var lower = trimmed.toLowerCase();
|
||||
if (trimmed.isEmpty() || !(lower.startsWith("http://") || lower.startsWith("https://"))) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** 触发阈值:小于 1 视为非法回退默认。 */
|
||||
public int thresholdCountOrDefault() {
|
||||
if (thresholdCount == null || thresholdCount < 1) {
|
||||
return DEFAULT_THRESHOLD_COUNT;
|
||||
}
|
||||
return thresholdCount;
|
||||
}
|
||||
|
||||
/** 统计窗口(分钟):小于 1 视为非法回退默认。 */
|
||||
public int windowMinutesOrDefault() {
|
||||
if (windowMinutes == null || windowMinutes < 1) {
|
||||
return DEFAULT_WINDOW_MINUTES;
|
||||
}
|
||||
return windowMinutes;
|
||||
}
|
||||
|
||||
public static AlertSettings defaults() {
|
||||
return new AlertSettings(DEFAULT_ENABLED, null, DEFAULT_THRESHOLD_COUNT,
|
||||
DEFAULT_WINDOW_MINUTES);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
/**
|
||||
* 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。
|
||||
*
|
||||
* <p>fire-and-forget(产品设计原则 4):超时 10 秒后放弃,失败(网络错误、非 2xx 响应、
|
||||
* URL 非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
|
||||
*
|
||||
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
|
||||
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AlertWebhookSender {
|
||||
|
||||
/** 发送超时:告警为旁路功能,超时即放弃(不重试)。 */
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private final WebClient webClient;
|
||||
|
||||
public AlertWebhookSender() {
|
||||
this.webClient = WebClient.builder().build();
|
||||
}
|
||||
|
||||
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */
|
||||
public void send(String url, Map<String, Object> payload) {
|
||||
try {
|
||||
webClient.post()
|
||||
.uri(url)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.bodyValue(payload)
|
||||
.retrieve()
|
||||
.toBodilessEntity()
|
||||
.timeout(TIMEOUT)
|
||||
.subscribe(null, e -> log.warn("Failed to send alert webhook to {}", url, e));
|
||||
} catch (Exception e) {
|
||||
// URL 非法等同步异常同样静默降级,绝不影响调用方
|
||||
log.warn("Failed to initiate alert webhook to {}", url, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
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。
|
||||
*
|
||||
* <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 清零计数,失败累计告警)。
|
||||
* 任何失败静默降级,不影响调用方。
|
||||
*/
|
||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode) {
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
|
||||
settingProvider.get().subscribe(
|
||||
settings -> handle(settings, snapshot, success, 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, 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(), 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, Instant timestamp) {
|
||||
var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
|
||||
+ remoteIp + (userAgent != null && !userAgent.isBlank()
|
||||
? "(" + userAgent + ")" : "")
|
||||
+ "。可在 Console「操作审计」查看详情。";
|
||||
var data = new LinkedHashMap<String, Object>();
|
||||
data.put("failures", failures);
|
||||
data.put("windowMinutes", windowMinutes);
|
||||
data.put("remoteIp", remoteIp);
|
||||
data.put("userAgent", userAgent);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ public final class CaptureRule {
|
||||
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
|
||||
public static final String APIS_PREFIX = "/apis/";
|
||||
|
||||
/** 登录端点(告警通道唯一触发路径;登出与登录页 GET 不算登录尝试)。 */
|
||||
public static final String LOGIN_ENDPOINT = "/login";
|
||||
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
@@ -37,4 +40,13 @@ public final class CaptureRule {
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||
* 登录失败告警的触发条件——2xx 为登录成功,其余为失败;
|
||||
* 登录页 GET 与登出不算。
|
||||
*/
|
||||
public static boolean isLoginAttempt(String path, String method) {
|
||||
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -13,6 +13,7 @@ import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.context.ContextView;
|
||||
import run.halo.app.security.AfterSecurityWebFilter;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1)。
|
||||
@@ -31,6 +32,10 @@ import run.halo.app.security.AfterSecurityWebFilter;
|
||||
* <p>系统内部变更(产品设计 V2):所有写方法请求(含未被捕获规则命中的 {@code /api/**}
|
||||
* 核心模型与登录端点)均经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
|
||||
* Webhook;与审计开关相互独立。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -42,6 +47,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
private final LoginFailureAlertService loginFailureAlertService;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
@@ -66,6 +72,11 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 2xx 清零计数、其余累计,独立于下方审计记录决策
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange));
|
||||
}
|
||||
operatorOf(ctx, path).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
|
||||
Reference in New Issue
Block a user