fix: 登录失败按 Halo 登录端点契约判定,不再被 200/302 掩盖
Halo 2.26 登录端点表单提交的成功与失败均为 302 重定向(成功 → /uc, 失败 → /login?error=...&method=...),失败回显页 GET /login?error=... 渲染 HTTP 200;旧逻辑按「2xx 即成功」判定导致: - 审计列表中失败登录显示绿色 200/302,误读为登录成功 - 登录失败告警把表单成功登录也计为失败,成功清零失效、可误报警 修复: - 新增 LoginOutcome 纯函数:2xx 成功;3xx 以重定向目标查询串是否含 error 参数判定(含无值形式);其余(401、状态码缺失)失败 - 失败的登录尝试与失败回显(GET /login?error=...)落库标注语义动作 login-failure(spec.action),HTTP 状态码仍如实记录 - Console 列表/详情与 CSV:登录失败记录显示红色「失败」而非裸状态码, 语义动作筛选与「结果=失败」筛选均命中登录失败记录 - LoginFailureAlertService 改由过滤器传入 LoginOutcome 判定结果, 成功清零、失败累计恢复正常 - 历史局限:升级前落库的表单登录失败(302)无法由路径重新推导, 仍按登录展示;升级后新记录捕获时标注,不再有此局限 测试:后端 265 例、前端 60 例全部通过;文档与 README 同步更新。
This commit is contained in:
+10
-6
@@ -15,8 +15,10 @@ import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
* 推送一次 JSON 告警。
|
||||
*
|
||||
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
||||
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
|
||||
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
|
||||
* 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入——
|
||||
* 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分,
|
||||
* 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值);
|
||||
* 窗口过期同样重开,无失败时不累计。
|
||||
*
|
||||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||||
@@ -40,15 +42,17 @@ public class LoginFailureAlertService {
|
||||
int failureCount;
|
||||
|
||||
/**
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
|
||||
* 任何失败静默降级,不影响调用方。
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功清零计数,失败累计告警)。
|
||||
* 成败由调用方(捕获过滤器)经 {@code LoginOutcome} 判定后传入,本服务不做
|
||||
* 状态码推断。任何失败静默降级,不影响调用方。
|
||||
*
|
||||
* @param success 登录是否成功(表单登录 302 重定向目标含 error 参数或
|
||||
* 响应 4xx/5xx 为失败;2xx 与成功重定向为成功)
|
||||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||||
* 提取失败为 null)
|
||||
*/
|
||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
|
||||
public void onLoginResult(RequestSnapshot snapshot, boolean success,
|
||||
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 {}",
|
||||
|
||||
+7
-4
@@ -103,8 +103,11 @@ public class AuditLogCsvExporter {
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
|
||||
// 结果语义与前端一致:登录失败标注(HTTP 状态码可能为 200/302——失败回显页
|
||||
// 渲染/失败重定向)一律失败,其余 2xx/3xx 成功
|
||||
var failedLogin = OperationDescription.LOGIN_FAILURE_ACTION.equals(spec.getAction());
|
||||
var success = !failedLogin && statusCode != null && statusCode >= 200
|
||||
&& statusCode < 400;
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
@@ -113,8 +116,8 @@ public class AuditLogCsvExporter {
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
escape(OperationDescription.describe(
|
||||
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
||||
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||
escape(OperationDescription.describe(spec)),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
|
||||
+9
-3
@@ -56,16 +56,22 @@ final class AuditLogFilters {
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
var loginFailure = Queries.equal("spec.action",
|
||||
OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
conditions.add(Queries.not(loginFailure));
|
||||
}
|
||||
case "failure" -> conditions.add(
|
||||
Queries.greaterThan("spec.statusCode", "400", true));
|
||||
case "failure" -> conditions.add(Queries.or(
|
||||
Queries.greaterThan("spec.statusCode", "400", true),
|
||||
loginFailure));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
|
||||
+18
-9
@@ -38,9 +38,13 @@ public class AuditRecorder {
|
||||
*
|
||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
|
||||
* 302 重定向且目标含 error 参数)或失败回显
|
||||
* (GET /login?error=...,HTTP 200),语义动作标注
|
||||
* login-failure;其余请求为 false
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
@@ -48,19 +52,20 @@ public class AuditRecorder {
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername,
|
||||
loginFailed);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
@@ -147,7 +152,7 @@ public class AuditRecorder {
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
@@ -156,11 +161,15 @@ public class AuditRecorder {
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
|
||||
spec.setAction(OperationDescription.actionOf(
|
||||
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
|
||||
// 登录失败(POST /login 失败或 GET /login?error=... 失败回显)标注
|
||||
// login-failure——回显页 HTTP 200 无法由路径重新推导,必须落库标注
|
||||
spec.setAction(loginFailed ? OperationDescription.LOGIN_FAILURE_ACTION
|
||||
: OperationDescription.actionOf(
|
||||
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||
spec.setPath(snapshot.getFullPath());
|
||||
// 状态码如实记录(失败回显页为 200、表单登录失败为 302),登录成败看语义动作标注
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
|
||||
@@ -43,8 +43,8 @@ public final class CaptureRule {
|
||||
|
||||
/**
|
||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||
* 登录失败告警的触发条件——2xx 为登录成功,其余为失败;
|
||||
* 登录页 GET 与登出不算。
|
||||
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||
* 302 重定向,不能只看状态码);登录页 GET 与登出不算。
|
||||
*/
|
||||
public static boolean isLoginAttempt(String path, String method) {
|
||||
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 登录结果判定(纯函数):Halo 2.26 登录端点的成功/失败在 HTTP 层并非「非 2xx 即失败」——
|
||||
* 表单提交的成功与失败都以 302 重定向收尾(成功 → {@code /uc} 或 2FA 页;失败 →
|
||||
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
|
||||
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
|
||||
* 因此登录结果须结合重定向目标判定,不能只看状态码。
|
||||
*/
|
||||
public final class LoginOutcome {
|
||||
|
||||
private LoginOutcome() {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST {@code /login} 的登录结果判定(Halo 2.26 登录端点契约):
|
||||
*
|
||||
* <ul>
|
||||
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
|
||||
* <li>3xx → 重定向目标查询串含 {@code error} 参数 → 失败(表单登录失败统一重定向
|
||||
* 到 {@code /login?error=invalid-credential&method=...} 等,含无值的
|
||||
* {@code /login?error&method=...});其余重定向目标(成功 → {@code /uc}、
|
||||
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
|
||||
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public static boolean isFailure(Integer statusCode, URI location) {
|
||||
if (statusCode == null) {
|
||||
return true;
|
||||
}
|
||||
if (statusCode >= 200 && statusCode < 300) {
|
||||
return false;
|
||||
}
|
||||
if (statusCode >= 300 && statusCode < 400) {
|
||||
return location != null && hasErrorParam(location.getRawQuery());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败回显判定:{@code GET /login} 且查询串含 {@code error} 参数。
|
||||
* 登录失败后 Halo 重定向到带 error 参数的登录页,浏览器随后渲染该页(HTTP 200);
|
||||
* 该请求是失败登录的回显而非独立操作,审计记录须标注登录失败而非「登录成功 200」。
|
||||
*/
|
||||
public static boolean isFailureEcho(String fullPath) {
|
||||
if (fullPath == null) {
|
||||
return false;
|
||||
}
|
||||
var queryStart = fullPath.indexOf('?');
|
||||
if (queryStart < 0 || !"/login".equals(fullPath.substring(0, queryStart))) {
|
||||
return false;
|
||||
}
|
||||
return hasErrorParam(fullPath.substring(queryStart + 1));
|
||||
}
|
||||
|
||||
/** 查询串是否含 {@code error} 参数(可为无值形式 {@code error})。 */
|
||||
private static boolean hasErrorParam(String query) {
|
||||
if (query == null || query.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Arrays.stream(query.split("&"))
|
||||
.map(pair -> {
|
||||
var idx = pair.indexOf('=');
|
||||
return idx < 0 ? pair : pair.substring(0, idx);
|
||||
})
|
||||
.anyMatch("error"::equals);
|
||||
}
|
||||
}
|
||||
+33
-7
@@ -34,10 +34,15 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
|
||||
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
|
||||
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||
* {@code error} 参数区分,不能只看状态码)。尝试的用户名(功能评审 P0-1)由
|
||||
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
|
||||
* {@code spec.attemptedUsername} 并进入告警负载。
|
||||
*
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||
* 与筛选;HTTP 状态码仍如实记录。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -82,17 +87,21 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 2xx 清零计数、其余累计,独立于下方审计记录决策
|
||||
var statusCode = statusOf(exchange);
|
||||
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
|
||||
// 以重定向目标是否含 error 参数区分;GET /login?error=... 为失败回显
|
||||
var loginFailed = isLoginFailed(path, method, statusCode, exchange, snapshot);
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 成功清零计数、失败累计,独立于下方审计记录决策
|
||||
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
|
||||
loginAttempt.getAttemptedUsername());
|
||||
}
|
||||
operatorOf(ctx, path).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, capture, statusOf(exchange), username,
|
||||
loginAttempt.getAttemptedUsername());
|
||||
recorder.record(snapshot, capture, statusCode, username,
|
||||
loginAttempt.getAttemptedUsername(), loginFailed);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||
@@ -132,6 +141,23 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败判定(LoginOutcome):POST {@code /login} 按状态码 + 重定向目标判定
|
||||
* (表单登录成败均为 302,以 Location 是否含 {@code error} 参数区分);
|
||||
* 其余请求仅登录失败回显({@code GET /login?error=...},HTTP 200)判为失败。
|
||||
*/
|
||||
private static boolean isLoginFailed(String path, String method, Integer statusCode,
|
||||
ServerWebExchange exchange, RequestSnapshot snapshot) {
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
return LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
}
|
||||
if (CaptureRule.isAuthEndpoint(path) && "GET".equals(method)) {
|
||||
return LoginOutcome.isFailureEcho(snapshot.getFullPath());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
|
||||
static boolean isAnonymous(Authentication authentication) {
|
||||
return authentication == null || !StringUtils.hasText(authentication.getName())
|
||||
|
||||
+21
@@ -64,9 +64,17 @@ final class OperationDescription {
|
||||
Map.entry("password", "password"),
|
||||
Map.entry("resetpassword", "resetpassword"));
|
||||
|
||||
/**
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
*/
|
||||
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||
Map.entry("login", "登录"),
|
||||
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||
Map.entry("logout", "登出"),
|
||||
Map.entry("auth", "认证操作"),
|
||||
Map.entry("password", "修改密码"),
|
||||
@@ -149,6 +157,19 @@ final class OperationDescription {
|
||||
return method + resourceLabel(resourceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||
*/
|
||||
static String describe(AuditLogSpec spec) {
|
||||
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
return describe(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||
}
|
||||
|
||||
private static String resourceLabel(String resourceType) {
|
||||
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user