From 9e89ed75ed79b0d390eae51d154431f2f6b72319 Mon Sep 17 00:00:00 2001 From: Guichumo <836061373@qq.com> Date: Sun, 22 Nov 2026 15:47:47 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=99=BB=E5=BD=95=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=8C=89=20Halo=20=E7=99=BB=E5=BD=95=E7=AB=AF=E7=82=B9?= =?UTF-8?q?=E5=A5=91=E7=BA=A6=E5=88=A4=E5=AE=9A=EF=BC=8C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=A2=AB=20200/302=20=E6=8E=A9=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 同步更新。 --- README.md | 3 +- docs/operation-audit-design.md | 7 +- docs/operation-audit-tech-design.md | 2 + .../alert/LoginFailureAlertService.java | 16 ++- .../audit/AuditLogCsvExporter.java | 11 +- .../operationaudit/audit/AuditLogFilters.java | 12 +- .../operationaudit/audit/AuditRecorder.java | 27 ++-- .../operationaudit/audit/CaptureRule.java | 4 +- .../operationaudit/audit/LoginOutcome.java | 71 ++++++++++ .../audit/OperationAuditWebFilter.java | 40 +++++- .../audit/OperationDescription.java | 21 +++ .../alert/LoginFailureAlertServiceTest.java | 32 +++-- .../audit/AuditExportEndpointTest.java | 26 ++++ .../audit/AuditQueryEndpointTest.java | 24 +++- .../audit/AuditRecorderTest.java | 71 ++++++++-- .../audit/LoginOutcomeTest.java | 103 ++++++++++++++ .../audit/OperationAuditWebFilterTest.java | 128 +++++++++++++++--- .../audit/OperationDescriptionTest.java | 29 ++++ .../ui/src/utils/audit.spec.ts | 114 +++++++++++++++- plugin-operation-audit/ui/src/utils/audit.ts | 66 ++++++++- .../ui/src/views/AuditLogDetail.vue | 21 ++- .../ui/src/views/AuditLogList.vue | 15 +- 22 files changed, 743 insertions(+), 100 deletions(-) create mode 100644 plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/LoginOutcome.java create mode 100644 plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/LoginOutcomeTest.java diff --git a/README.md b/README.md index c6af240..ddd1bff 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资 |---|---| | 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) | | 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 | -| 语义动作标注 | 捕获时标注语义动作键(登录/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 | +| 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 | +| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标 `error` 参数区分):失败尝试与失败回显页(`GET /login?error=...`)在列表/详情/CSV 中显示红色「失败」,而非被页面渲染的绿色 HTTP 200 掩盖 | | 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 | | Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) | | 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) | diff --git a/docs/operation-audit-design.md b/docs/operation-audit-design.md index 0658195..03dc3b5 100644 --- a/docs/operation-audit-design.md +++ b/docs/operation-audit-design.md @@ -79,22 +79,23 @@ Console 左侧菜单新增"操作审计"页: | 功能 | 说明 | 阶段 | |---|---|---| -| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 | +| 语义动作标注 | 区分"发布/编辑/恢复/登录失败"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 | | 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 | | 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 | | 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 | | 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 | +| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否含 `error` 参数区分,见 `LoginOutcome`):失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)标注语义动作 `login-failure`,列表/详情/CSV 显示红色「失败」而非裸状态码,避免绿色 200/302 误读为登录成功;HTTP 状态码仍如实记录 | V2+ 已实现 | | 操作回滚 | 不在产品范围内 | 不做 | ## 7. 已知局限 -- 登录失败时无法得知尝试的用户名(解析请求体留到 V2) - 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准 - 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先) - reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见) - 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中 - 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更 -- 登录失败告警仅覆盖 POST /login 的失败结果(非 2xx),不含尝试的用户名(与登录记录同一局限);告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志 +- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向,失败目标含 `error` 参数):Halo 若调整失败重定向格式或引入新的登录方式,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登录页 GET 与登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志 +- 升级前落库的历史记录无法补标注登录失败:表单登录失败(POST /login,302)在列表中仍显示数字状态码,仅失败回显页(GET,路径含 `error` 参数)可现场推导;升级后新记录由捕获时标注(`spec.action = login-failure`),不再有此局限 - 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******` - 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中 - 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口) diff --git a/docs/operation-audit-tech-design.md b/docs/operation-audit-tech-design.md index e195c7e..f851d9b 100644 --- a/docs/operation-audit-tech-design.md +++ b/docs/operation-audit-tech-design.md @@ -51,6 +51,7 @@ plugin-operation-audit/ │ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8) │ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName) │ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试) + │ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标 error 参数(纯函数) │ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数) │ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照 │ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态) @@ -211,6 +212,7 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { ``` - `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。 +- 登录成败判定(`LoginOutcome`,纯函数):Halo 2.26 登录端点**表单提交的成功与失败均为 302 重定向**(成功 → `/uc` 或 2FA 页,失败 → `/login?error=invalid-credential&method=...`),仅 XHR/JSON 请求以 200/401 区分成败——不能只看状态码。规则:2xx 成功;3xx 以重定向目标查询串是否含 `error` 参数判定(含无值形式 `error`);其余(401、状态码缺失)失败。失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)的记录标注语义动作 `login-failure`(`spec.action`),列表/详情/CSV 据此显示红色「失败」;HTTP 状态码仍如实记录。告警服务(`LoginFailureAlertService`)按同一判定结果清零/累计,修复了旧版「2xx 即成功」把表单成功登录误计为失败的问题。 - 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。 ### 5.2 资源解析规则(通用,不追求语义完美) diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/LoginFailureAlertService.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/LoginFailureAlertService.java index 80b8530..d42fb67 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/LoginFailureAlertService.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/LoginFailureAlertService.java @@ -15,8 +15,10 @@ import run.halo.operationaudit.audit.RequestSnapshot; * 推送一次 JSON 告警。 * *

触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}): - * 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击 - * 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。 + * 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入—— + * 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分, + * 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值); + * 窗口过期同样重开,无失败时不累计。 * *

告警负载含失败次数、窗口、最近一次来源 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 {}", diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogCsvExporter.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogCsvExporter.java index 3ebef53..987412f 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogCsvExporter.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogCsvExporter.java @@ -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)), diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogFilters.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogFilters.java index a320080..13563bc 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogFilters.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLogFilters.java @@ -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); } diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditRecorder.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditRecorder.java index e8ed8e3..7b1d51f 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditRecorder.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditRecorder.java @@ -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()); diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/CaptureRule.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/CaptureRule.java index 10277bf..772ccca 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/CaptureRule.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/CaptureRule.java @@ -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); diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/LoginOutcome.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/LoginOutcome.java new file mode 100644 index 0000000..e71cf82 --- /dev/null +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/LoginOutcome.java @@ -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 登录端点契约): + * + *

+ */ + 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); + } +} diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationAuditWebFilter.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationAuditWebFilter.java index 3ed6112..fe03238 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationAuditWebFilter.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationAuditWebFilter.java @@ -34,10 +34,15 @@ import run.halo.operationaudit.alert.LoginFailureAlertService; * {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。 * *

登录失败告警(产品设计 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} 并进入告警负载。 + * + *

登录失败标注(语义动作 {@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()) diff --git a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationDescription.java b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationDescription.java index 4fc80cb..31892fc 100644 --- a/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationDescription.java +++ b/plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationDescription.java @@ -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 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); } diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/alert/LoginFailureAlertServiceTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/alert/LoginFailureAlertServiceTest.java index 19952a9..df8e5d4 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/alert/LoginFailureAlertServiceTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/alert/LoginFailureAlertServiceTest.java @@ -167,22 +167,24 @@ class LoginFailureAlertServiceTest { } @Test - void shouldTreat3xxAsFailure() { + void shouldCountFailureFromCallbackFlag() { + // 状态码→成败的解释已上移到 LoginOutcome(表单登录成败均为 302 重定向), + // 服务只按回调布尔计数:false 计失败 enableAlerts(1, 5); var snapshot = loginSnapshot(); - service.onLoginResult(snapshot, 302, null); + service.onLoginResult(snapshot, false, null); verify(sender, times(1)).send(eq(WEBHOOK_URL), any()); } @Test - void shouldTreat2xxAsSuccess() { + void shouldResetCounterOnSuccessCallback() { enableAlerts(1, 5); var snapshot = loginSnapshot(); - service.onLoginResult(snapshot, 200, null); - service.onLoginResult(snapshot, 204, null); + service.onLoginResult(snapshot, true, null); + service.onLoginResult(snapshot, true, null); verify(sender, never()).send(any(), any()); } @@ -192,7 +194,7 @@ class LoginFailureAlertServiceTest { enableAlerts(1, 5); var snapshot = loginSnapshot(); - service.onLoginResult(snapshot, 401, null); + service.onLoginResult(snapshot, false, null); verify(sender, times(1)).send(eq(WEBHOOK_URL), any()); } @@ -203,7 +205,7 @@ class LoginFailureAlertServiceTest { enableAlerts(1, 5); var snapshot = loginSnapshot(); - service.onLoginResult(snapshot, 401, "admin"); + service.onLoginResult(snapshot, false, "admin"); var payload = capturedPayload(); assertThat((String) payload.get("content")).contains("尝试的账号:admin"); @@ -216,7 +218,7 @@ class LoginFailureAlertServiceTest { enableAlerts(1, 5); var snapshot = loginSnapshot(); - service.onLoginResult(snapshot, 401, null); + service.onLoginResult(snapshot, false, null); var payload = capturedPayload(); assertThat((String) payload.get("content")).doesNotContain("尝试的账号"); @@ -231,8 +233,8 @@ class LoginFailureAlertServiceTest { var snapshot = loginSnapshot(); // 开关关闭:不计数也不告警(阈值 1 也应无任何副作用) - service.onLoginResult(snapshot, 401, null); - service.onLoginResult(snapshot, 401, null); + service.onLoginResult(snapshot, false, null); + service.onLoginResult(snapshot, false, null); verify(sender, never()).send(any(), any()); assertThat(service.failureCount).isZero(); @@ -247,8 +249,8 @@ class LoginFailureAlertServiceTest { var snapshot = loginSnapshot(); // 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警 - service.onLoginResult(snapshot, 401, null); - service.onLoginResult(snapshot, 401, null); + service.onLoginResult(snapshot, false, null); + service.onLoginResult(snapshot, false, null); verify(sender, never()).send(any(), any()); assertThat(service.failureCount).isZero(); @@ -259,7 +261,7 @@ class LoginFailureAlertServiceTest { when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom"))); var snapshot = loginSnapshot(); - assertThatCode(() -> service.onLoginResult(snapshot, 401, null)) + assertThatCode(() -> service.onLoginResult(snapshot, false, null)) .doesNotThrowAnyException(); verify(sender, never()).send(any(), any()); @@ -271,7 +273,7 @@ class LoginFailureAlertServiceTest { doThrow(new IllegalStateException("webhook broken")) .when(sender).send(any(), any()); - assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401, null)) + assertThatCode(() -> service.onLoginResult(loginSnapshot(), false, null)) .doesNotThrowAnyException(); } @@ -282,7 +284,7 @@ class LoginFailureAlertServiceTest { .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .build()); - service.onLoginResult(snapshot, 401, null); + service.onLoginResult(snapshot, false, null); var payload = capturedPayload(); assertThat((String) payload.get("content")).doesNotContain("()"); diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditExportEndpointTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditExportEndpointTest.java index d9b96b1..158c2a4 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditExportEndpointTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditExportEndpointTest.java @@ -114,6 +114,32 @@ class AuditExportEndpointTest { + ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0"); } + @Test + void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() { + // 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页 + // (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」; + // 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」 + 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"); + failedFormLogin.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION); + var failureEcho = auditLog("auditlog-2", time.plusSeconds(60), "unknown", null, "GET", + "auth", null, "/login?error=invalid-credential&method=local", 200, "119.53.161.18", + "Mozilla/5.0"); + failureEcho.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION); + stubSinglePage(List.of(failedFormLogin, failureEcho)); + + var body = exportAndGetBody(EXPORT_URI); + + var lines = body.split("\r\n"); + assertThat(lines).hasSize(3); + assertThat(lines[1]).isEqualTo(expectedTimeColumn(time) + + ",unknown,admin,POST,auth,,/login,登录失败,,失败,302,119.53.161.18,Mozilla/5.0"); + assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60)) + + ",unknown,,GET,auth,,/login?error=invalid-credential&method=local" + + ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0"); + } + @Test void shouldExportChangesColumnWhenRecordHasChanges() { var time = Instant.parse("2026-11-04T00:00:00Z"); diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditQueryEndpointTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditQueryEndpointTest.java index 9476809..ff55f04 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditQueryEndpointTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditQueryEndpointTest.java @@ -106,10 +106,30 @@ 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(无上界) + // failure = statusCode >= 400(无上界)或语义动作标注 login-failure + // (登录失败的 HTTP 状态码可能为 200/302) assertThat(condition) .contains("spec.statusCode") - .contains("400"); + .contains("400") + .contains("spec.action") + .contains("login-failure"); + } + + @Test + void shouldApplySuccessResultFilterExcludingLoginFailure() { + webClient.get() + .uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=success") + .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(); + // success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间) + assertThat(condition) + .contains("spec.statusCode") + .contains("spec.action") + .contains("login-failure"); } @Test diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditRecorderTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditRecorderTest.java index f0a7bd1..50f5582 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditRecorderTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/AuditRecorderTest.java @@ -55,7 +55,7 @@ class AuditRecorderTest { .header("User-Agent", "UA-1") .build()); - recorder.record(snapshot, new ChangeCapture(), 204, "admin", null); + recorder.record(snapshot, new ChangeCapture(), 204, "admin", null, false); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); @@ -78,14 +78,15 @@ class AuditRecorderTest { @Test void shouldUseUnknownUsernameWhenOperatorMissing() { - recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null); + // XHR/JSON 登录失败(401):过滤器判定 loginFailed=true,动作标注登录失败 + recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null, true); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); assertThat(captor.getValue().getSpec().getUsername()) .isEqualTo(AuditLogSpec.UNKNOWN_USERNAME); assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth"); - assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login"); + assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login-failure"); assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401); } @@ -93,21 +94,21 @@ class AuditRecorderTest { void shouldRecordAttemptedUsernameForLoginAttempt() { // 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库 recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, - AuditLogSpec.UNKNOWN_USERNAME, "zhangsan"); + AuditLogSpec.UNKNOWN_USERNAME, "zhangsan", true); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); var spec = captor.getValue().getSpec(); assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME); assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan"); - assertThat(spec.getAction()).isEqualTo("login"); + assertThat(spec.getAction()).isEqualTo("login-failure"); } @Test void shouldAnnotateSubActionSemanticAction() { recorder.record(RequestSnapshot.of(MockServerHttpRequest .put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish") - .build()), new ChangeCapture(), 200, "admin", null); + .build()), new ChangeCapture(), 200, "admin", null, false); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); @@ -115,13 +116,59 @@ class AuditRecorderTest { assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts"); } + // ===== 登录失败标注(LoginOutcome + 语义动作 login-failure) ===== + + @Test + void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() { + // 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true, + // 语义动作标注 login-failure;状态码仍如实记录 302 + recorder.record(snapshotOf("/login"), new ChangeCapture(), 302, + AuditLogSpec.UNKNOWN_USERNAME, null, true); + + 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(302); + } + + @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); + + 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"); + } + + @Test + void shouldKeepLoginActionOnSuccessfulLogin() { + // 表单登录成功(302 → /uc):语义动作仍为 login,不标注登录失败 + recorder.record(snapshotOf("/login"), new ChangeCapture(), 302, + AuditLogSpec.UNKNOWN_USERNAME, null, false); + + var captor = ArgumentCaptor.forClass(AuditLog.class); + verify(client).create(captor.capture()); + assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login"); + } + @Test void shouldSkipRecordingWhenAuditDisabled() { when(settingProvider.get()) .thenReturn(Mono.just(new AuditSettings(false, 30, null, null))); recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(), - 200, "admin", null); + 200, "admin", null, false); verify(client, never()).create(any(AuditLog.class)); } @@ -131,7 +178,7 @@ class AuditRecorderTest { when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom"))); assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), - new ChangeCapture(), 200, "admin", null)).doesNotThrowAnyException(); + new ChangeCapture(), 200, "admin", null, false)).doesNotThrowAnyException(); // 设置读取失败属于降级路径:按默认配置(开启)继续记录 verify(client).create(any(AuditLog.class)); @@ -143,7 +190,7 @@ class AuditRecorderTest { new IllegalStateException("storage unavailable"))); assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), - new ChangeCapture(), 500, "admin", null)).doesNotThrowAnyException(); + new ChangeCapture(), 500, "admin", null, false)).doesNotThrowAnyException(); } @Test @@ -161,7 +208,7 @@ class AuditRecorderTest { .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .build()); - recorder.record(snapshot, capture, 200, "admin", null); + recorder.record(snapshot, capture, 200, "admin", null, false); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); @@ -186,7 +233,7 @@ class AuditRecorderTest { .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .build()); - recorder.record(snapshot, capture, 403, "admin", null); + recorder.record(snapshot, capture, 403, "admin", null, false); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); @@ -197,7 +244,7 @@ class AuditRecorderTest { @Test void shouldNotRecordChangesWhenContextMissing() { recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"), - new ChangeCapture(), 200, "admin", null); + new ChangeCapture(), 200, "admin", null, false); var captor = ArgumentCaptor.forClass(AuditLog.class); verify(client).create(captor.capture()); diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/LoginOutcomeTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/LoginOutcomeTest.java new file mode 100644 index 0000000..4271073 --- /dev/null +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/LoginOutcomeTest.java @@ -0,0 +1,103 @@ +package run.halo.operationaudit.audit; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URI; +import org.junit.jupiter.api.Test; + +/** + * 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为 + * 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON + * 请求以 200/401 区分成败,成败判定必须结合重定向目标。 + */ +class LoginOutcomeTest { + + // ===== POST /login:状态码 + 重定向目标 ===== + + @Test + void xhrSuccessIsNotFailure() { + // XHR/JSON 登录成功:200 + 主体 JSON + assertThat(LoginOutcome.isFailure(200, null)).isFalse(); + assertThat(LoginOutcome.isFailure(204, null)).isFalse(); + } + + @Test + void xhrFailureIsFailure() { + // XHR/JSON 登录失败:401 + JSON 错误体 + assertThat(LoginOutcome.isFailure(401, null)).isTrue(); + } + + @Test + void formSuccessRedirectIsNotFailure() { + // 表单登录成功:302 → /uc(无 error 参数) + assertThat(LoginOutcome.isFailure(302, URI.create("/uc"))).isFalse(); + // 两步验证:302 → /challenges/two-factor/totp + assertThat(LoginOutcome.isFailure(302, + URI.create("/challenges/two-factor/totp"))).isFalse(); + } + + @Test + void formFailureRedirectWithErrorParamIsFailure() { + // 表单登录失败:302 → /login?error=invalid-credential&method=local + 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(); + } + + @Test + void redirectWithoutLocationIsNotFailure() { + // 3xx 但缺失 Location(无法确认失败):按成功处理,不凭空判失败 + assertThat(LoginOutcome.isFailure(302, null)).isFalse(); + } + + @Test + void missingOrZeroStatusIsFailure() { + // 状态码缺失(响应未写出)按失败处理,宁可多告警不漏报 + assertThat(LoginOutcome.isFailure(null, null)).isTrue(); + assertThat(LoginOutcome.isFailure(0, 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(); + } +} diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationAuditWebFilterTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationAuditWebFilterTest.java index ca9b273..f3b4033 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationAuditWebFilterTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationAuditWebFilterTest.java @@ -2,6 +2,7 @@ package run.halo.operationaudit.audit; import static org.assertj.core.api.Assertions.assertThat; 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.mock; @@ -29,8 +30,10 @@ import run.halo.operationaudit.alert.LoginFailureAlertService; * 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。 * 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。 * 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。 - * 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。 + * 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(由 LoginOutcome 判定: + * 表单登录成败均为 302 重定向,以 Location 是否含 error 参数区分;2xx 成功、其余失败)。 * 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。 + * 登录失败标注:POST /login 失败与 GET /login?error=... 失败回显随记录标注 login-failure。 */ class OperationAuditWebFilterTest { @@ -68,6 +71,26 @@ class OperationAuditWebFilterTest { } } + /** + * 终止型 chain:模拟 Halo 登录端点的 302 重定向响应(表单登录成败均为重定向, + * 以 Location 目标是否含 error 参数区分成败)后完成。 + */ + private static final class RedirectWebFilterChainStub implements + org.springframework.web.server.WebFilterChain { + private final java.net.URI location; + + private RedirectWebFilterChainStub(java.net.URI location) { + this.location = location; + } + + @Override + public Mono filter(org.springframework.web.server.ServerWebExchange exchange) { + exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FOUND); + exchange.getResponse().getHeaders().setLocation(location); + return Mono.empty(); + } + } + @BeforeEach void setUp() { recorder = mock(AuditRecorder.class); @@ -97,7 +120,7 @@ class OperationAuditWebFilterTest { .verifyComplete(); verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), - eq("admin"), isNull()); + eq("admin"), isNull(), eq(false)); } @Test @@ -108,7 +131,7 @@ class OperationAuditWebFilterTest { StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); - verify(recorder, never()).record(any(), any(), any(), any(), any()); + verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -121,7 +144,7 @@ class OperationAuditWebFilterTest { // 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录 verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), - eq(AuditLogSpec.UNKNOWN_USERNAME), isNull()); + eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false)); } @Test @@ -137,8 +160,8 @@ class OperationAuditWebFilterTest { StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), - eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin")); - verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200), + eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false)); + verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true), eq("admin")); } @@ -151,7 +174,7 @@ class OperationAuditWebFilterTest { StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); - verify(recorder, never()).record(any(), any(), any(), any(), any()); + verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -168,7 +191,7 @@ class OperationAuditWebFilterTest { .contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous))) .verifyComplete(); - verify(recorder, never()).record(any(), any(), any(), any(), any()); + verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -187,7 +210,7 @@ class OperationAuditWebFilterTest { var captor = ArgumentCaptor.forClass(RequestSnapshot.class); verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"), - isNull()); + isNull(), eq(false)); assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType()) .isEqualTo("auth"); } @@ -219,7 +242,7 @@ class OperationAuditWebFilterTest { // 请求期创建的同一个 capture 实例被透传给记录阶段 verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200), - eq("admin"), isNull()); + eq("admin"), isNull(), eq(false)); } @Test @@ -246,7 +269,7 @@ class OperationAuditWebFilterTest { verify(writeMarker).onRequestStart(any()); verify(writeMarker).onRequestComplete(any()); - verify(recorder, never()).record(any(), any(), any(), any(), any()); + verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -261,22 +284,23 @@ class OperationAuditWebFilterTest { verify(writeMarker, never()).onRequestComplete(any()); } - // ===== 登录失败告警(产品设计 V2「告警通知」) ===== + // ===== 登录失败告警与登录结果判定(产品设计 V2「告警通知」/ LoginOutcome) ===== @Test - void shouldNotifyLoginResultOnLoginAttempt() { + void shouldNotifyLoginSuccessOnXhrLogin() { var exchange = MockServerWebExchange.from(MockServerHttpRequest .post("/login") .build()); StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); - verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200), + // XHR/JSON 登录成功(200):回调成功,清零计数 + verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true), isNull()); } @Test - void shouldNotifyLoginFailureStatusOnFailedLogin() { + void shouldNotifyLoginFailureOnUnauthorized() { var exchange = MockServerWebExchange.from(MockServerHttpRequest .post("/login") .build()); @@ -285,11 +309,77 @@ class OperationAuditWebFilterTest { new FailingWebFilterChainStub(org.springframework.http.HttpStatus.UNAUTHORIZED))) .verifyComplete(); - // 非常响应(401)同样回调,由告警服务按失败累计 - verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401), + // XHR/JSON 登录失败(401)同样回调,由告警服务按失败累计 + verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false), isNull()); } + @Test + void shouldTreatFormFailureRedirectAsLoginFailure() { + // 表单登录失败:302 → /login?error=invalid-credential&method=local, + // 与成功重定向同状态码,必须按 Location 目标判定 + var exchange = MockServerWebExchange.from(MockServerHttpRequest + .post("/login") + .build()); + + StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub( + java.net.URI.create("/login?error=invalid-credential&method=local")))) + .verifyComplete(); + + verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false), + isNull()); + verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(302), + eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true)); + } + + @Test + void shouldTreatFormSuccessRedirectAsLoginSuccess() { + // 表单登录成功:302 → /uc(无 error 参数)——修复前会被 2xx 判定误计为失败 + var exchange = MockServerWebExchange.from(MockServerHttpRequest + .post("/login") + .build()); + + StepVerifier.create(filter.filter(exchange, + new RedirectWebFilterChainStub(java.net.URI.create("/uc")))) + .verifyComplete(); + + verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true), + isNull()); + verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(302), + eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false)); + } + + @Test + void shouldRecordLoginPageErrorEchoAsLoginFailure() { + // 登录失败回显:GET /login?error=invalid-credential 页面渲染 HTTP 200, + // 审计记录标注登录失败(loginFailed=true),但不是登录尝试、不触发告警 + var exchange = MockServerWebExchange.from(MockServerHttpRequest + .get("/login?error=invalid-credential&method=local") + .build()); + + StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); + + verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), + eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true)); + verify(loginFailureAlertService, never()) + .onLoginResult(any(RequestSnapshot.class), anyBoolean(), any()); + } + + @Test + void shouldRecordPlainLoginPageAsLoginWithoutFailureMark() { + // 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败 + var exchange = MockServerWebExchange.from(MockServerHttpRequest + .get("/login") + .build()); + + StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); + + verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), + eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false)); + verify(loginFailureAlertService, never()) + .onLoginResult(any(RequestSnapshot.class), anyBoolean(), any()); + } + @Test void shouldNotNotifyLoginResultForLoginPageOrLogout() { // 登录页 GET 与登出不是登录尝试 @@ -304,7 +394,7 @@ class OperationAuditWebFilterTest { StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete(); verify(loginFailureAlertService, never()) - .onLoginResult(any(RequestSnapshot.class), any(), any()); + .onLoginResult(any(RequestSnapshot.class), anyBoolean(), any()); } @Test @@ -316,6 +406,6 @@ class OperationAuditWebFilterTest { StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); verify(loginFailureAlertService, never()) - .onLoginResult(any(RequestSnapshot.class), any(), any()); + .onLoginResult(any(RequestSnapshot.class), anyBoolean(), any()); } } diff --git a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationDescriptionTest.java b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationDescriptionTest.java index da2e6b5..2167497 100644 --- a/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationDescriptionTest.java +++ b/plugin-operation-audit/src/test/java/run/halo/operationaudit/audit/OperationDescriptionTest.java @@ -197,6 +197,9 @@ class OperationDescriptionTest { @Test void shouldDescribeFromActionKey() { assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录"); + // 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显) + assertThat(OperationDescription.describeAction("login-failure", "auth")) + .isEqualTo("登录失败"); assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出"); assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作"); assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户"); @@ -215,4 +218,30 @@ class OperationDescriptionTest { assertThat(OperationDescription.describeAction(null, "posts")).isNull(); assertThat(OperationDescription.describeAction("bogus", "posts")).isNull(); } + + @Test + void shouldDescribeSpecPreferingStoredAction() { + // 落库语义动作优先:登录失败标注(回显页 HTTP 200 无法由路径重新推导出失败) + var spec = new AuditLogSpec(); + spec.setMethod("GET"); + spec.setResourceType("auth"); + spec.setPath("/login?error=invalid-credential&method=local"); + spec.setAction("login-failure"); + assertThat(OperationDescription.describe(spec)).isEqualTo("登录失败"); + + // 无标注(历史记录)回退 method/path 现场推导 + var legacy = new AuditLogSpec(); + legacy.setMethod("POST"); + legacy.setResourceType("auth"); + legacy.setPath("/login"); + assertThat(OperationDescription.describe(legacy)).isEqualTo("登录"); + + // 落库标注未识别时同样回退现场推导 + var bogus = new AuditLogSpec(); + bogus.setMethod("PUT"); + bogus.setResourceType("posts"); + bogus.setPath("/apis/content.halo.run/v1alpha1/posts/abc"); + bogus.setAction("bogus"); + assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章"); + } } diff --git a/plugin-operation-audit/ui/src/utils/audit.spec.ts b/plugin-operation-audit/ui/src/utils/audit.spec.ts index 14d2a25..728ad32 100644 --- a/plugin-operation-audit/ui/src/utils/audit.spec.ts +++ b/plugin-operation-audit/ui/src/utils/audit.spec.ts @@ -6,6 +6,8 @@ import { deriveAction, describeOperation, displayUsername, + isLoginFailure, + resultBadge, SEMANTIC_ACTIONS, SYSTEM_USERNAME, UNKNOWN_USERNAME, @@ -153,6 +155,19 @@ describe('deriveAction 语义动作推导', () => { expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth') }) + it('登录失败回显(GET /login?error=...)推导为 login-failure', () => { + // 登录失败后 Halo 重定向到带 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?errors=1')).toBe('login') + }) + it('子动作段优先于 HTTP 方法', () => { expect(deriveAction('PUT', 'posts', '/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish')).toBe('publish') @@ -219,6 +234,101 @@ describe('describeOperation 落库标注优先', () => { action: 'bogus', }))).toBe('修改文章') }) + + it('登录失败标注(login-failure)描述为 登录失败', () => { + // 表单登录失败(POST /login,302)与失败回显页(GET /login?error=...,200) + // 均落库标注,描述为 登录失败 而非按路径推导出的 登录 + expect(describeOperation(spec({ + method: 'POST', + resourceType: 'auth', + path: '/login', + action: 'login-failure', + }))).toBe('登录失败') + 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('登录失败') + }) +}) + +describe('isLoginFailure / resultBadge 登录失败结果展示', () => { + it('落库标注 login-failure 判定为登录失败(HTTP 200/302 也可能是失败)', () => { + expect(isLoginFailure(spec({ + method: 'POST', + resourceType: 'auth', + path: '/login', + statusCode: 302, + action: 'login-failure', + }))).toBe(true) + expect(isLoginFailure(spec({ + method: 'GET', + resourceType: 'auth', + path: '/login?error=invalid-credential&method=local', + statusCode: 200, + action: 'login-failure', + }))).toBe(true) + }) + + 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('登录失败记录结果徽标为红色 失败(不显示裸状态码)', () => { + // 失败回显页 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('非登录记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => { + 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' }) + expect(resultBadge(spec({ statusCode: 500 }))).toEqual({ text: '500', class: 'status-fail' }) + expect(resultBadge(spec({ statusCode: undefined }))) + .toEqual({ text: 'undefined', class: 'status-fail' }) + }) }) describe('SEMANTIC_ACTIONS 筛选选项', () => { @@ -231,9 +341,9 @@ describe('SEMANTIC_ACTIONS 筛选选项', () => { }) it('覆盖全部可落库的语义动作键(view 不会被捕获规则记录,除外)', () => { - // 全量枚举:登录/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并) + // 全量枚举:登录/登录失败/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并) const storable = new Set([ - 'login', 'logout', 'auth', + 'login', 'login-failure', 'logout', 'auth', 'create', 'update', 'delete', 'publish', 'unpublish', 'recycle', 'restore', 'enable', 'disable', 'upgrade', 'uninstall', 'reload', 'reply', 'recalculate', diff --git a/plugin-operation-audit/ui/src/utils/audit.ts b/plugin-operation-audit/ui/src/utils/audit.ts index 8391641..5ba71a0 100644 --- a/plugin-operation-audit/ui/src/utils/audit.ts +++ b/plugin-operation-audit/ui/src/utils/audit.ts @@ -104,9 +104,13 @@ const SEGMENT_ACTIONS: Record = { resetpassword: 'resetpassword', } +/** 登录失败语义动作键(与后端 OperationDescription.LOGIN_FAILURE_ACTION 同步)。 */ +const LOGIN_FAILURE_ACTION = 'login-failure' + /** 语义动作键 → 完整短语(不拼资源名)。 */ const ACTION_PHRASES: Record = { login: '登录', + [LOGIN_FAILURE_ACTION]: '登录失败', logout: '登出', auth: '认证操作', password: '修改密码', @@ -138,6 +142,7 @@ const ACTION_VERBS: Record = { */ export const SEMANTIC_ACTIONS: Array<{ value: string; label: string }> = [ { value: 'login', label: '登录' }, + { value: 'login-failure', label: '登录失败' }, { value: 'logout', label: '登出' }, { value: 'auth', label: '认证操作' }, { value: 'create', label: '新建' }, @@ -167,10 +172,32 @@ function pathWithoutQuery(path?: string | null): string { return queryStart >= 0 ? path.slice(0, queryStart) : path } +/** + * 查询串是否含 error 参数(可为无值形式 error)。 + * 登录失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。 + */ +function hasErrorParam(path?: string | null): boolean { + if (!path) { + return false + } + const queryStart = path.indexOf('?') + if (queryStart < 0) { + return false + } + return path + .slice(queryStart + 1) + .split('&') + .some((pair) => (pair.indexOf('=') < 0 ? pair : pair.slice(0, pair.indexOf('='))) === 'error') +} + /** * 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致): - * 登录/登出/认证操作由路径判定,子动作段优先于 HTTP 方法,其余方法归为 - * create/update/delete/view;无法识别返回 null。 + * 登录/登录失败/登出/认证操作由路径判定(GET /login?error=... 为登录失败回显), + * 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view; + * 无法识别返回 null。 + * + *

历史局限:升级前落库的表单登录失败记录(POST /login,302)无法由路径重新 + * 推导出失败,仍推导为 login;仅回显页(GET,error 参数在路径中)可现场推导。 */ export function deriveAction( method: string, @@ -179,7 +206,7 @@ export function deriveAction( ): string | null { const cleanPath = pathWithoutQuery(path) if (cleanPath === '/login') { - return 'login' + return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login' } if (cleanPath === '/logout') { return 'logout' @@ -250,6 +277,39 @@ export function isSuccessful(statusCode?: number | null): boolean { return statusCode != null && statusCode >= 200 && statusCode < 400 } +/** 结果徽标展示形态:文本与配色 class。 */ +export interface ResultBadge { + text: string + class: 'status-ok' | 'status-fail' +} + +/** + * 结果列徽标(列表/详情共用):登录失败记录(语义动作 login-failure,HTTP 状态码可能 + * 为 200/302——失败回显页渲染/表单登录失败重定向)显示「失败」而非裸状态码,避免 + * 绿色 200/302 误读为登录成功;其余记录保持原状——按 HTTP 状态码展示 + * (2xx/3xx 绿、其余红),与既有行为一致。 + */ +export function resultBadge(spec: Pick): ResultBadge { + if (isLoginFailure(spec)) { + return { text: '失败', class: 'status-fail' } + } + return { + text: String(spec.statusCode), + class: isSuccessful(spec.statusCode) ? 'status-ok' : 'status-fail', + } +} + +/** + * 是否为登录失败记录:优先落库语义动作标注(spec.action,POST /login 失败与 + * 失败回显均落库),历史记录回退由路径现场推导(仅回显页可推导)。 + */ +export function isLoginFailure(spec: Pick): boolean { + const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path) + return action === LOGIN_FAILURE_ACTION +} + /** 变更类型 → 中文标签(未知类型回退原始值)。 */ const CHANGE_TYPE_LABELS: Record = { ADDED: '新增', diff --git a/plugin-operation-audit/ui/src/views/AuditLogDetail.vue b/plugin-operation-audit/ui/src/views/AuditLogDetail.vue index 16142ba..b4616b6 100644 --- a/plugin-operation-audit/ui/src/views/AuditLogDetail.vue +++ b/plugin-operation-audit/ui/src/views/AuditLogDetail.vue @@ -8,6 +8,7 @@ import { describeOperation, displayUsername, formatTime, + isLoginFailure, isSuccessful, methodBadgeClass, } from '@/utils/audit' @@ -23,13 +24,28 @@ 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 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' +}) + /** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */ const changes = computed(() => props.log?.spec.changes ?? []) @@ -105,10 +121,7 @@ const rawJson = computed(() =>

结果
- + {{ resultText }} · {{ log.spec.statusCode }}
diff --git a/plugin-operation-audit/ui/src/views/AuditLogList.vue b/plugin-operation-audit/ui/src/views/AuditLogList.vue index 46e506f..bc325d0 100644 --- a/plugin-operation-audit/ui/src/views/AuditLogList.vue +++ b/plugin-operation-audit/ui/src/views/AuditLogList.vue @@ -24,9 +24,9 @@ import { describeOperation, displayUsername, formatTime, - isSuccessful, localDateTimeToInstant, methodBadgeClass, + resultBadge, SEMANTIC_ACTIONS, } from '@/utils/audit' import AuditLogDetail from './AuditLogDetail.vue' @@ -382,15 +382,14 @@ onMounted(fetchLogs)