fix: 登录页访问不再记成「登录成功」——认证端点只记录 POST,登录成败以响应确认为准
现场反馈:审计列表「没有失败,全是成功,登录失败也显示成功」。在 Halo 2.26.1 上 复现(afda8d0 构建):GET /login、GET /login?authentication_required 只是打开登录页 (HTTP 200),却被记成「未知用户 · 登录 200」,列表里看起来全是登录成功;POST /login 本身的成败判定是对的,但被这些记录淹没。 - 捕获:AuthEndpointAuditWebFilter 只记录 POST /login(登录尝试)与 POST /logout (登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出 确认页)原样透传不记录(CaptureRule.isAuthOperation) - 判定:LoginOutcome 只有响应明确确认才算成功——302 跳回登录页(含 error 参数或 路径即 /login)、缺失 Location、4xx/5xx 一律判失败;移除失败回显页判定 - 结果语义:新增 AuditResult(成功 / 失败 / 页面访问),结果筛选、CSV 导出与前端 resultBadge 共用同一规则;登录成功显示「成功」,与「失败」对称 - 历史数据:升级前落库的登录页访问记录(GET,标注 login/logout)展示与导出为 「访问登录页/登出页」且不计成败,结果筛选与「登录/登出」语义动作筛选均排除; 落库标注不改写 - demo 同步同一套规则;README 与设计/技术文档同步 测试:后端 286、UI 74、demo 61 全过;真实 Halo 2.26.1 升级场景联调记录见测试报告
This commit is contained in:
@@ -9,8 +9,14 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
|
||||
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
|
||||
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出),登录请求白名单提取尝试的用户名落库
|
||||
(`spec.attemptedUsername`,密码等其余字段绝不落库,登录失败时操作者记"未知用户")。
|
||||
另捕获认证操作 `POST /login`、`POST /logout`(登录成功/失败/登出),登录请求白名单
|
||||
提取尝试的用户名落库(`spec.attemptedUsername`,密码等其余字段绝不落库,登录时操作者
|
||||
记"未知用户")。登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出
|
||||
确认页)不是操作,不记录。
|
||||
- **登录成败标注**:表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定
|
||||
(`LoginOutcome`,只有响应明确确认才算成功);列表/详情显示「成功」/红色「失败」,
|
||||
CSV 结果列同理。升级前落库的登录页访问记录(`GET /login`,曾显示成绿色「登录 200」)
|
||||
纠正为灰色「—」的「访问登录页」,不计成败。
|
||||
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
|
||||
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
|
||||
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
|
||||
@@ -133,9 +139,9 @@ Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配
|
||||
## 技术说明
|
||||
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证操作 `POST /login`、
|
||||
`POST /logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器
|
||||
命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证操作请求,
|
||||
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||
Extension + 索引查询,全程响应式非阻塞。
|
||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||
|
||||
+5
-7
@@ -103,11 +103,6 @@ public class AuditLogCsvExporter {
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端一致:登录失败标注(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()),
|
||||
@@ -116,10 +111,13 @@ public class AuditLogCsvExporter {
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||
// 优先落库语义动作(含登录失败标注与页面访问纠正),历史记录回退
|
||||
// method/path 现场推导
|
||||
escape(OperationDescription.describe(spec)),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
// 结果语义与前端一致(AuditResult):登录失败标注一律失败(HTTP 状态码
|
||||
// 可能是 302/200),认证端点的页面访问记录(历史 GET)不计成败,其余按状态码
|
||||
escape(AuditResult.of(spec).label()),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
escape(spec.getRemoteIp()),
|
||||
escape(spec.getUserAgent()));
|
||||
|
||||
+28
-6
@@ -25,6 +25,22 @@ final class AuditLogFilters {
|
||||
static final Set<String> FILTERABLE_FIELDS = Set.of("spec.username", "spec.resourceType",
|
||||
"spec.method", "spec.action", "spec.statusCode");
|
||||
|
||||
/**
|
||||
* 登录/登出操作的语义动作键:按其筛选时排除页面访问记录——升级前落库的
|
||||
* GET /login、GET /logout 带同样的标注,但展示为「访问登录页/登出页」。
|
||||
*/
|
||||
private static final Set<String> AUTH_OPERATION_ACTIONS = Set.of("login", "logout");
|
||||
|
||||
/**
|
||||
* 页面访问记录({@link OperationDescription#isAuthPageVisit} 的索引查询形态):
|
||||
* 非 POST 的 {@code /login}、{@code /logout} 请求(含查询串)。不是操作,不计成败。
|
||||
*/
|
||||
private static final Condition PAGE_VISIT = Queries.and(
|
||||
Queries.notEqual("spec.method", "POST"),
|
||||
Queries.or(
|
||||
Queries.startsWith("spec.path", "/login"),
|
||||
Queries.startsWith("spec.path", "/logout")));
|
||||
|
||||
private AuditLogFilters() {
|
||||
}
|
||||
|
||||
@@ -44,7 +60,11 @@ final class AuditLogFilters {
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
throw new IllegalArgumentException("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
var condition = Queries.equal(field, value);
|
||||
if ("spec.action".equals(field) && AUTH_OPERATION_ACTIONS.contains(value)) {
|
||||
condition = Queries.and(condition, Queries.not(PAGE_VISIT));
|
||||
}
|
||||
conditions.add(condition);
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
@@ -56,9 +76,9 @@ final class AuditLogFilters {
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||
// 结果筛选(与 AuditResult 同一规则):success = 2xx/3xx 且非登录失败标注、
|
||||
// 非页面访问;failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,
|
||||
// 仅凭状态码识别不出)或 4xx/5xx(页面访问除外)。页面访问记录不计成败
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
var loginFailure = Queries.equal("spec.action",
|
||||
@@ -68,10 +88,12 @@ final class AuditLogFilters {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
conditions.add(Queries.not(loginFailure));
|
||||
conditions.add(Queries.not(PAGE_VISIT));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.or(
|
||||
Queries.greaterThan("spec.statusCode", "400", true),
|
||||
loginFailure));
|
||||
loginFailure,
|
||||
Queries.and(Queries.greaterThan("spec.statusCode", "400", true),
|
||||
Queries.not(PAGE_VISIT))));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
|
||||
+8
-3
@@ -27,8 +27,10 @@ public class AuditLogSpec {
|
||||
|
||||
/**
|
||||
* 语义动作键(语义动作标注,产品设计 V2):捕获时由 method/path 推导落库
|
||||
* (如 login/logout/create/update/delete/publish/restore),注册索引后支持
|
||||
* 按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导)。
|
||||
* (如 login/logout/create/update/delete/publish/login-failure,可空),注册索引后
|
||||
* 支持按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导);
|
||||
* 升级前落库的登录页访问记录(GET,现已不再记录)带 login/logout 标注,
|
||||
* 展示时按方法纠正为页面访问。
|
||||
*/
|
||||
private String action;
|
||||
|
||||
@@ -41,7 +43,10 @@ public class AuditLogSpec {
|
||||
/** 完整请求路径(资源语义解析的兜底,保证完整性)。 */
|
||||
private String path;
|
||||
|
||||
/** 响应状态码(结果:2xx 成功,其余失败)。 */
|
||||
/**
|
||||
* 响应状态码,如实记录。结果语义见 {@link AuditResult}:不能只看状态码——表单登录
|
||||
* 成败均为 302,登录失败靠语义动作 {@code login-failure} 标注识别。
|
||||
*/
|
||||
private Integer statusCode;
|
||||
|
||||
/** 来源 IP。 */
|
||||
|
||||
+5
-6
@@ -39,9 +39,8 @@ 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
|
||||
* 302 重定向且回跳登录页),语义动作标注 login-failure;
|
||||
* 其余请求为 false
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
@@ -162,14 +161,14 @@ public class AuditRecorder {
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
|
||||
// 登录失败(POST /login 失败或 GET /login?error=... 失败回显)标注
|
||||
// login-failure——回显页 HTTP 200 无法由路径重新推导,必须落库标注
|
||||
// 登录失败(POST /login 回跳登录页或 4xx/5xx)标注 login-failure——
|
||||
// 表单登录失败的 HTTP 状态码与成功相同(302),结果只能靠落库标注区分
|
||||
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),登录成败看语义动作标注
|
||||
// 状态码如实记录(表单登录成败均为 302),登录成败看语义动作标注
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
/**
|
||||
* 审计记录的结果语义(纯函数):结果筛选({@link AuditLogFilters})、CSV 导出
|
||||
* ({@link AuditLogCsvExporter})与前端 {@code ui/src/utils/audit.ts} 的结果徽标
|
||||
* 共用同一规则——什么算成功、什么算失败,只能有一个定义。
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #FAILURE}:登录失败(语义动作 {@code login-failure},HTTP 状态码可能是
|
||||
* 302/200);其余按状态码判定,4xx/5xx 为失败;</li>
|
||||
* <li>{@link #PAGE_VISIT}:认证端点的页面访问(升级前落库的 GET /login、GET /logout
|
||||
* 历史记录)——不是操作,不计成败;</li>
|
||||
* <li>{@link #SUCCESS}:其余状态码 2xx/3xx。</li>
|
||||
* </ul>
|
||||
*/
|
||||
enum AuditResult {
|
||||
SUCCESS("成功"),
|
||||
FAILURE("失败"),
|
||||
PAGE_VISIT("页面访问");
|
||||
|
||||
/** 导出 CSV「结果」列的中文值。 */
|
||||
private final String label;
|
||||
|
||||
AuditResult(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
static AuditResult of(AuditLogSpec spec) {
|
||||
if (OperationDescription.LOGIN_FAILURE_ACTION.equals(
|
||||
OperationDescription.semanticAction(spec))) {
|
||||
return FAILURE;
|
||||
}
|
||||
if (OperationDescription.isAuthPageVisit(spec.getMethod(), spec.getPath())) {
|
||||
return PAGE_VISIT;
|
||||
}
|
||||
var statusCode = spec.getStatusCode();
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
? SUCCESS : FAILURE;
|
||||
}
|
||||
|
||||
String label() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
+22
-33
@@ -1,6 +1,6 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthOperation;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isLoginAttempt;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -13,16 +13,21 @@ import run.halo.app.security.BeforeSecurityWebFilter;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 认证端点({@code /login}、{@code /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||
* 认证操作({@code POST /login}、{@code POST /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||
*
|
||||
* <p>以 {@link BeforeSecurityWebFilter} 扩展点注册:位于 Security 过滤链最前
|
||||
* ({@code SecurityWebFiltersOrder.FIRST})。原先认证端点由
|
||||
* {@code AfterSecurityWebFilter} 扩展点注册的 {@link OperationAuditWebFilter} 捕获,
|
||||
* 但该扩展点位于认证环节之后——表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
|
||||
* 请求后直接完成 302 响应、不再向下游传递,POST /login 与 POST /logout 永远到不了
|
||||
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证端点整体
|
||||
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证操作整体
|
||||
* 移交本过滤器,在 Security 链之前承接捕获与记录。
|
||||
*
|
||||
* <p>只记录认证操作本身:{@code POST /login} 是登录尝试,{@code POST /logout} 是登出。
|
||||
* 登录/登出页面的 GET 访问(打开登录页、匿名访问被弹回登录页、登录失败后的回显、
|
||||
* 登出确认页)原样透传、不记录——它们只是渲染页面(HTTP 200),落库会显示成
|
||||
* 「未知用户 · 登录 · 200」,看起来像登录成功,真正的成败反而被淹没(现场实测反馈)。
|
||||
*
|
||||
* <p>操作者归属:Security 链最前无认证上下文(SecurityContext 由链内更晚位置的
|
||||
* ReactorContextWebFilter 写入订阅上下文,对链首过滤器不可见),统一记
|
||||
* {@link AuditLogSpec#UNKNOWN_USERNAME 未知用户}(既有兜底路径);登录尝试的账号
|
||||
@@ -30,13 +35,12 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* 并进入告警负载(功能评审 P0-1),账号归属信息不受影响。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||
* {@code error} 参数区分,不能只看状态码)。
|
||||
* 回调给 {@link LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否
|
||||
* 跳回登录页区分,不能只看状态码)。
|
||||
*
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||
* 与筛选;HTTP 状态码仍如实记录。
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):失败的 POST {@code /login} 落库
|
||||
* 标注登录失败,供列表红色标记与筛选;HTTP 状态码仍如实记录。
|
||||
*
|
||||
* <p>任何失败均静默降级(记录器与告警服务内部兜底),绝不影响登录主流程(设计原则 4)。
|
||||
*/
|
||||
@@ -54,16 +58,17 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
var request = exchange.getRequest();
|
||||
var path = request.getPath().value();
|
||||
var method = request.getMethod().name();
|
||||
if (!isAuthEndpoint(path)) {
|
||||
// 非 /login、/logout 一律原样透传:不触碰请求体、不读会话,零附加开销
|
||||
if (!isAuthOperation(path, method)) {
|
||||
// 登录/登出页面的 GET 访问等非认证操作一律原样透传:不触碰请求体、不记录
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var loginAttempt = new LoginAttempt();
|
||||
var loginAttempted = isLoginAttempt(path, method);
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 登出与登录页 GET 原样透传
|
||||
var bodyPrepared = isLoginAttempt(path, method)
|
||||
// 登出原样透传
|
||||
var bodyPrepared = loginAttempted
|
||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||
: Mono.just(exchange);
|
||||
return bodyPrepared
|
||||
@@ -72,9 +77,10 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
writeMarker.onRequestComplete(request);
|
||||
var statusCode = statusOf(exchange);
|
||||
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
|
||||
// 以重定向目标是否含 error 参数区分;GET /login?error=... 为失败回显
|
||||
var loginFailed = isLoginFailed(path, method, statusCode, exchange, snapshot);
|
||||
if (isLoginAttempt(path, method)) {
|
||||
// 以重定向目标是否跳回登录页区分;登出不存在登录成败
|
||||
var loginFailed = loginAttempted && LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
if (loginAttempted) {
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 成功清零计数、失败累计,独立于审计记录
|
||||
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
|
||||
@@ -90,21 +96,4 @@ public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
|
||||
var status = exchange.getResponse().getStatusCode();
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败判定(LoginOutcome):POST {@code /login} 按状态码 + 重定向目标判定
|
||||
* (表单登录成败均为 302,以 Location 是否含 {@code error} 参数区分);
|
||||
* 登出与登录页 GET 仅失败回显({@code GET /login?error=...},HTTP 200)判为失败。
|
||||
*/
|
||||
private static boolean isLoginFailed(String path, String method, Integer statusCode,
|
||||
ServerWebExchange exchange, RequestSnapshot snapshot) {
|
||||
if (isLoginAttempt(path, method)) {
|
||||
return LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
}
|
||||
if ("GET".equals(method)) {
|
||||
return LoginOutcome.isFailureEcho(snapshot.getFullPath());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+25
-8
@@ -9,13 +9,18 @@ import java.util.Set;
|
||||
* <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
|
||||
* 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
|
||||
* 可获得认证用户上下文);</li>
|
||||
* <li>认证端点 {@code /login}、{@code /logout} 精确匹配({@link #isAuthEndpoint},
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 消费)——登录端点不在 /apis/** 下,且
|
||||
* 表单登录/登出过滤器命中请求后直接完成响应、不再向下游传递,链尾的
|
||||
* AfterSecurityWebFilter 永远看不到(P0 缺陷实测),因此必须在 Security 链之前
|
||||
* 独立捕获。</li>
|
||||
* <li>认证操作 {@code POST /login}(登录尝试)与 {@code POST /logout}(登出)精确匹配
|
||||
* ({@link #isAuthOperation},由 {@link AuthEndpointAuditWebFilter} 消费)——
|
||||
* 登录/登出端点不在 /apis/** 下,且表单登录/登出过滤器命中请求后直接完成响应、
|
||||
* 不再向下游传递,链尾的 AfterSecurityWebFilter 永远看不到(P0 缺陷实测),
|
||||
* 因此必须在 Security 链之前独立捕获。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录/登出页面的 GET 访问不是操作,不记录({@link #isAuthEndpoint} 仅用于路径归类):
|
||||
* 打开登录页、匿名访问被弹回登录页({@code /login?authentication_required})、登录失败
|
||||
* 后的回显({@code /login?error=...})、登出确认页都只是渲染页面(HTTP 200),若落库
|
||||
* 会显示成「未知用户 · 登录 · 200」,看起来像登录成功,而真正的登录尝试是 POST /login。
|
||||
*
|
||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||
*/
|
||||
public final class CaptureRule {
|
||||
@@ -24,16 +29,19 @@ public final class CaptureRule {
|
||||
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
|
||||
public static final String APIS_PREFIX = "/apis/";
|
||||
|
||||
/** 登录端点(告警通道唯一触发路径;登出与登录页 GET 不算登录尝试)。 */
|
||||
/** 登录端点(告警通道唯一触发路径;登录页 GET 不算登录尝试)。 */
|
||||
public static final String LOGIN_ENDPOINT = "/login";
|
||||
|
||||
/** 登出端点(POST 为登出操作;GET 为登出确认页)。 */
|
||||
public static final String LOGOUT_ENDPOINT = "/logout";
|
||||
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否命中捕获规则。path 为不含查询串的请求路径。
|
||||
*
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证端点由 {@link #isAuthEndpoint} 单独判定、
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证操作由 {@link #isAuthOperation} 单独判定、
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
|
||||
* 互不重叠,不会重复记录。
|
||||
*/
|
||||
@@ -44,11 +52,20 @@ public final class CaptureRule {
|
||||
return method != null && WRITE_METHODS.contains(method);
|
||||
}
|
||||
|
||||
/** 是否为登录/登出端点(由 {@link AuthEndpointAuditWebFilter} 捕获)。 */
|
||||
/** 是否为登录/登出端点(仅用于路径归类,不代表需要记录)。 */
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证操作(由 {@link AuthEndpointAuditWebFilter} 捕获):{@code POST /login}
|
||||
* 与 {@code POST /logout}。登录/登出页面的 GET 访问不是操作,不记录。
|
||||
*/
|
||||
public static boolean isAuthOperation(String path, String method) {
|
||||
return isLoginAttempt(path, method)
|
||||
|| "POST".equals(method) && LOGOUT_ENDPOINT.equals(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||
|
||||
+15
-21
@@ -9,9 +9,15 @@ import java.util.Arrays;
|
||||
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
|
||||
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
|
||||
* 因此登录结果须结合重定向目标判定,不能只看状态码。
|
||||
*
|
||||
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把失败
|
||||
* 登录记成成功,远比把异常响应记成失败更糟。
|
||||
*/
|
||||
public final class LoginOutcome {
|
||||
|
||||
/** 登录页路径:重定向回登录页即表示没有登录成功。 */
|
||||
private static final String LOGIN_PAGE_PATH = "/login";
|
||||
|
||||
private LoginOutcome() {
|
||||
}
|
||||
|
||||
@@ -20,9 +26,9 @@ public final class LoginOutcome {
|
||||
*
|
||||
* <ul>
|
||||
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
|
||||
* <li>3xx → 重定向目标查询串含 {@code error} 参数 → 失败(表单登录失败统一重定向
|
||||
* 到 {@code /login?error=invalid-credential&method=...} 等,含无值的
|
||||
* {@code /login?error&method=...});其余重定向目标(成功 → {@code /uc}、
|
||||
* <li>3xx → 重定向目标跳回登录页(查询串含 {@code error} 参数,如
|
||||
* {@code /login?error=invalid-credential&method=...},或路径就是 {@code /login})
|
||||
* 或缺失 Location → 失败;其余重定向目标(成功 → {@code /uc}、
|
||||
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
|
||||
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
|
||||
* </ul>
|
||||
@@ -35,29 +41,17 @@ public final class LoginOutcome {
|
||||
return false;
|
||||
}
|
||||
if (statusCode >= 300 && statusCode < 400) {
|
||||
return location != null && hasErrorParam(location.getRawQuery());
|
||||
// 跳回登录页必然是失败:Halo 2.26 的四种失败重定向均带 error 参数,
|
||||
// 无参跳回登录页同样不可能是登录成功(成功只会去 /uc、已保存的原请求或 2FA 页)
|
||||
return location == null
|
||||
|| LOGIN_PAGE_PATH.equals(location.getPath())
|
||||
|| 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) {
|
||||
static boolean hasErrorParam(String query) {
|
||||
if (query == null || query.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
+63
-14
@@ -12,10 +12,10 @@ import java.util.Map;
|
||||
* 展示/导出由 {@link #describe} 推导中文短语,历史记录(无 action 字段)同样按
|
||||
* method/path 现场推导,不受影响。
|
||||
*
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code describeOperation}
|
||||
* 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS / SEGMENT_ACTIONS / ACTION_PHRASES /
|
||||
* ACTION_VERBS 映射与子动作解析规则),两处需同步修改。未识别的子动作回退为
|
||||
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code semanticAction} /
|
||||
* {@code describeOperation} 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS /
|
||||
* SEGMENT_ACTIONS / ACTION_PHRASES / ACTION_VERBS 映射与子动作解析规则),两处需同步修改。
|
||||
* 未识别的子动作回退为「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
final class OperationDescription {
|
||||
|
||||
@@ -65,17 +65,28 @@ final class OperationDescription {
|
||||
Map.entry("resetpassword", "resetpassword"));
|
||||
|
||||
/**
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向跳回登录页或 4xx/5xx)落库
|
||||
* 标注,供列表红色标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
* 升级前落库的失败回显页(GET {@code /login?error=...},HTTP 200)带同一标注。
|
||||
*/
|
||||
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||
|
||||
/**
|
||||
* 登录页访问语义动作键:GET {@code /login}(打开登录页、被弹回登录页、失败回显)。
|
||||
* 仅升级前落库的历史记录会出现——页面访问不是操作,现已不记录。
|
||||
*/
|
||||
static final String LOGIN_PAGE_ACTION = "login-page";
|
||||
|
||||
/** 登出页访问语义动作键:GET {@code /logout}(登出确认页),仅升级前的历史记录。 */
|
||||
static final String LOGOUT_PAGE_ACTION = "logout-page";
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||
Map.entry("login", "登录"),
|
||||
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||
Map.entry("logout", "登出"),
|
||||
Map.entry(LOGIN_PAGE_ACTION, "访问登录页"),
|
||||
Map.entry(LOGOUT_PAGE_ACTION, "访问登出页"),
|
||||
Map.entry("auth", "认证操作"),
|
||||
Map.entry("password", "修改密码"),
|
||||
Map.entry("resetpassword", "重置密码"));
|
||||
@@ -102,17 +113,26 @@ final class OperationDescription {
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径判定,
|
||||
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径与方法判定,
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别(未知方法等)返回 null,记录不标注。
|
||||
*
|
||||
* <p>认证端点按方法区分:POST 是登录/登出操作,其余方法是页面访问
|
||||
* ({@link #LOGIN_PAGE_ACTION} / {@link #LOGOUT_PAGE_ACTION});路径含 {@code error}
|
||||
* 参数的登录页是升级前落库的失败回显,无标注时现场推导为登录失败。
|
||||
*/
|
||||
static String actionOf(String method, String resourceType, String path) {
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
if ("/login".equals(cleanPath)) {
|
||||
return "login";
|
||||
var queryStart = path == null ? -1 : path.indexOf('?');
|
||||
if (queryStart >= 0
|
||||
&& LoginOutcome.hasErrorParam(path.substring(queryStart + 1))) {
|
||||
return LOGIN_FAILURE_ACTION;
|
||||
}
|
||||
return "POST".equals(method) ? "login" : LOGIN_PAGE_ACTION;
|
||||
}
|
||||
if ("/logout".equals(cleanPath)) {
|
||||
return "logout";
|
||||
return "POST".equals(method) ? "logout" : LOGOUT_PAGE_ACTION;
|
||||
}
|
||||
if ("auth".equals(resourceType)) {
|
||||
return "auth";
|
||||
@@ -132,6 +152,35 @@ final class OperationDescription {
|
||||
return METHOD_ACTIONS.get(method);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证端点的页面访问:{@code GET /login}、{@code GET /logout}(含查询串),
|
||||
* 即非 POST 的认证端点请求。页面访问不是登录/登出操作,结果不计成败;仅升级前
|
||||
* 落库的历史记录会出现。
|
||||
*/
|
||||
static boolean isAuthPageVisit(String method, String path) {
|
||||
if ("POST".equals(method)) {
|
||||
return false;
|
||||
}
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
return "/login".equals(cleanPath) || "/logout".equals(cleanPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录的语义动作键(展示、导出与结果判定共用):优先落库标注;认证端点的失败回显与
|
||||
* 页面访问(升级前落库为 login/logout 或无标注的历史记录)按方法与路径纠正;
|
||||
* 落库标注未识别时回退 method/path 现场推导(与前端 {@code semanticAction} 一致)。
|
||||
*/
|
||||
static String semanticAction(AuditLogSpec spec) {
|
||||
var derived = actionOf(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||
if (LOGIN_FAILURE_ACTION.equals(derived) || LOGIN_PAGE_ACTION.equals(derived)
|
||||
|| LOGOUT_PAGE_ACTION.equals(derived)) {
|
||||
return derived;
|
||||
}
|
||||
var stored = spec.getAction();
|
||||
return stored != null && describeAction(stored, spec.getResourceType()) != null
|
||||
? stored : derived;
|
||||
}
|
||||
|
||||
/** 由语义动作键推导中文描述;键为 null 或未识别返回 null(调用方回退 method 推导)。 */
|
||||
static String describeAction(String action, String resourceType) {
|
||||
if (action == null) {
|
||||
@@ -158,12 +207,12 @@ final class OperationDescription {
|
||||
}
|
||||
|
||||
/**
|
||||
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||
* 由落库 spec 推导操作中文描述(导出用):以 {@link #semanticAction} 为准
|
||||
* (含登录失败标注与页面访问纠正),无标注或未识别时回退为 method/path 现场推导
|
||||
* (与前端 {@code describeOperation} 一致)。
|
||||
*/
|
||||
static String describe(AuditLogSpec spec) {
|
||||
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||
var phrase = describeAction(semanticAction(spec), spec.getResourceType());
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
|
||||
+49
-3
@@ -116,9 +116,9 @@ class AuditExportEndpointTest {
|
||||
|
||||
@Test
|
||||
void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页
|
||||
// (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」;
|
||||
// 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)状态码落在
|
||||
// 2xx/3xx,结果列仍应为「失败」;描述列优先落库语义动作(登录失败)。
|
||||
// 升级前落库的失败回显页(GET /login?error=...,200,带同一标注)同样导出失败
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var failedFormLogin = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 302, "119.53.161.18", "Mozilla/5.0");
|
||||
@@ -140,6 +140,52 @@ class AuditExportEndpointTest {
|
||||
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportSuccessfulLoginAsSuccessInsteadOfBareRedirectCode() {
|
||||
// 登录成功(表单提交为 302):结果列写「成功」,与失败的「失败」对称
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var success = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth", null,
|
||||
"/login", 302, "116.179.32.88", "Mozilla/5.0");
|
||||
success.getSpec().setAction("login");
|
||||
stubSinglePage(List.of(success));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,admin,POST,auth,,/login,登录,,成功,302,116.179.32.88,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportAuthPageVisitsAsPageVisitInsteadOfLoginSuccess() {
|
||||
// 升级前落库的页面访问记录(GET /login、GET /logout,带着 login/logout 标注、
|
||||
// HTTP 200):原先导出为「登录,成功」,看起来像未知用户登录成功;
|
||||
// 现在描述列写「访问登录页/访问登出页」,结果列写「页面访问」(不计成败)
|
||||
var time = Instant.parse("2026-12-04T14:16:36Z");
|
||||
var bounced = auditLog("auditlog-1", time, "unknown", null, "GET", "auth", null,
|
||||
"/login?authentication_required", 200, "43.228.157.244", "Mozilla/5.0");
|
||||
bounced.getSpec().setAction("login");
|
||||
var opened = auditLog("auditlog-2", time.plusSeconds(9), "unknown", null, "GET", "auth",
|
||||
null, "/login", 200, "43.228.157.244", "Mozilla/5.0");
|
||||
opened.getSpec().setAction("login");
|
||||
var logoutConfirm = auditLog("auditlog-3", time.plusSeconds(60), "unknown", null,
|
||||
"GET", "auth", null, "/logout", 200, "127.0.0.1", "Mozilla/5.0");
|
||||
logoutConfirm.getSpec().setAction("logout");
|
||||
stubSinglePage(List.of(bounced, opened, logoutConfirm));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(4);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,,GET,auth,,/login?authentication_required,访问登录页,,页面访问,200"
|
||||
+ ",43.228.157.244,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(9))
|
||||
+ ",unknown,,GET,auth,,/login,访问登录页,,页面访问,200,43.228.157.244,Mozilla/5.0");
|
||||
assertThat(lines[3]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,,GET,auth,,/logout,访问登出页,,页面访问,200,127.0.0.1,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
|
||||
+29
-5
@@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.after;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
@@ -69,6 +70,9 @@ class AuditFilterChainIntegrationTest {
|
||||
/** doFinally 回调为响应式异步执行,断言等待上限(毫秒)。 */
|
||||
private static final long CALLBACK_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** 「不记录」断言的等待时长(毫秒):确认透传请求在全链上始终没有触发记录。 */
|
||||
private static final long PASS_THROUGH_WAIT_MS = 500;
|
||||
|
||||
private static final String LOGIN_FORM = "username=admin&password=right-password";
|
||||
|
||||
private AuditRecorder recorder;
|
||||
@@ -212,16 +216,36 @@ class AuditFilterChainIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageVisitExactlyOnceThroughRealChain() {
|
||||
// GET /login 会流经全链(无终止过滤器命中):必须仅由链首过滤器记录一次,
|
||||
// 链尾过滤器不得重复记录(两个过滤器按 CaptureRule 分治、互不重叠)
|
||||
void shouldNotRecordLoginPageVisitThroughRealChain() {
|
||||
// 登录页的 GET 访问不是操作:打开登录页、被弹回登录页(?authentication_required)、
|
||||
// 登录失败后的回显(?error=...)都只渲染页面,全链任何位置都不得落库——
|
||||
// 否则列表里全是「未知用户 · 登录 · 200」,真正的登录成败被淹没
|
||||
for (var path : List.of("/login", "/login?authentication_required",
|
||||
"/login?error=invalid-credential&method=local")) {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get(path)
|
||||
.build());
|
||||
|
||||
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||
}
|
||||
|
||||
// 真实链的记录回调可能异步晚于 block() 返回:等待一段时间后仍为零调用才算数
|
||||
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
|
||||
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordLogoutConfirmPageThroughRealChain() {
|
||||
// 登出确认页(GET /logout)同样只是页面访问
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.get("/logout")
|
||||
.build());
|
||||
|
||||
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||
|
||||
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
|
||||
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
|
||||
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
|
||||
+46
-4
@@ -106,13 +106,16 @@ class AuditQueryEndpointTest {
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// failure = statusCode >= 400(无上界)或语义动作标注 login-failure
|
||||
// (登录失败的 HTTP 状态码可能为 200/302)
|
||||
// failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,仅凭状态码识别不出)
|
||||
// 或 4xx/5xx;页面访问记录(非 POST 的 /login、/logout)不计成败,予以排除
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("400")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
.contains("login-failure")
|
||||
.contains("spec.method")
|
||||
.contains("/login")
|
||||
.contains("/logout");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -126,10 +129,49 @@ class AuditQueryEndpointTest {
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
|
||||
// 与页面访问记录(升级前落库的 GET /login、GET /logout,HTTP 200)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
.contains("login-failure")
|
||||
.contains("spec.method")
|
||||
.contains("/login")
|
||||
.contains("/logout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExcludePageVisitsWhenFilteringByLoginOrLogoutAction() {
|
||||
// 升级前落库的页面访问记录带着 login/logout 标注,但展示为「访问登录页/登出页」:
|
||||
// 按语义动作筛登录/登出操作时不混入
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.action=login")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
assertThat(condition)
|
||||
.contains("spec.action")
|
||||
.contains("login")
|
||||
.contains("spec.method")
|
||||
.contains("/login");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepPlainEqualityForOtherSemanticActions() {
|
||||
// 其余语义动作的等值筛选不带页面访问排除条件
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.action=login-failure")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
assertThat(condition).doesNotContain("spec.method");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+7
-13
@@ -120,7 +120,7 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
|
||||
// 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true,
|
||||
// 表单登录失败(302 重定向回跳登录页):过滤器传入 loginFailed=true,
|
||||
// 语义动作标注 login-failure;状态码仍如实记录 302
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
@@ -133,22 +133,16 @@ class AuditRecorderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailureEcho() {
|
||||
// 登录失败回显(GET /login?error=... 页面渲染 HTTP 200):同样标注登录失败
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.get("http://localhost/login?error=invalid-credential&method=local")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 200,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
void shouldAnnotateLogoutWithoutFailureMark() {
|
||||
// 登出(POST /logout)是认证操作但不是登录尝试:语义动作 logout,不标注登录失败
|
||||
recorder.record(snapshotOf("/logout"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(200);
|
||||
assertThat(spec.getPath()).isEqualTo("/login?error=invalid-credential&method=local");
|
||||
assertThat(spec.getAction()).isEqualTo("logout");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(302);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 结果语义测试(AuditResult):结果筛选与 CSV 导出共用的成败判定。
|
||||
* 登录失败不能只看状态码(表单登录失败的 HTTP 状态码与成功相同,均为 302);
|
||||
* 认证端点的页面访问(升级前落库的 GET 记录)不是操作,不计成败。
|
||||
*/
|
||||
class AuditResultTest {
|
||||
|
||||
private static AuditLogSpec spec(String method, String path, Integer statusCode,
|
||||
String action) {
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setMethod(method);
|
||||
spec.setResourceType("auth");
|
||||
spec.setPath(path);
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setAction(action);
|
||||
return spec;
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginFailureIsFailureRegardlessOfStatusCode() {
|
||||
// 表单登录失败:302(与成功相同的状态码),只能靠落库标注识别
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 302, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
// XHR 登录失败、CSRF 拦截
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 401, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 403, "login-failure")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
// 升级前落库的失败回显(GET /login?error=...,HTTP 200):带标注或由路径推导
|
||||
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200,
|
||||
"login-failure"))).isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200, null)))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulLoginIsSuccess() {
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 302, "login")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/login", 200, "login")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authPageVisitsAreNeitherSuccessNorFailure() {
|
||||
// 升级前落库的页面访问记录:当时带着 login/logout 标注、HTTP 200——
|
||||
// 原先显示为绿色「登录 200」,看起来像未知用户登录成功
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 200, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/login?authentication_required", 200, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/logout", 200, "logout")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 200, null)))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
assertThat(AuditResult.of(spec("GET", "/login", 500, "login")))
|
||||
.isEqualTo(AuditResult.PAGE_VISIT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryRecordsFollowStatusCode() {
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 201, "create")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 302, "create")))
|
||||
.isEqualTo(AuditResult.SUCCESS);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 403, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 500, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", null, "create")))
|
||||
.isEqualTo(AuditResult.FAILURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsAreUsedForCsvResultColumn() {
|
||||
assertThat(AuditResult.SUCCESS.label()).isEqualTo("成功");
|
||||
assertThat(AuditResult.FAILURE.label()).isEqualTo("失败");
|
||||
assertThat(AuditResult.PAGE_VISIT.label()).isEqualTo("页面访问");
|
||||
}
|
||||
}
|
||||
+61
-18
@@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -27,8 +28,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
/**
|
||||
* 认证端点捕获过滤器行为测试(P0 修复):POST /login、POST /logout 必须产生审计记录
|
||||
* (真实环境中表单登录/登出过滤器在链尾过滤器之前直接完成响应,因此由本过滤器在
|
||||
* Security 链之前承接)。操作者统一为未知用户,登录尝试账号由请求体白名单提取;
|
||||
* 登录失败告警回调仅发生在 POST /login;非认证端点请求一律透传、零副作用。
|
||||
* Security 链之前承接)。登录/登出页面的 GET 访问不是操作,一律透传不记录。
|
||||
* 操作者统一为未知用户,登录尝试账号由请求体白名单提取;登录失败告警回调仅发生在
|
||||
* POST /login;非认证端点请求一律透传、零副作用。
|
||||
*/
|
||||
class AuthEndpointAuditWebFilterTest {
|
||||
|
||||
@@ -130,34 +132,75 @@ class AuthEndpointAuditWebFilterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageVisitWithoutFailureMark() {
|
||||
// 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
void shouldPassThroughLoginPageVisitsWithoutRecording() {
|
||||
// 登录页的 GET 访问不是登录操作:打开登录页、匿名访问被弹回登录页
|
||||
// (/login?authentication_required)、登录失败后的回显(/login?error=...)
|
||||
// 都只渲染页面(HTTP 200)。原先一律落库为「未知用户 · 登录 · 200」,在列表里
|
||||
// 与登录成功无法区分(现场反馈:全是成功、登录失败也显示成功)——现在原样透传
|
||||
for (var path : List.of("/login", "/login?authentication_required",
|
||||
"/login?error=invalid-credential&method=local", "/login?logout")) {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
}
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
verify(writeMarker, never()).onRequestComplete(any());
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageErrorEchoAsLoginFailure() {
|
||||
// 登录失败回显:GET /login?error=... 页面渲染 HTTP 200,标注登录失败,
|
||||
// 但不是登录尝试、不触发告警
|
||||
void shouldPassThroughLogoutConfirmPageWithoutRecording() {
|
||||
// 登出确认页(GET /logout)同样只是页面访问,不是登出操作
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login?error=invalid-credential&method=local")
|
||||
.get("/logout")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureWhenRedirectedBackToLoginWithoutErrorParam() {
|
||||
// 302 跳回登录页且不带 error 参数:不可能是登录成功(成功只会去 /uc、已保存的
|
||||
// 原请求或 2FA 页),同样判失败——只有响应明确确认才算成功
|
||||
var exchange = loginExchange("bob", "wrong");
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
|
||||
URI.create("/login")))).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
|
||||
eq("bob"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureWhenRedirectHasNoLocation() {
|
||||
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
|
||||
var exchange = loginExchange("bob", "wrong");
|
||||
WebFilterChain foundWithoutLocation = ex -> {
|
||||
ex.getResponse().setStatusCode(HttpStatus.FOUND);
|
||||
return Mono.empty();
|
||||
};
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, foundWithoutLocation)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
|
||||
}
|
||||
|
||||
private static MockServerWebExchange loginExchange(String username, String password) {
|
||||
var body = "username=" + username + "&password=" + password;
|
||||
return MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+18
-1
@@ -29,7 +29,7 @@ class CaptureRuleTest {
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureAuthEndpointsInApisRule() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 独立捕获(isAuthEndpoint),
|
||||
// 认证操作由 AuthEndpointAuditWebFilter 独立捕获(isAuthOperation),
|
||||
// 通用规则不再包含,两个过滤器按规则分治、互不重叠
|
||||
assertThat(shouldCapture("/login", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/login", "GET")).isFalse();
|
||||
@@ -71,4 +71,21 @@ class CaptureRuleTest {
|
||||
assertThat(CaptureRule.isLoginAttempt(null, "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/login", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatOnlyPostAsAuthOperation() {
|
||||
// 认证操作 = POST /login(登录尝试)+ POST /logout(登出)
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "POST")).isTrue();
|
||||
assertThat(CaptureRule.isAuthOperation("/logout", "POST")).isTrue();
|
||||
// 登录/登出页面的 GET 访问不是操作:打开登录页、被弹回登录页、失败回显、登出确认页
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "GET")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/logout", "GET")).isFalse();
|
||||
// 其余方法与路径一律不算
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "HEAD")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/login", "PUT")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/loginx", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/console/login", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation(null, "POST")).isFalse();
|
||||
assertThat(CaptureRule.isAuthOperation("/login", null)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
+34
-34
@@ -9,6 +9,9 @@ import org.junit.jupiter.api.Test;
|
||||
* 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为
|
||||
* 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON
|
||||
* 请求以 200/401 区分成败,成败判定必须结合重定向目标。
|
||||
*
|
||||
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把
|
||||
* 失败登录记成成功,远比把异常响应记成失败更糟。
|
||||
*/
|
||||
class LoginOutcomeTest {
|
||||
|
||||
@@ -34,26 +37,42 @@ class LoginOutcomeTest {
|
||||
// 两步验证:302 → /challenges/two-factor/totp
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/challenges/two-factor/totp"))).isFalse();
|
||||
// 登录前被弹回的原请求:302 → 已保存的受保护页面
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/console/posts"))).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("http://blog.guichumo.com/console/posts?page=1"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formFailureRedirectWithErrorParamIsFailure() {
|
||||
// 表单登录失败:302 → /login?error=invalid-credential&method=local
|
||||
// (Halo 2.26.1 LoginFailureHandler 的四种失败重定向:invalid-credential /
|
||||
// account-disabled / rate-limit-exceeded / 无值 error)
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=invalid-credential&method=local"))).isTrue();
|
||||
// 账号禁用/限流等其他失败码同样含 error 参数
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=account-disabled&method=local"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=rate-limit-exceeded&method=local"))).isTrue();
|
||||
// 兜底失败分支:error 参数无值(/login?error&method=...)
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?error&method=local"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("http://blog.guichumo.com/login?error=invalid-credential"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectWithoutLocationIsNotFailure() {
|
||||
// 3xx 但缺失 Location(无法确认失败):按成功处理,不凭空判失败
|
||||
assertThat(LoginOutcome.isFailure(302, null)).isFalse();
|
||||
void redirectBackToLoginPageWithoutErrorParamIsFailure() {
|
||||
// 跳回登录页必然是失败:成功只会去 /uc、已保存的原请求或 2FA 页。
|
||||
// 不依赖 error 参数——宿主或第三方登录扩展换了失败重定向格式也不会把失败记成成功
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?authentication_required")))
|
||||
.isTrue();
|
||||
assertThat(LoginOutcome.isFailure(307, URI.create("/login?logout"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectWithoutLocationIsFailure() {
|
||||
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
|
||||
assertThat(LoginOutcome.isFailure(302, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,41 +82,22 @@ class LoginOutcomeTest {
|
||||
assertThat(LoginOutcome.isFailure(0, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientAndServerErrorsAreFailure() {
|
||||
// CSRF 拦截(403)、服务端异常(500)同为失败
|
||||
assertThat(LoginOutcome.isFailure(403, URI.create("/login"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(500, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorParamNameMustMatchExactly() {
|
||||
// 含 error 字样的其他参数(如 errors=1)不算失败标记
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/uc?errors=1"))).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?errors=1"))).isFalse();
|
||||
}
|
||||
|
||||
// ===== GET /login?error=...:失败回显 =====
|
||||
|
||||
@Test
|
||||
void loginPageWithErrorParamIsFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error=invalid-credential&method=local"))
|
||||
.isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error&method=local")).isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local&error=invalid-credential"))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainLoginPageIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherEndpointsAreNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/logout?error=x")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/core.halo.run/v1alpha1/login?error=x"))
|
||||
.isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/uc?error=x")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOrQuerylessPathIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho(null)).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/content.halo.run/v1alpha1/posts")).isFalse();
|
||||
void loginPagePathMustMatchExactly() {
|
||||
// 仅路径恰为 /login 才算跳回登录页;/login-xxx 等前缀相同的路径不算
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login-callback"))).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
+105
-6
@@ -12,15 +12,24 @@ class OperationDescriptionTest {
|
||||
|
||||
@Test
|
||||
void shouldDescribeLoginEndpointIncludingQuery() {
|
||||
// POST /login 是登录操作;GET /login(含任意查询串)只是打开登录页
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.describe("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("登录");
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole"))
|
||||
.isEqualTo("访问登录页");
|
||||
assertThat(OperationDescription.describe("GET", "auth", "/login?authentication_required"))
|
||||
.isEqualTo("访问登录页");
|
||||
// 升级前落库的失败回显(GET /login?error=...)无标注时由 error 参数现场推导
|
||||
assertThat(OperationDescription.describe("GET", "auth",
|
||||
"/login?error=invalid-credential&method=local")).isEqualTo("登录失败");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeLogoutEndpoint() {
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出");
|
||||
// GET /logout 是登出确认页
|
||||
assertThat(OperationDescription.describe("GET", "auth", "/logout"))
|
||||
.isEqualTo("访问登出页");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,14 +113,46 @@ class OperationDescriptionTest {
|
||||
@Test
|
||||
void shouldDeriveLoginLogoutAuthActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/login")).isEqualTo("login");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("login");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/logout")).isEqualTo("logout");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/auth/other"))
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveAuthPageVisitsByMethod() {
|
||||
// 认证端点的页面访问(非 POST):打开登录页、被弹回登录页、登出确认页
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login"))
|
||||
.isEqualTo("login-page");
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?authentication_required")).isEqualTo("login-page");
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/logout"))
|
||||
.isEqualTo("logout-page");
|
||||
// 失败回显(路径含 error 参数)推导为登录失败
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?error=invalid-credential&method=local"))
|
||||
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login?error&method=local"))
|
||||
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
// 含 error 字样的其他参数不算失败标记
|
||||
assertThat(OperationDescription.actionOf("GET", "auth", "/login?errors=1"))
|
||||
.isEqualTo("login-page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectAuthPageVisits() {
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/login")).isTrue();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/login?error=x")).isTrue();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/logout")).isTrue();
|
||||
// POST 是真正的登录/登出操作
|
||||
assertThat(OperationDescription.isAuthPageVisit("POST", "/login")).isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("POST", "/logout")).isFalse();
|
||||
// 其余路径一律不算
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/apis/core.halo.run/v1alpha1/posts"))
|
||||
.isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", "/loginx")).isFalse();
|
||||
assertThat(OperationDescription.isAuthPageVisit("GET", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveMethodActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "users",
|
||||
@@ -197,10 +238,15 @@ class OperationDescriptionTest {
|
||||
@Test
|
||||
void shouldDescribeFromActionKey() {
|
||||
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
||||
// 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显)
|
||||
// 登录失败语义动作(POST /login 失败,或升级前落库的 GET /login?error=... 失败回显)
|
||||
assertThat(OperationDescription.describeAction("login-failure", "auth"))
|
||||
.isEqualTo("登录失败");
|
||||
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
||||
// 认证端点的页面访问(升级前落库的历史 GET 记录)
|
||||
assertThat(OperationDescription.describeAction("login-page", "auth"))
|
||||
.isEqualTo("访问登录页");
|
||||
assertThat(OperationDescription.describeAction("logout-page", "auth"))
|
||||
.isEqualTo("访问登出页");
|
||||
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
||||
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
||||
assertThat(OperationDescription.describeAction("update", "posts")).isEqualTo("修改文章");
|
||||
@@ -244,4 +290,57 @@ class OperationDescriptionTest {
|
||||
bogus.setAction("bogus");
|
||||
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCorrectAuthPageVisitsRegardlessOfStoredAction() {
|
||||
// 升级前落库的页面访问记录带着 login/logout 标注(当时 GET 也被当成登录/登出记录):
|
||||
// 展示必须按方法纠正为页面访问,否则这些记录继续显示成「未知用户 · 登录」
|
||||
var loginPage = new AuditLogSpec();
|
||||
loginPage.setMethod("GET");
|
||||
loginPage.setResourceType("auth");
|
||||
loginPage.setPath("/login?authentication_required");
|
||||
loginPage.setAction("login");
|
||||
assertThat(OperationDescription.semanticAction(loginPage)).isEqualTo("login-page");
|
||||
assertThat(OperationDescription.describe(loginPage)).isEqualTo("访问登录页");
|
||||
|
||||
var logoutPage = new AuditLogSpec();
|
||||
logoutPage.setMethod("GET");
|
||||
logoutPage.setResourceType("auth");
|
||||
logoutPage.setPath("/logout");
|
||||
logoutPage.setAction("logout");
|
||||
assertThat(OperationDescription.semanticAction(logoutPage)).isEqualTo("logout-page");
|
||||
assertThat(OperationDescription.describe(logoutPage)).isEqualTo("访问登出页");
|
||||
|
||||
// 无标注的页面访问记录同样推导为页面访问
|
||||
var unannotated = new AuditLogSpec();
|
||||
unannotated.setMethod("GET");
|
||||
unannotated.setResourceType("auth");
|
||||
unannotated.setPath("/login");
|
||||
assertThat(OperationDescription.describe(unannotated)).isEqualTo("访问登录页");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepStoredActionForAuthOperations() {
|
||||
// POST 是真正的认证操作:落库标注优先(成功 login / 失败 login-failure / 登出 logout)
|
||||
var success = new AuditLogSpec();
|
||||
success.setMethod("POST");
|
||||
success.setResourceType("auth");
|
||||
success.setPath("/login");
|
||||
success.setAction("login");
|
||||
assertThat(OperationDescription.semanticAction(success)).isEqualTo("login");
|
||||
|
||||
var failure = new AuditLogSpec();
|
||||
failure.setMethod("POST");
|
||||
failure.setResourceType("auth");
|
||||
failure.setPath("/login");
|
||||
failure.setAction("login-failure");
|
||||
assertThat(OperationDescription.semanticAction(failure)).isEqualTo("login-failure");
|
||||
|
||||
var logout = new AuditLogSpec();
|
||||
logout.setMethod("POST");
|
||||
logout.setResourceType("auth");
|
||||
logout.setPath("/logout");
|
||||
logout.setAction("logout");
|
||||
assertThat(OperationDescription.semanticAction(logout)).isEqualTo("logout");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
deriveAction,
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
isAuthPageVisit,
|
||||
isLoginFailure,
|
||||
resultBadge,
|
||||
resultOutcome,
|
||||
SEMANTIC_ACTIONS,
|
||||
SYSTEM_USERNAME,
|
||||
UNKNOWN_USERNAME,
|
||||
@@ -28,27 +30,58 @@ function spec(overrides: Partial<AuditLogSpec>): AuditLogSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/** 升级前落库的登录页访问记录:GET、HTTP 200、带着 login 标注(当时 GET 也被当成登录记录)。 */
|
||||
function legacyLoginPageVisit(overrides: Partial<AuditLogSpec> = {}): AuditLogSpec {
|
||||
return spec({
|
||||
username: 'unknown',
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 200,
|
||||
remoteIp: '43.228.157.244',
|
||||
action: 'login',
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
describe('describeOperation', () => {
|
||||
it('登录端点(含查询串)描述为 登录', () => {
|
||||
it('登录端点:POST 描述为 登录,GET(含查询串)描述为 访问登录页', () => {
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
}))).toBe('登录')
|
||||
// GET /login?redirect_uri=... 也应识别为登录(spec.path 含查询串)
|
||||
// GET /login 只是打开登录页,不是登录操作(spec.path 含查询串同样如此)
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole',
|
||||
}))).toBe('登录')
|
||||
}))).toBe('访问登录页')
|
||||
// 匿名访问受保护页面被弹回登录页
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?authentication_required',
|
||||
}))).toBe('访问登录页')
|
||||
// 升级前落库的失败回显(GET /login?error=...)无标注时由 error 参数现场推导
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
}))).toBe('登录失败')
|
||||
})
|
||||
|
||||
it('登出端点描述为 登出', () => {
|
||||
it('登出端点:POST 描述为 登出,GET(登出确认页)描述为 访问登出页', () => {
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
}))).toBe('登出')
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
}))).toBe('访问登出页')
|
||||
})
|
||||
|
||||
it('auth 类型但非登录/登出路径回退为 认证操作', () => {
|
||||
@@ -147,25 +180,26 @@ describe('describeOperation', () => {
|
||||
})
|
||||
|
||||
describe('deriveAction 语义动作推导', () => {
|
||||
it('登录/登出/认证操作由路径判定(含查询串剥离)', () => {
|
||||
it('登录/登出按方法区分:POST 是操作,GET 是页面访问;认证操作由路径判定', () => {
|
||||
expect(deriveAction('POST', 'auth', '/login')).toBe('login')
|
||||
expect(deriveAction('GET', 'auth', '/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com'))
|
||||
.toBe('login')
|
||||
.toBe('login-page')
|
||||
expect(deriveAction('GET', 'auth', '/login?authentication_required')).toBe('login-page')
|
||||
expect(deriveAction('POST', 'auth', '/logout')).toBe('logout')
|
||||
expect(deriveAction('GET', 'auth', '/logout')).toBe('logout-page')
|
||||
expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth')
|
||||
})
|
||||
|
||||
it('登录失败回显(GET /login?error=...)推导为 login-failure', () => {
|
||||
// 登录失败后 Halo 重定向到带 error 参数的登录页,页面渲染 HTTP 200;
|
||||
// 历史记录(无落库标注)由路径中的 error 参数现场推导
|
||||
// 升级前落库的失败回显页(HTTP 200)无标注时由路径中的 error 参数现场推导
|
||||
expect(deriveAction('GET', 'auth', '/login?error=invalid-credential&method=local'))
|
||||
.toBe('login-failure')
|
||||
// 兜底失败分支:error 参数无值
|
||||
expect(deriveAction('GET', 'auth', '/login?error&method=local')).toBe('login-failure')
|
||||
// 首次打开登录页(无 error 参数)不是失败回显
|
||||
expect(deriveAction('GET', 'auth', '/login?method=local')).toBe('login')
|
||||
// 不带 error 参数的登录页只是页面访问
|
||||
expect(deriveAction('GET', 'auth', '/login?method=local')).toBe('login-page')
|
||||
// 含 error 字样的其他参数不算失败标记
|
||||
expect(deriveAction('GET', 'auth', '/login?errors=1')).toBe('login')
|
||||
expect(deriveAction('GET', 'auth', '/login?errors=1')).toBe('login-page')
|
||||
})
|
||||
|
||||
it('子动作段优先于 HTTP 方法', () => {
|
||||
@@ -236,92 +270,126 @@ describe('describeOperation 落库标注优先', () => {
|
||||
})
|
||||
|
||||
it('登录失败标注(login-failure)描述为 登录失败', () => {
|
||||
// 表单登录失败(POST /login,302)与失败回显页(GET /login?error=...,200)
|
||||
// 均落库标注,描述为 登录失败 而非按路径推导出的 登录
|
||||
// 表单登录失败(POST /login,302)落库标注 login-failure,描述为 登录失败
|
||||
// 而非按路径推导出的 登录
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
// 升级前落库的失败回显页(GET /login?error=...,200)带同一标注
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
// 历史回显记录(无落库标注)由路径现场推导,同样得到 登录失败
|
||||
// 无标注的历史回显记录由路径现场推导,同样得到 登录失败
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
}))).toBe('登录失败')
|
||||
})
|
||||
|
||||
it('升级前落库的登录页访问记录(GET + login 标注)纠正为 访问登录页,不再显示成登录', () => {
|
||||
// 当时登录页的 GET 访问被记成「未知用户 · 登录 · 200」,看起来像登录成功
|
||||
expect(describeOperation(legacyLoginPageVisit())).toBe('访问登录页')
|
||||
expect(describeOperation(legacyLoginPageVisit({
|
||||
path: '/login?authentication_required',
|
||||
}))).toBe('访问登录页')
|
||||
expect(describeOperation(legacyLoginPageVisit({
|
||||
path: '/logout',
|
||||
action: 'logout',
|
||||
}))).toBe('访问登出页')
|
||||
// 无标注的页面访问记录同样推导为页面访问
|
||||
expect(describeOperation(legacyLoginPageVisit({ action: undefined }))).toBe('访问登录页')
|
||||
// POST 才是登录/登出操作,落库标注照常生效
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
action: 'login',
|
||||
}))).toBe('登录')
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/logout',
|
||||
action: 'logout',
|
||||
}))).toBe('登出')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLoginFailure / resultBadge 登录失败结果展示', () => {
|
||||
it('落库标注 login-failure 判定为登录失败(HTTP 200/302 也可能是失败)', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
describe('isAuthPageVisit 认证端点的页面访问', () => {
|
||||
it('GET /login、GET /logout(含查询串)是页面访问;POST 是认证操作', () => {
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login?authentication_required' })))
|
||||
.toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/login?error=x' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/logout' }))).toBe(true)
|
||||
expect(isAuthPageVisit(spec({ method: 'POST', path: '/login' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'POST', path: '/logout' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/console/' }))).toBe(false)
|
||||
expect(isAuthPageVisit(spec({ method: 'GET', path: '/apis/core.halo.run/v1alpha1/login' })))
|
||||
.toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resultOutcome / resultBadge 结果语义', () => {
|
||||
it('登录失败为 failure:红色 失败,不显示裸状态码(表单失败是 302、失败回显是 200)', () => {
|
||||
const failed = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
})
|
||||
expect(isLoginFailure(failed)).toBe(true)
|
||||
expect(resultOutcome(failed)).toBe('failure')
|
||||
expect(resultBadge(failed)).toEqual({ text: '失败', class: 'status-fail' })
|
||||
// XHR 登录失败(401)、CSRF 拦截(403)
|
||||
expect(resultOutcome({ ...failed, statusCode: 401 })).toBe('failure')
|
||||
expect(resultOutcome({ ...failed, statusCode: 403 })).toBe('failure')
|
||||
// 升级前落库的失败回显页(GET,200):带标注或由路径推导
|
||||
const echo = spec({
|
||||
method: 'GET', resourceType: 'auth', statusCode: 200,
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
})
|
||||
expect(resultOutcome({ ...echo, action: 'login-failure' })).toBe('failure')
|
||||
expect(isLoginFailure(echo)).toBe(true)
|
||||
expect(resultBadge({ ...echo, action: 'login-failure' }))
|
||||
.toEqual({ text: '失败', class: 'status-fail' })
|
||||
})
|
||||
|
||||
it('历史回显记录(无落库标注)由路径现场推导', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
}))).toBe(true)
|
||||
// 表单登录失败的历史记录(POST /login,302)无法由路径推导,仍按登录展示
|
||||
// (升级后新记录落库标注,不再有此局限)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
}))).toBe(false)
|
||||
// 成功登录(POST /login,302 → /uc)不是登录失败
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login',
|
||||
}))).toBe(false)
|
||||
it('登录成功为 success:绿色 成功(表单成功同样是 302,裸状态码读不出成败)', () => {
|
||||
const success = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302, action: 'login',
|
||||
})
|
||||
expect(isLoginFailure(success)).toBe(false)
|
||||
expect(resultOutcome(success)).toBe('success')
|
||||
expect(resultBadge(success)).toEqual({ text: '成功', class: 'status-ok' })
|
||||
// XHR 登录成功(200)
|
||||
expect(resultBadge({ ...success, statusCode: 200 }))
|
||||
.toEqual({ text: '成功', class: 'status-ok' })
|
||||
})
|
||||
|
||||
it('登录失败记录结果徽标为红色 失败(不显示裸状态码)', () => {
|
||||
// 失败回显页 HTTP 200:修复前显示绿色 200,误读为登录成功
|
||||
expect(resultBadge(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
// 表单登录失败 302 重定向:同理
|
||||
expect(resultBadge(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
it('登录页访问记录为 page-visit:灰色 —,既不算成功也不算失败', () => {
|
||||
// 升级前落库的 GET /login(HTTP 200、带 login 标注)原先显示绿色「200」,
|
||||
// 看起来像未知用户登录成功;现在按方法纠正为页面访问
|
||||
const visit = legacyLoginPageVisit({ path: '/login?authentication_required' })
|
||||
expect(isLoginFailure(visit)).toBe(false)
|
||||
expect(resultOutcome(visit)).toBe('page-visit')
|
||||
expect(resultBadge(visit)).toEqual({ text: '—', class: 'status-na' })
|
||||
expect(resultOutcome(legacyLoginPageVisit({ path: '/logout', action: 'logout' })))
|
||||
.toBe('page-visit')
|
||||
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
|
||||
expect(resultOutcome(legacyLoginPageVisit({ action: undefined }))).toBe('page-visit')
|
||||
expect(resultOutcome(legacyLoginPageVisit({ statusCode: 500 }))).toBe('page-visit')
|
||||
})
|
||||
|
||||
it('非登录记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||
it('登出与其他记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||
const logout = spec({
|
||||
method: 'POST', resourceType: 'auth', path: '/logout', statusCode: 302, action: 'logout',
|
||||
})
|
||||
expect(resultBadge(logout)).toEqual({ text: '302', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 200 }))).toEqual({ text: '200', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 302 }))).toEqual({ text: '302', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 403 }))).toEqual({ text: '403', class: 'status-fail' })
|
||||
|
||||
@@ -107,11 +107,19 @@ const SEGMENT_ACTIONS: Record<string, string> = {
|
||||
/** 登录失败语义动作键(与后端 OperationDescription.LOGIN_FAILURE_ACTION 同步)。 */
|
||||
const LOGIN_FAILURE_ACTION = 'login-failure'
|
||||
|
||||
/** 登录页访问(打开登录页、被弹回登录页、失败回显):仅升级前落库的历史记录。 */
|
||||
const LOGIN_PAGE_ACTION = 'login-page'
|
||||
|
||||
/** 登出页访问(登出确认页):仅升级前落库的历史记录。 */
|
||||
const LOGOUT_PAGE_ACTION = 'logout-page'
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼资源名)。 */
|
||||
const ACTION_PHRASES: Record<string, string> = {
|
||||
login: '登录',
|
||||
[LOGIN_FAILURE_ACTION]: '登录失败',
|
||||
logout: '登出',
|
||||
[LOGIN_PAGE_ACTION]: '访问登录页',
|
||||
[LOGOUT_PAGE_ACTION]: '访问登出页',
|
||||
auth: '认证操作',
|
||||
password: '修改密码',
|
||||
resetpassword: '重置密码',
|
||||
@@ -174,7 +182,7 @@ function pathWithoutQuery(path?: string | null): string {
|
||||
|
||||
/**
|
||||
* 查询串是否含 error 参数(可为无值形式 error)。
|
||||
* 登录失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||
* 升级前落库的失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||
*/
|
||||
function hasErrorParam(path?: string | null): boolean {
|
||||
if (!path) {
|
||||
@@ -190,26 +198,40 @@ function hasErrorParam(path?: string | null): boolean {
|
||||
.some((pair) => (pair.indexOf('=') < 0 ? pair : pair.slice(0, pair.indexOf('='))) === 'error')
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为认证端点的页面访问(GET /login、GET /logout,含查询串):打开登录页、匿名访问
|
||||
* 被弹回登录页(?authentication_required)、失败回显(?error=...)、登出确认页。
|
||||
* 页面访问不是登录/登出操作,结果不计成败;现已不再记录,只有升级前落库的历史记录
|
||||
* 会出现——当时它们被记成「未知用户 · 登录 · 200」,看起来像登录成功。
|
||||
*/
|
||||
export function isAuthPageVisit(spec: Pick<AuditLogSpec, 'method' | 'path'>): boolean {
|
||||
if (spec.method === 'POST') {
|
||||
return false
|
||||
}
|
||||
const cleanPath = pathWithoutQuery(spec.path)
|
||||
return cleanPath === '/login' || cleanPath === '/logout'
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致):
|
||||
* 登录/登录失败/登出/认证操作由路径判定(GET /login?error=... 为登录失败回显),
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 认证端点按方法区分——POST 是登录/登出操作,其余方法是页面访问,路径带 error 参数的
|
||||
* 登录页是失败回显;子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别返回 null。
|
||||
*
|
||||
* <p>历史局限:升级前落库的表单登录失败记录(POST /login,302)无法由路径重新
|
||||
* 推导出失败,仍推导为 login;仅回显页(GET,error 参数在路径中)可现场推导。
|
||||
*/
|
||||
export function deriveAction(
|
||||
method: string,
|
||||
resourceType: string,
|
||||
path?: string | null,
|
||||
path?: string | null
|
||||
): string | null {
|
||||
const cleanPath = pathWithoutQuery(path)
|
||||
if (cleanPath === '/login') {
|
||||
return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login'
|
||||
if (hasErrorParam(path)) {
|
||||
return LOGIN_FAILURE_ACTION
|
||||
}
|
||||
return method === 'POST' ? 'login' : LOGIN_PAGE_ACTION
|
||||
}
|
||||
if (cleanPath === '/logout') {
|
||||
return 'logout'
|
||||
return method === 'POST' ? 'logout' : LOGOUT_PAGE_ACTION
|
||||
}
|
||||
if (resourceType === 'auth') {
|
||||
return 'auth'
|
||||
@@ -240,19 +262,36 @@ function describeFromAction(action: string | null, resourceType: string): string
|
||||
return verb ? `${verb}${RESOURCE_LABELS[resourceType] ?? resourceType}` : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录的语义动作键(展示与结果判定共用,与后端 OperationDescription.semanticAction 一致):
|
||||
* 优先落库标注(spec.action);认证端点的失败回显与页面访问——升级前落库为 login/logout
|
||||
* 或无标注的历史记录——按方法与路径纠正;落库标注未识别时回退 method/path 现场推导。
|
||||
*/
|
||||
function semanticAction(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): string | null {
|
||||
const derived = deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
if (
|
||||
derived === LOGIN_FAILURE_ACTION ||
|
||||
derived === LOGIN_PAGE_ACTION ||
|
||||
derived === LOGOUT_PAGE_ACTION
|
||||
) {
|
||||
return derived
|
||||
}
|
||||
return spec.action && describeFromAction(spec.action, spec.resourceType) ? spec.action : derived
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作描述(这条操作真正干了什么):推导中文短语,
|
||||
* 如 登录、登出、新建用户、修改文章、发布文章、启用插件、修改密码。
|
||||
*
|
||||
* <p>优先使用落库的语义动作标注(spec.action);历史记录(无 action 字段)由
|
||||
* method/path 现场推导,同样适用。识别失败回退为「method 动词 + 资源名」,
|
||||
* 未识别的资源类型直接使用原始 resourceType。
|
||||
* <p>以记录的语义动作键为准(含登录失败标注与页面访问纠正);识别失败回退为
|
||||
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
export function describeOperation(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>,
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): string {
|
||||
const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
const fromAction = describeFromAction(action, spec.resourceType)
|
||||
const fromAction = describeFromAction(semanticAction(spec), spec.resourceType)
|
||||
if (fromAction) {
|
||||
return fromAction
|
||||
}
|
||||
@@ -277,23 +316,49 @@ export function isSuccessful(statusCode?: number | null): boolean {
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
}
|
||||
|
||||
/** 结果语义(与后端 AuditResult 同一规则,结果筛选与 CSV 导出沿用)。 */
|
||||
export type ResultOutcome = 'success' | 'failure' | 'page-visit'
|
||||
|
||||
type ResultSpec = Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action' | 'statusCode'>
|
||||
|
||||
/**
|
||||
* 记录的结果语义:登录失败(语义动作 login-failure,表单登录失败的 HTTP 状态码与成功
|
||||
* 相同、均为 302,只能靠标注识别)为 failure;认证端点的页面访问(升级前落库的 GET
|
||||
* 记录)不是操作,为 page-visit,不计成败;其余按状态码 2xx/3xx 判成功。
|
||||
*/
|
||||
export function resultOutcome(spec: ResultSpec): ResultOutcome {
|
||||
if (isLoginFailure(spec)) {
|
||||
return 'failure'
|
||||
}
|
||||
if (isAuthPageVisit(spec)) {
|
||||
return 'page-visit'
|
||||
}
|
||||
return isSuccessful(spec.statusCode) ? 'success' : 'failure'
|
||||
}
|
||||
|
||||
/** 结果徽标展示形态:文本与配色 class。 */
|
||||
export interface ResultBadge {
|
||||
text: string
|
||||
class: 'status-ok' | 'status-fail'
|
||||
class: 'status-ok' | 'status-fail' | 'status-na'
|
||||
}
|
||||
|
||||
/**
|
||||
* 结果列徽标(列表/详情共用):登录失败记录(语义动作 login-failure,HTTP 状态码可能
|
||||
* 为 200/302——失败回显页渲染/表单登录失败重定向)显示「失败」而非裸状态码,避免
|
||||
* 绿色 200/302 误读为登录成功;其余记录保持原状——按 HTTP 状态码展示
|
||||
* (2xx/3xx 绿、其余红),与既有行为一致。
|
||||
* 结果列徽标(列表/详情共用):
|
||||
* - 登录失败显示红色「失败」——表单登录失败是 302、失败回显页是 200,裸状态码是绿的;
|
||||
* - 登录成功显示绿色「成功」——表单登录成功同样是 302,与「失败」对称才读得出成败;
|
||||
* - 认证端点的页面访问(升级前落库的历史 GET 记录)显示灰色「—」,不计成败;
|
||||
* - 其余记录按 HTTP 状态码展示(2xx/3xx 绿、其余红)。
|
||||
*/
|
||||
export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action' | 'statusCode'>): ResultBadge {
|
||||
export function resultBadge(spec: ResultSpec): ResultBadge {
|
||||
if (isLoginFailure(spec)) {
|
||||
return { text: '失败', class: 'status-fail' }
|
||||
}
|
||||
if (isAuthPageVisit(spec)) {
|
||||
return { text: '—', class: 'status-na' }
|
||||
}
|
||||
if (semanticAction(spec) === 'login' && isSuccessful(spec.statusCode)) {
|
||||
return { text: '成功', class: 'status-ok' }
|
||||
}
|
||||
return {
|
||||
text: String(spec.statusCode),
|
||||
class: isSuccessful(spec.statusCode) ? 'status-ok' : 'status-fail',
|
||||
@@ -301,13 +366,13 @@ export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' |
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录失败记录:优先落库语义动作标注(spec.action,POST /login 失败与
|
||||
* 失败回显均落库),历史记录回退由路径现场推导(仅回显页可推导)。
|
||||
* 是否为登录失败记录:以记录的语义动作键为准(POST /login 失败落库标注 login-failure;
|
||||
* 升级前落库的失败回显页带同一标注,或由路径中的 error 参数现场推导)。
|
||||
*/
|
||||
export function isLoginFailure(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action'>): boolean {
|
||||
const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
return action === LOGIN_FAILURE_ACTION
|
||||
export function isLoginFailure(
|
||||
spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path' | 'action'>
|
||||
): boolean {
|
||||
return semanticAction(spec) === LOGIN_FAILURE_ACTION
|
||||
}
|
||||
|
||||
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
||||
|
||||
@@ -39,3 +39,18 @@ describe('AuditLogDetail 字段变更区块', () => {
|
||||
expect(sfc).not.toContain('删除变更')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AuditLogDetail 结果语义', () => {
|
||||
it('结果与列表徽标、结果筛选、CSV 导出共用同一规则(resultOutcome)', () => {
|
||||
// 登录失败靠语义动作标注识别(HTTP 状态码可能是 302/200),不能在组件里按状态码另判一套
|
||||
expect(sfc).toContain('resultOutcome(props.log.spec)')
|
||||
expect(sfc).not.toContain('isSuccessful(')
|
||||
})
|
||||
|
||||
it('结果三态:成功 / 失败 / 页面访问(中性灰,不计成败)', () => {
|
||||
// 升级前落库的登录页访问记录原先显示「成功 · 200」,误读为未知用户登录成功
|
||||
expect(sfc).toContain("'page-visit': '页面访问'")
|
||||
expect(sfc).toContain("'page-visit': 'status-na'")
|
||||
expect(sfc).toContain('.status-na {')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,9 +8,8 @@ import {
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
formatTime,
|
||||
isLoginFailure,
|
||||
isSuccessful,
|
||||
methodBadgeClass,
|
||||
resultOutcome,
|
||||
} from '@/utils/audit'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -24,27 +23,26 @@ const emit = defineEmits<{
|
||||
|
||||
const close = () => emit('update:visible', false)
|
||||
|
||||
// 结果语义:登录失败记录(HTTP 状态码可能为 200/302)显示「登录失败」,
|
||||
// 其余按 HTTP 状态码判定成败
|
||||
const resultText = computed(() => {
|
||||
if (!props.log) {
|
||||
return '-'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return '登录失败'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
||||
})
|
||||
const RESULT_TEXT = {
|
||||
success: '成功',
|
||||
failure: '失败',
|
||||
// 认证端点的页面访问(升级前落库的 GET 记录):不是操作,不计成败
|
||||
'page-visit': '页面访问',
|
||||
} as const
|
||||
|
||||
const resultBadgeClass = computed(() => {
|
||||
if (!props.log) {
|
||||
return 'status-fail'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return 'status-fail'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? 'status-ok' : 'status-fail'
|
||||
})
|
||||
const RESULT_CLASS = {
|
||||
success: 'status-ok',
|
||||
failure: 'status-fail',
|
||||
'page-visit': 'status-na',
|
||||
} as const
|
||||
|
||||
// 结果语义(与列表徽标、结果筛选、CSV 导出同一规则):登录失败靠语义动作标注识别
|
||||
// (HTTP 状态码可能是 302/200),页面访问不计成败,其余按 HTTP 状态码判定
|
||||
const outcome = computed(() => (props.log ? resultOutcome(props.log.spec) : 'failure'))
|
||||
|
||||
const resultText = computed(() => RESULT_TEXT[outcome.value])
|
||||
|
||||
const resultBadgeClass = computed(() => RESULT_CLASS[outcome.value])
|
||||
|
||||
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
||||
const changes = computed(() => props.log?.spec.changes ?? [])
|
||||
@@ -347,6 +345,8 @@ const rawJson = computed(() =>
|
||||
}
|
||||
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
|
||||
.status-fail { color: #d71d1d; background: rgba(215, 29, 29, 0.12); }
|
||||
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰 */
|
||||
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
|
||||
.raw-json {
|
||||
margin-top: 1rem;
|
||||
font-size: 0.75rem;
|
||||
|
||||
@@ -110,4 +110,11 @@ describe('AuditLogList 页面外观', () => {
|
||||
expect(descIdx).toBeGreaterThan(resourceIdx)
|
||||
expect(statusIdx).toBeGreaterThan(descIdx)
|
||||
})
|
||||
|
||||
it('结果徽标有中性灰样式:页面访问(登录页/登出页的 GET)不计成败', () => {
|
||||
// 升级前落库的登录页访问记录原先显示绿色 200,误读为未知用户登录成功;
|
||||
// resultBadge 现判为 page-visit,需有既非成功色也非失败色的样式承接
|
||||
expect(sfc).toContain("resultBadge(log.spec)")
|
||||
expect(styleRule('.status-na')).toMatch(/color:\s*#6b7280/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -387,8 +387,9 @@ onMounted(fetchLogs)
|
||||
</VEntityField>
|
||||
</template>
|
||||
<template #end>
|
||||
<!-- 结果列:登录失败记录(HTTP 200/302 也可能是失败,语义动作已标注)
|
||||
显示红色「失败」,避免绿色 200/302 误读为登录成功;
|
||||
<!-- 结果列:登录失败显示红色「失败」(表单登录失败是 302,裸状态码是绿的),
|
||||
登录成功显示「成功」;升级前落库的登录页访问(GET,HTTP 200)显示
|
||||
灰色「—」——只是打开过登录页,不计成败,不再以绿色 200 误读为登录成功;
|
||||
徽标经 #title 插槽渲染(当前版本组件在无 title 时不渲染 #extra,
|
||||
原先徽标实际不可见) -->
|
||||
<VEntityField width="4rem">
|
||||
@@ -590,6 +591,8 @@ onMounted(fetchLogs)
|
||||
}
|
||||
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
|
||||
.status-fail { color: var(--audit-red); background: rgba(215, 29, 29, 0.12); }
|
||||
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰,既不是成功色也不是失败色 */
|
||||
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
|
||||
.audit-pagination {
|
||||
/* 在白卡内铺满整行:白底与上方列表左右对齐;上下各留 1rem,
|
||||
文字的垂直位置与原分页条一致;上边缘 1px 分隔线同控制台卡片 footer 观感 */
|
||||
|
||||
Reference in New Issue
Block a user