Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb3ff6ef17 | ||
|
|
3269bafbc4 | ||
|
|
08e7bd8a12 | ||
|
|
cb86a3d305 |
@@ -0,0 +1,101 @@
|
||||
# Halo 操作审计插件 · 功能增减评审
|
||||
|
||||
> 版本:v0.1 · 日期:2026-11-21
|
||||
> 关联文档:[operation-audit-design.md](./operation-audit-design.md)(产品设计)·
|
||||
> [operation-audit-tech-design.md](./operation-audit-tech-design.md)(技术方案)
|
||||
> 插件标识:`operation-audit`(工作目录 `plugin-operation-audit/`)
|
||||
|
||||
## 1. 总体结论
|
||||
|
||||
插件当前功能已相对其定位(站长自用、轻量、完整性优先于丰富度)饱和,V2 规划项
|
||||
(语义动作标注、字段级 diff、系统内部变更、CSV 导出、登录失败告警)均已落地且有测试覆盖。
|
||||
|
||||
- **减少侧无硬需求**:没有该砍的功能,比"减少"更重要的是守住第 3 节的"不做"清单;
|
||||
- **增加侧的重点**是补两三个安全价值短板,而非扩展功能面。
|
||||
|
||||
## 2. 建议增加(按价值排序)
|
||||
|
||||
### P0-1 登录失败记录尝试的用户名(补 V2 欠账)
|
||||
|
||||
**缺口**:告警只含"窗口内失败次数 + 来源 IP/User-Agent",不知道哪个账号被爆破——
|
||||
是定向撞库还是无差别扫描无法区分,告警的处置价值大打折扣。对应产品文档第 7 节
|
||||
已知局限"登录失败时无法得知尝试的用户名(解析请求体留到 V2)"。
|
||||
|
||||
**方案要点**:
|
||||
|
||||
- 请求体缓存基建已在 `ChangeCaptureManager`,但 `/login` 非注册模型、请求为表单形态,
|
||||
需为登录端点补一条独立的请求体读取(与现有 JSON 缓存逻辑分开);
|
||||
- 只提取 `username`,**密码绝不落库**(提取字段白名单制,并兜底受现有敏感字段脱敏规则约束);
|
||||
- 落库为新增字段(如 `spec.attemptedUsername`),不与现有 `operator`(登录失败记"未知用户")冲突;
|
||||
不建索引(无需按其筛选);CSV 导出增加"尝试用户"列;
|
||||
- 告警 payload 的 `data` 增加 `attemptedUsername`。
|
||||
|
||||
**测试点**:表单体解析(成功/无 username/异常静默)、落库字段、CSV 列、告警 payload 字段。
|
||||
|
||||
### P0-2 Webhook「发送测试告警」
|
||||
|
||||
**缺口**:验证 webhook 配置正确的唯一方式是等真实告警触发——阈值窗口未达到就永远
|
||||
无法验证配置(地址错误、网络不通均不可知)。
|
||||
|
||||
**方案要点**:
|
||||
|
||||
- 在插件设置「告警通知」区增加手动推送入口,复用 `AlertWebhookSender`(fire-and-forget、
|
||||
超时 10 秒、失败静默);
|
||||
- 使用独立 `type: "test"`(与 `login-failure` 区分),接收方可识别为测试消息;
|
||||
- 推送结果以设置页提示 + 运行日志反馈,不新增设置项。
|
||||
|
||||
**测试点**:推送调用、payload 结构、失败静默不抛出。
|
||||
|
||||
### P1-1 列表行内「查看该资源历史」
|
||||
|
||||
**缺口**:产品定位第一个典型场景("这篇文章谁改过的")目前需手动选资源类型 + 填关键字。
|
||||
|
||||
**方案要点**:
|
||||
|
||||
- 纯前端改动(`ui/src/views/AuditLogList.vue`):行内增加快捷动作,点击预填
|
||||
`resourceType` + 关键字(关键字匹配资源名称/路径)并刷新列表;
|
||||
- 不新增后端参数,与现有筛选/导出条件共用同一套状态。
|
||||
|
||||
**测试点**:vitest 断言筛选预填与请求参数生成。
|
||||
|
||||
### 可选(低优先级,按需取舍)
|
||||
|
||||
| 项 | 说明 | 约束 |
|
||||
|---|---|---|
|
||||
| 列表顶部轻量概览 | 总记录数 + 最早记录时间(感知保留期/存储占用) | 两行统计文字,不做仪表盘 |
|
||||
| 敏感操作即时告警 | 复用 webhook 通道,按语义动作键(删除用户、角色变更、插件启停等)配置即时推送 | 可配置白名单 + 默认关,防止滑向过度工程 |
|
||||
| i18n(至少英文) | 上架应用市场的前置条件 | 仅决定上架时才做,自用不需要 |
|
||||
|
||||
## 3. 明确不做(维持现有边界)
|
||||
|
||||
- **读操作审计**:量级爆炸,违背轻量原则;
|
||||
- **操作回滚**:产品文档已定不做;
|
||||
- **钉钉/企业微信/飞书格式适配**:已定由中转服务侧转换;
|
||||
- **篡改哈希链/审计链**:自用场景过度工程;
|
||||
- **IP 封禁/防火墙**:是另一类插件的职责,审计只负责留痕;
|
||||
- **JSON 导出**:CSV 已覆盖需求。
|
||||
|
||||
唯一可考虑的简化:**动作(HTTP 方法)与语义动作两个筛选维度重叠**——语义动作覆盖后
|
||||
按方法筛选使用频率很低,若嫌筛选器拥挤可合并;但收益小,不值得专门开工。
|
||||
|
||||
## 4. 顺带观察(非性能问题)
|
||||
|
||||
审计写入为静默降级(`AuditRecorder` 失败仅记 warn 日志),意味着审计可能存在**用户无感知
|
||||
的静默盲区**。低成本缓解:在设置页展示"近 24h 写入失败次数"一类可见性计数。优先级不高,
|
||||
但比新增功能更贴近"完整性优先"的设计原则。
|
||||
|
||||
## 5. 实施顺序与验收
|
||||
|
||||
1. P0-1(登录用户名)→ 2. P0-2(测试告警)→ 3. P1-1(资源历史入口);
|
||||
2. 三项均可独立提交,遵循仓库约定(每项改动独立 commit + 对应测试全绿后交付);
|
||||
3. 可选项不排期,待明确需求后再评审。
|
||||
|
||||
## 6. 涉及文件索引
|
||||
|
||||
- `plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/ChangeCaptureManager.java`(请求体缓存基建)
|
||||
- `plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/OperationAuditWebFilter.java`(捕获过滤器)
|
||||
- `plugin-operation-audit/src/main/java/run/halo/operationaudit/audit/AuditLog.java` / `AuditLogSpec.java`(模型字段)
|
||||
- `plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/AlertWebhookSender.java`(告警推送)
|
||||
- `plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/LoginFailureAlertService.java`(阈值窗口)
|
||||
- `plugin-operation-audit/ui/src/views/AuditLogList.vue`(列表筛选)
|
||||
- `plugin-operation-audit/README.md` 第 7 节(已知局限,落地后需同步更新)
|
||||
@@ -9,7 +9,8 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
|
||||
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
|
||||
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出)。
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出),登录请求白名单提取尝试的用户名落库
|
||||
(`spec.attemptedUsername`,密码等其余字段绝不落库,登录失败时操作者记"未知用户")。
|
||||
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
|
||||
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
|
||||
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
|
||||
@@ -18,13 +19,17 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
中文操作描述由同一套推导生成,贯穿列表、详情与导出 CSV,历史记录同样适用。
|
||||
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 八维筛选(操作者/资源类型/动作/
|
||||
语义动作/结果/时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
|
||||
有资源名称的记录行内提供「历史」快捷动作:一键预填资源类型 + 资源名关键字并刷新列表,
|
||||
直接回答"这个资源被谁改过"(功能评审 P1-1)。
|
||||
- **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成
|
||||
(UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、
|
||||
动作、资源类型、资源名称、路径、操作描述、结果、状态码、来源 IP、User-Agent),
|
||||
含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
|
||||
尝试用户、动作、资源类型、资源名称、路径、操作描述、变更、结果、状态码、来源 IP、
|
||||
User-Agent),含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
|
||||
- **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警
|
||||
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零);独立于审计开关,
|
||||
在插件设置「告警通知」中配置(默认关闭)。
|
||||
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零;内容含尝试的用户名,
|
||||
可区分定向撞库与无差别扫描);独立于审计开关,在插件设置「告警通知」中配置(默认关闭)。
|
||||
该区提供「发送测试告警」入口:以 `type: "test"` 测试消息向已保存的 Webhook 地址推送并
|
||||
同步反馈发送结果,无需等待真实告警即可验证配置是否可用。
|
||||
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
|
||||
启动时补跑一次。
|
||||
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
|
||||
@@ -53,6 +58,7 @@ Console「插件 → 操作审计 → 设置」:
|
||||
| 保留天数 | 90 | 最小 7 天;过期记录每日自动清理 |
|
||||
| 启用登录失败告警 | 关 | 统计窗口内失败达到阈值时推送 Webhook 告警(独立于审计开关) |
|
||||
| Webhook 地址 | 空 | 接收告警的 http(s) 地址,JSON POST 异步推送 |
|
||||
| 发送测试告警(按钮) | - | 向已保存的 Webhook 地址推送 `type: "test"` 测试消息并直接反馈发送结果(不保存配置值,仅超级管理员可用) |
|
||||
| 触发阈值(次) | 5 | 统计窗口内累计登录失败达到该次数即触发一次告警 |
|
||||
| 统计窗口(分钟) | 5 | 失败次数的累计窗口;告警后窗口重开,登录成功立即清零 |
|
||||
|
||||
@@ -65,13 +71,25 @@ Console「插件 → 操作审计 → 设置」:
|
||||
{
|
||||
"type": "login-failure",
|
||||
"title": "操作审计告警:登录失败",
|
||||
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...)。
|
||||
可在 Console「操作审计」查看详情。",
|
||||
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...),
|
||||
尝试的账号:admin。可在 Console「操作审计」查看详情。",
|
||||
"timestamp": "2026-11-21T12:34:56Z",
|
||||
"data": { "failures": 5, "windowMinutes": 5, "remoteIp": "1.2.3.4", "userAgent": "..." }
|
||||
"data": {
|
||||
"failures": 5,
|
||||
"windowMinutes": 5,
|
||||
"remoteIp": "1.2.3.4",
|
||||
"userAgent": "...",
|
||||
"attemptedUsername": "admin"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`attemptedUsername` 为登录请求体中白名单提取的尝试用户名,提取失败时为 `null`。
|
||||
|
||||
「发送测试告警」以相同结构推送 `type: "test"` 的测试消息(接收方可识别为测试消息),
|
||||
推送结果同步返回并提示到设置页(成功/失败 + 原因摘要),同时反馈到运行日志;
|
||||
Webhook 未配置或非法时提示先保存设置。
|
||||
|
||||
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
|
||||
## 模型 group 与权限标识
|
||||
@@ -86,8 +104,6 @@ Console「插件 → 操作审计 → 设置」:
|
||||
|
||||
## 已知局限(对应产品设计第 7 节)
|
||||
|
||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2),记为"未知用户";
|
||||
登录失败告警同样不含尝试的用户名,仅含失败次数与最近一次来源 IP/User-Agent。
|
||||
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)
|
||||
不记录(几乎均伴随页面/API 操作,已被过滤器捕获)。
|
||||
- 系统内部变更的描述由事件类型推导(更新/删除),无法像页面操作那样区分"定时发布/恢复"
|
||||
@@ -126,11 +142,24 @@ Console「插件 → 操作审计 → 设置」:
|
||||
(告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经
|
||||
`AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;`AlertWebhookSender`
|
||||
以 JSON POST 异步推送(fire-and-forget,超时 10 秒、失败不重试不抛出)。
|
||||
- 关于测试:`./gradlew test`(当前 188 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、查询端点参数校验、导出 CSV
|
||||
- 登录尝试用户名(功能评审 P0-1):`LoginAttemptCapture` 为登录端点单独缓存请求体
|
||||
(表单/JSON 双形态,Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制
|
||||
仅提取 `username` 并经现有敏感字段脱敏规则兜底,随 `spec.attemptedUsername` 落库
|
||||
并进入告警负载;与审计开关、告警开关均无关(消费方各自决定是否使用)。
|
||||
- Webhook 测试告警(功能评审 P0-2):`AlertWebhookSender.sendForResult` 在
|
||||
fire-and-forget 推送之外提供结果化推送(送达与否 + 原因摘要,超时/网络错误/非 2xx/
|
||||
URL 非法一律归一为失败结果,永不抛出,真实告警路径语义不变);`AlertTestEndpoint`
|
||||
以 `POST /apis/audit.guichumo.com/v1alpha1/alerts/-/test` 同步等待结果返回,RBAC
|
||||
资源组合 `alerts + alerts/test`(create 动词)不在只读角色模板授权内,仅管理角色可用;
|
||||
设置页经自定义 FormKit 输入(Halo 2.25+ `formkit.inputs`,`@formkit/vue` 已被
|
||||
bundler kit 外部化为宿主共享模块)注册「发送测试告警」按钮,`ignore: true` 不落任何配置值。
|
||||
- 关于测试:`./gradlew test`(当前 219 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、登录尝试用户名提取
|
||||
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
|
||||
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
|
||||
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
|
||||
(阈值窗口推进/告警防轰炸/成功清零/设置归一/真实 HTTP 推送与静默降级);Console UI 以
|
||||
(阈值窗口推进/告警防轰炸/成功清零/设置归一/真实 HTTP 推送与静默降级/Webhook 结果化
|
||||
推送与测试端点反馈/测试负载结构);Console UI 以
|
||||
vitest 断言
|
||||
路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)+ 类型检查 + 构建通过为准
|
||||
(技术方案 §7,MVP 不引入组件测试)。
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
/**
|
||||
* Webhook 推送结果(功能评审 P0-2)。
|
||||
*
|
||||
* <p>{@code success} 为 true 表示接收方返回 2xx(送达);false 表示失败,
|
||||
* {@code message} 携带原因摘要(异常类名 + 消息或 HTTP 状态),供发送方记日志、
|
||||
* 供测试告警端点({@link AlertTestEndpoint})反馈到设置页提示。
|
||||
*
|
||||
* @param success 是否送达(接收方 2xx)
|
||||
* @param message 成功时为响应状态摘要(如 "HTTP 200"),失败时为原因摘要
|
||||
*/
|
||||
public record AlertSendResult(boolean success, String message) {
|
||||
|
||||
public static AlertSendResult ok(int statusCode) {
|
||||
return new AlertSendResult(true, "HTTP " + statusCode);
|
||||
}
|
||||
|
||||
public static AlertSendResult failure(Throwable cause) {
|
||||
var message = cause.getMessage();
|
||||
var summary = message != null && !message.isBlank()
|
||||
? cause.getClass().getSimpleName() + ": " + message
|
||||
: cause.getClass().getSimpleName();
|
||||
return new AlertSendResult(false, summary);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.core.extension.endpoint.CustomEndpoint;
|
||||
import run.halo.app.extension.GroupVersion;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 告警测试端点(功能评审 P0-2):验证 Webhook 配置是否可用——以当前配置地址推送一条
|
||||
* {@code type: "test"} 测试消息(与 login-failure 区分,接收方可识别为测试消息),
|
||||
* 同步等待推送结果并返回,供插件设置「告警通知」区的「发送测试告警」入口直接提示。
|
||||
*
|
||||
* <p>路径 {@code POST /apis/{group}/v1alpha1/alerts/-/test}。RBAC 资源组合为
|
||||
* {@code alerts + 子资源 test}(POST → create 动词):只读角色模板
|
||||
* (auditlogs get/list)未授权该资源,仅超级管理员等管理角色可调用——与
|
||||
* "验证告警配置"的管理动作语义一致。
|
||||
*
|
||||
* <p>Webhook 地址未配置或非法(非 http(s))返回 400;推送失败不抛出——以 200 +
|
||||
* {@code success=false} 返回原因摘要(fire-and-forget 语义不变:真实告警路径仍异步
|
||||
* 不等待)。推送结果同时反馈到运行日志,任何异常不影响主流程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AlertTestEndpoint implements CustomEndpoint {
|
||||
|
||||
private final AlertSettingProvider settingProvider;
|
||||
private final AlertWebhookSender sender;
|
||||
|
||||
@Override
|
||||
public GroupVersion groupVersion() {
|
||||
return GroupVersion.parseAPIVersion(AuditLog.GROUP + "/v1alpha1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouterFunction<ServerResponse> endpoint() {
|
||||
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
|
||||
.POST("alerts/-/test", this::test, builder -> builder
|
||||
.operationId("TestAlertWebhook")
|
||||
.description("向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回"
|
||||
+ "推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;"
|
||||
+ "Webhook 未配置或非法时返回 400")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> test(ServerRequest request) {
|
||||
return settingProvider.get()
|
||||
.flatMap(settings -> {
|
||||
var url = settings.webhookUrlOrDefault();
|
||||
if (url == null) {
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("message",
|
||||
"Webhook 地址未配置或非法(需以 http(s) 开头),请先保存设置"));
|
||||
}
|
||||
return sender.sendForResult(url, buildTestPayload(Instant.now()))
|
||||
.doOnNext(result -> {
|
||||
if (result.success()) {
|
||||
log.info("Test alert sent to {}: {}", url, result.message());
|
||||
} else {
|
||||
log.warn("Failed to send test alert to {}: {}", url,
|
||||
result.message());
|
||||
}
|
||||
})
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
|
||||
"success", result.success(),
|
||||
"message", result.message())));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装测试告警负载:与真实告警同结构(type/title/content/timestamp/data),
|
||||
* {@code type} 为独立的 {@value #TEST_TYPE},接收方可识别为测试消息。
|
||||
*/
|
||||
static Map<String, Object> buildTestPayload(Instant timestamp) {
|
||||
var payload = new LinkedHashMap<String, Object>();
|
||||
payload.put("type", TEST_TYPE);
|
||||
payload.put("title", "操作审计告警:测试消息");
|
||||
payload.put("content", "这是一条测试告警:收到即表示 Webhook 配置可用,"
|
||||
+ "真实告警(登录失败达到阈值)将以相同结构推送。");
|
||||
payload.put("timestamp", timestamp.toString());
|
||||
payload.put("data", Map.of("test", true));
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** 测试告警的类型标识(与 login-failure 区分)。 */
|
||||
static final String TEST_TYPE = "test";
|
||||
}
|
||||
+25
-9
@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。
|
||||
@@ -15,6 +16,10 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
*
|
||||
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
|
||||
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
*
|
||||
* <p>功能评审 P0-2:新增 {@link #sendForResult(String, Map)}——返回推送结果
|
||||
* (送达与否 + 原因摘要)供测试告警端点同步反馈到设置页;登录失败告警路径
|
||||
* 仍走 {@link #send(String, Map)}(fire-and-forget 语义不变)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -31,18 +36,29 @@ public class AlertWebhookSender {
|
||||
|
||||
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */
|
||||
public void send(String url, Map<String, Object> payload) {
|
||||
try {
|
||||
webClient.post()
|
||||
sendForResult(url, payload).subscribe(result -> {
|
||||
if (!result.success()) {
|
||||
log.warn("Failed to send alert webhook to {}: {}", url, result.message());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送 JSON 负载并返回结果(功能评审 P0-2):成功为接收方 2xx;超时、网络错误、
|
||||
* 非 2xx、URL 非法等任何失败均归一为失败结果,绝不抛出、绝不重试。
|
||||
*
|
||||
* <p>返回的 Mono 永不为空、永不报错,超时上限与 fire-and-forget 路径一致
|
||||
* (10 秒)——测试告警端点同步等待该结果反馈到设置页。
|
||||
*/
|
||||
public Mono<AlertSendResult> sendForResult(String url, Map<String, Object> payload) {
|
||||
return Mono.defer(() -> webClient.post()
|
||||
.uri(url)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.bodyValue(payload)
|
||||
.retrieve()
|
||||
.toBodilessEntity()
|
||||
.timeout(TIMEOUT)
|
||||
.subscribe(null, e -> log.warn("Failed to send alert webhook to {}", url, e));
|
||||
} catch (Exception e) {
|
||||
// URL 非法等同步异常同样静默降级,绝不影响调用方
|
||||
log.warn("Failed to initiate alert webhook to {}", url, e);
|
||||
}
|
||||
.toBodilessEntity())
|
||||
.timeout(TIMEOUT)
|
||||
.map(response -> AlertSendResult.ok(response.getStatusCode().value()))
|
||||
.onErrorResume(e -> Mono.just(AlertSendResult.failure(e)));
|
||||
}
|
||||
}
|
||||
|
||||
+15
-7
@@ -17,8 +17,8 @@ import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
|
||||
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
|
||||
*
|
||||
* <p>登录失败暂无法得知尝试的用户名(产品设计已知局限,与登录记录一致),告警负载
|
||||
* 仅含失败次数、窗口、最近一次来源 IP 与 User-Agent。
|
||||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||||
*
|
||||
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
|
||||
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
|
||||
@@ -40,11 +40,15 @@ public class LoginFailureAlertService {
|
||||
/**
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
|
||||
* 任何失败静默降级,不影响调用方。
|
||||
*
|
||||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||||
* 提取失败为 null)
|
||||
*/
|
||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode) {
|
||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
|
||||
String attemptedUsername) {
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
|
||||
settingProvider.get().subscribe(
|
||||
settings -> handle(settings, snapshot, success, Instant.now()),
|
||||
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
|
||||
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
||||
snapshot.getFullPath(), e));
|
||||
}
|
||||
@@ -53,7 +57,8 @@ public class LoginFailureAlertService {
|
||||
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。
|
||||
* handle 包内可见以便测试直接驱动窗口推进。
|
||||
*/
|
||||
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success, Instant now) {
|
||||
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
|
||||
String attemptedUsername, Instant now) {
|
||||
try {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
return;
|
||||
@@ -85,7 +90,7 @@ public class LoginFailureAlertService {
|
||||
failureCount = 0;
|
||||
}
|
||||
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
|
||||
snapshot.getRemoteIp(), snapshot.getUserAgent(), now));
|
||||
snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
|
||||
} catch (Exception e) {
|
||||
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
|
||||
log.warn("Failed to handle login failure alert for {}",
|
||||
@@ -98,16 +103,19 @@ public class LoginFailureAlertService {
|
||||
* data 供程序化消费方取结构化字段。
|
||||
*/
|
||||
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp,
|
||||
String userAgent, Instant timestamp) {
|
||||
String userAgent, String attemptedUsername, Instant timestamp) {
|
||||
var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
|
||||
+ remoteIp + (userAgent != null && !userAgent.isBlank()
|
||||
? "(" + userAgent + ")" : "")
|
||||
+ (attemptedUsername != null && !attemptedUsername.isBlank()
|
||||
? ",尝试的账号:" + attemptedUsername : "")
|
||||
+ "。可在 Console「操作审计」查看详情。";
|
||||
var data = new LinkedHashMap<String, Object>();
|
||||
data.put("failures", failures);
|
||||
data.put("windowMinutes", windowMinutes);
|
||||
data.put("remoteIp", remoteIp);
|
||||
data.put("userAgent", userAgent);
|
||||
data.put("attemptedUsername", attemptedUsername);
|
||||
var payload = new LinkedHashMap<String, Object>();
|
||||
payload.put("type", "login-failure");
|
||||
payload.put("title", "操作审计告警:登录失败");
|
||||
|
||||
+6
-2
@@ -38,9 +38,12 @@ public class AuditLogCsvExporter {
|
||||
/** 每批查询条数。 */
|
||||
static final int EXPORT_BATCH_SIZE = 200;
|
||||
|
||||
/** CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要)。 */
|
||||
/**
|
||||
* CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要,
|
||||
* "尝试用户"列为登录尝试的用户名,功能评审 P0-1)。
|
||||
*/
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private static final DataBufferFactory BUFFER_FACTORY =
|
||||
DefaultDataBufferFactory.sharedInstance;
|
||||
@@ -105,6 +108,7 @@ public class AuditLogCsvExporter {
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
escape(spec.getAttemptedUsername()),
|
||||
escape(spec.getMethod()),
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
|
||||
@@ -14,6 +14,14 @@ public class AuditLogSpec {
|
||||
/** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 登录尝试的用户名(功能评审 P0-1):仅 POST {@code /login} 请求从表单/JSON 请求体
|
||||
* 白名单提取落库(密码等其余字段绝不提取);登录失败时操作者为
|
||||
* {@link #UNKNOWN_USERNAME},本字段用于区分定向撞库与无差别扫描。
|
||||
* 提取失败或非登录请求为 null;不建索引(无需按其筛选)。
|
||||
*/
|
||||
private String attemptedUsername;
|
||||
|
||||
/** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */
|
||||
private String method;
|
||||
|
||||
|
||||
+11
-6
@@ -35,9 +35,12 @@ public class AuditRecorder {
|
||||
*
|
||||
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
|
||||
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
|
||||
*
|
||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
String username, String attemptedUsername) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
@@ -45,19 +48,19 @@ public class AuditRecorder {
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, capture, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, capture, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
String username, String attemptedUsername) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username);
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
@@ -144,11 +147,13 @@ public class AuditRecorder {
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
String username, String attemptedUsername) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
|
||||
// 登录尝试用户名(功能评审 P0-1):仅登录请求由捕获器提取,其余请求为 null
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
|
||||
|
||||
+5
-2
@@ -366,8 +366,11 @@ final class ChangeDiffEngine {
|
||||
out.add(entry);
|
||||
}
|
||||
|
||||
/** 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。 */
|
||||
private static boolean isSensitiveField(String field) {
|
||||
/**
|
||||
* 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。
|
||||
* 包内可见:登录尝试用户名提取({@link LoginAttemptCapture})兜底复用同一规则。
|
||||
*/
|
||||
static boolean isSensitiveField(String field) {
|
||||
for (var segment : field.split("\\.")) {
|
||||
if (SENSITIVE_FIELD.matcher(segment).find()) {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 登录尝试上下文(功能评审 P0-1):请求期由 {@link LoginAttemptCapture} 一次性提取
|
||||
* 尝试的用户名,响应完成后由捕获过滤器消费(落库 {@code spec.attemptedUsername} 与
|
||||
* 告警负载)。非登录请求或提取失败时保持 null。
|
||||
*/
|
||||
public class LoginAttempt {
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private volatile String attemptedUsername;
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
||||
* 登录端点非注册模型,与 {@link ChangeCaptureManager} 的 JSON 缓存逻辑分开,
|
||||
* 为登录端点单独补一条请求体读取:缓存请求体(下游可重复读)并提取尝试的用户名。
|
||||
*
|
||||
* <p>提取规则(安全边界):
|
||||
* <ul>
|
||||
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
||||
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
||||
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
||||
* <li>请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存,
|
||||
* 与字段级变更捕获同款边界(分块传输/超限一律不读,仅不提取用户名)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
|
||||
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
|
||||
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
|
||||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class LoginAttemptCapture {
|
||||
|
||||
/** 登录请求体缓存上限(字节):登录表单极小,上限远小于字段级变更捕获。 */
|
||||
static final int MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
|
||||
static final Set<String> USERNAME_FIELDS = Set.of("username");
|
||||
|
||||
private static final String USERNAME_FIELD = "username";
|
||||
|
||||
/**
|
||||
* 为登录请求缓存请求体并提取尝试的用户名。返回(可能包装了缓存请求体的)交换对象
|
||||
* 供后续链路继续处理;返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange。
|
||||
*/
|
||||
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, LoginAttempt attempt) {
|
||||
var contentType = exchange.getRequest().getHeaders().getContentType();
|
||||
if (!supported(contentType)) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
var contentLength = exchange.getRequest().getHeaders().getContentLength();
|
||||
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
||||
// 分块传输(无 Content-Length)或超限:不读请求体,避免中断流式请求
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return DataBufferUtils.join(exchange.getRequest().getBody(), MAX_BODY_BYTES)
|
||||
.map(joined -> {
|
||||
var bytes = new byte[joined.readableByteCount()];
|
||||
joined.read(bytes);
|
||||
DataBufferUtils.release(joined);
|
||||
attempt.setAttemptedUsername(extract(bytes, contentType));
|
||||
return decorate(exchange, bytes);
|
||||
})
|
||||
.defaultIfEmpty(exchange)
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to capture login attempt body for username extraction", e);
|
||||
return Mono.just(exchange);
|
||||
});
|
||||
}
|
||||
|
||||
/** 支持提取的请求体形态:表单或 JSON(登录端点仅接受这两种)。 */
|
||||
static boolean supported(MediaType contentType) {
|
||||
if (contentType == null) {
|
||||
return false;
|
||||
}
|
||||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
|| ChangeCaptureManager.isJson(contentType);
|
||||
}
|
||||
|
||||
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
|
||||
private static String extract(byte[] bytes, MediaType contentType) {
|
||||
try {
|
||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
|
||||
return usernameOfForm(new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
|
||||
} catch (Exception e) {
|
||||
// 解析异常静默:不提取,不影响登录主流程
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
|
||||
*/
|
||||
static String usernameOfForm(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String found = null;
|
||||
for (var pair : body.split("&")) {
|
||||
var idx = pair.indexOf('=');
|
||||
var name = safeDecode(idx < 0 ? pair : pair.substring(0, idx));
|
||||
if (!USERNAME_FIELDS.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
var value = safeDecode(idx < 0 ? "" : pair.substring(idx + 1));
|
||||
found = maskIfSensitive(name, value);
|
||||
}
|
||||
return StringUtils.hasText(found) ? found : null;
|
||||
} catch (Exception e) {
|
||||
// 表单解析异常静默:不提取,不影响登录主流程
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
||||
static String usernameOfJson(JsonNode root) {
|
||||
if (root == null || !root.isObject()) {
|
||||
return null;
|
||||
}
|
||||
var value = root.path(USERNAME_FIELD);
|
||||
if (!value.isValueNode()) {
|
||||
return null;
|
||||
}
|
||||
var text = value.asText();
|
||||
return StringUtils.hasText(text) ? maskIfSensitive(USERNAME_FIELD, text) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 兜底脱敏:白名单保证仅提取 username,若未来白名单调整后字段名命中现有敏感字段
|
||||
* 规则({@link ChangeDiffEngine}),提取值一律以 {@value ChangeDiffEngine#REDACTED_VALUE}
|
||||
* 代替,密码/密钥绝不落库。
|
||||
*/
|
||||
static String maskIfSensitive(String fieldName, String value) {
|
||||
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
|
||||
}
|
||||
|
||||
/** URL 编码解码失败(如裸 %)回退原值,尽力提取、绝不抛出。 */
|
||||
private static String safeDecode(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游登录处理可正常读取。 */
|
||||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||
@Override
|
||||
public Flux<DataBuffer> getBody() {
|
||||
return Flux.defer(
|
||||
() -> Mono.just(exchange.getResponse().bufferFactory().wrap(body)));
|
||||
}
|
||||
};
|
||||
return exchange.mutate().request(decorated).build();
|
||||
}
|
||||
}
|
||||
+16
-4
@@ -35,7 +35,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
|
||||
* Webhook;与审计开关相互独立。
|
||||
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
|
||||
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
|
||||
* {@code spec.attemptedUsername} 并进入告警负载。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -47,6 +49,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
private final LoginAttemptCapture loginAttemptCapture;
|
||||
private final LoginFailureAlertService loginFailureAlertService;
|
||||
|
||||
@Override
|
||||
@@ -67,7 +70,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var capture = new ChangeCapture();
|
||||
return captureManager.prepare(exchange, snapshot, capture)
|
||||
var loginAttempt = new LoginAttempt();
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 其余请求原样透传
|
||||
var bodyPrepared = CaptureRule.isLoginAttempt(path, method)
|
||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||
: Mono.just(exchange);
|
||||
return bodyPrepared
|
||||
.flatMap(prepared -> captureManager.prepare(prepared, snapshot, capture))
|
||||
.flatMap(prepared -> chain.filter(prepared))
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> {
|
||||
@@ -75,12 +85,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 2xx 清零计数、其余累计,独立于下方审计记录决策
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange));
|
||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
|
||||
loginAttempt.getAttemptedUsername());
|
||||
}
|
||||
operatorOf(ctx, path).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, capture, statusOf(exchange), username);
|
||||
recorder.record(snapshot, capture, statusOf(exchange), username,
|
||||
loginAttempt.getAttemptedUsername());
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||
|
||||
@@ -42,6 +42,11 @@ spec:
|
||||
name: webhookUrl
|
||||
value: ""
|
||||
help: 接收告警的 http(s) 地址,告警以 JSON POST 异步推送(失败不重试,仅记日志)
|
||||
- $formkit: operationAuditTestAlert
|
||||
name: testAlert
|
||||
label: 测试告警
|
||||
ignore: true
|
||||
help: 向已保存的 Webhook 地址推送一条测试消息并直接反馈发送结果,用于验证配置是否可用(不保存任何配置值)
|
||||
- $formkit: number
|
||||
label: 触发阈值(次)
|
||||
name: thresholdCount
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 告警测试端点测试(功能评审 P0-2):Webhook 未配置/非法返回 400、推送结果同步返回
|
||||
* (200 + success/message)、测试负载结构(type=test 与 login-failure 区分)。
|
||||
*/
|
||||
class AlertTestEndpointTest {
|
||||
|
||||
private static final String TEST_URI = "/apis/" + "audit.guichumo.com" + "/v1alpha1/alerts/-/test";
|
||||
|
||||
private AlertSettingProvider settingProvider;
|
||||
private AlertWebhookSender sender;
|
||||
private WebTestClient webClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settingProvider = mock(AlertSettingProvider.class);
|
||||
sender = mock(AlertWebhookSender.class);
|
||||
var endpoint = new AlertTestEndpoint(settingProvider, sender);
|
||||
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
|
||||
org.springframework.web.reactive.function.server.RequestPredicates.path(
|
||||
"/apis/audit.guichumo.com/v1alpha1"),
|
||||
endpoint.endpoint());
|
||||
webClient = WebTestClient.bindToRouterFunction(mounted).build();
|
||||
}
|
||||
|
||||
private static AlertSettings settings(String webhookUrl) {
|
||||
return new AlertSettings(true, webhookUrl, 5, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectWhenWebhookUrlMissing() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings(" ")));
|
||||
|
||||
webClient.post().uri(TEST_URI)
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest()
|
||||
.expectBody()
|
||||
.jsonPath("$.message").isEqualTo(
|
||||
"Webhook 地址未配置或非法(需以 http(s) 开头),请先保存设置");
|
||||
|
||||
verify(sender, org.mockito.Mockito.never()).sendForResult(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnSuccessResult() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
|
||||
.thenReturn(Mono.just(AlertSendResult.ok(200)));
|
||||
|
||||
webClient.post().uri(TEST_URI)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody()
|
||||
.jsonPath("$.success").isEqualTo(true)
|
||||
.jsonPath("$.message").isEqualTo("HTTP 200");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void shouldReturnFailureResultWithoutError() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
|
||||
.thenReturn(Mono.just(new AlertSendResult(false, "connect timed out")));
|
||||
|
||||
webClient.post().uri(TEST_URI)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody()
|
||||
.jsonPath("$.success").isEqualTo(false)
|
||||
.jsonPath("$.message").isEqualTo("connect timed out");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void shouldPostTestTypePayload() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(sender.sendForResult(any(), any()))
|
||||
.thenReturn(Mono.just(AlertSendResult.ok(204)));
|
||||
|
||||
webClient.post().uri(TEST_URI).exchange().expectStatus().isOk();
|
||||
|
||||
// 推送的是独立 type=test 的测试消息(与 login-failure 区分),接收方可识别
|
||||
var urlCaptor = ArgumentCaptor.forClass(String.class);
|
||||
var payloadCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(sender).sendForResult(urlCaptor.capture(), payloadCaptor.capture());
|
||||
assertThat(urlCaptor.getValue()).isEqualTo("https://hooks.example.com/x");
|
||||
var payload = payloadCaptor.getValue();
|
||||
assertThat(payload.get("type")).isEqualTo(AlertTestEndpoint.TEST_TYPE);
|
||||
assertThat((String) payload.get("title")).contains("测试消息");
|
||||
assertThat((String) payload.get("timestamp")).isNotBlank();
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("test", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldBuildTestPayloadStructure() {
|
||||
var payload = AlertTestEndpoint.buildTestPayload(Instant.parse("2026-11-21T12:34:56Z"));
|
||||
|
||||
assertThat(payload.get("type")).isEqualTo("test");
|
||||
assertThat(payload.get("title")).isEqualTo("操作审计告警:测试消息");
|
||||
assertThat((String) payload.get("content")).contains("测试告警");
|
||||
assertThat(payload.get("timestamp")).isEqualTo("2026-11-21T12:34:56Z");
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("test", true);
|
||||
}
|
||||
}
|
||||
+68
-1
@@ -16,7 +16,8 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Webhook 推送集成测试(JDK 内置 HttpServer 走真实 HTTP):
|
||||
* JSON POST 负载可达、非 2xx / 连接失败 / URL 非法均静默降级不抛出。
|
||||
* JSON POST 负载可达、非 2xx / 连接失败 / URL 非法均静默降级不抛出;
|
||||
* 结果化推送(功能评审 P0-2)返回送达与否 + 原因摘要,同样永不抛出。
|
||||
*/
|
||||
class AlertWebhookSenderTest {
|
||||
|
||||
@@ -91,4 +92,70 @@ class AlertWebhookSenderTest {
|
||||
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
|
||||
assertThatCode(() -> sender.send(null, Map.of())).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
// ===== 结果化推送(功能评审 P0-2:测试告警端点同步反馈到设置页) =====
|
||||
|
||||
@Test
|
||||
void shouldReturnSuccessResultOn2xx() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
server = startServer(200, body, contentType, received);
|
||||
|
||||
var result = sender.sendForResult(
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of("k", "v"))
|
||||
.block(java.time.Duration.ofSeconds(10));
|
||||
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.success()).isTrue();
|
||||
assertThat(result.message()).contains("HTTP 200");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultOnNon2xx() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
server = startServer(503, body, contentType, received);
|
||||
|
||||
var result = sender.sendForResult(
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of())
|
||||
.block(java.time.Duration.ofSeconds(10));
|
||||
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.success()).isFalse();
|
||||
assertThat(result.message()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultWhenTargetUnreachable() {
|
||||
// 端口 1 保留端口,连接立即被拒:归一为失败结果而非错误信号
|
||||
var result = sender.sendForResult("http://127.0.0.1:1/hook", Map.of())
|
||||
.block(java.time.Duration.ofSeconds(10));
|
||||
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.success()).isFalse();
|
||||
assertThat(result.message()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultWhenUrlMalformed() {
|
||||
// URL 非法(含 null):装配期异常归一为失败结果,Mono 永不报错
|
||||
assertThat(sender.sendForResult("not-a-url", Map.of())
|
||||
.map(AlertSendResult::success).defaultIfEmpty(false).block(
|
||||
java.time.Duration.ofSeconds(10))).isFalse();
|
||||
assertThat(sender.sendForResult(null, Map.of())
|
||||
.map(AlertSendResult::success).defaultIfEmpty(false).block(
|
||||
java.time.Duration.ofSeconds(10))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSendFireAndForgetWithoutThrowingForResultFailure() {
|
||||
// send(fire-and-forget)复用结果化推送:失败仅记日志,调用方无感知
|
||||
assertThatCode(() -> sender.send("http://127.0.0.1:1/hook", Map.of()))
|
||||
.doesNotThrowAnyException();
|
||||
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
|
||||
+62
-33
@@ -67,12 +67,12 @@ class LoginFailureAlertServiceTest {
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat(payload.get("type")).isEqualTo("login-failure");
|
||||
@@ -86,7 +86,8 @@ class LoginFailureAlertServiceTest {
|
||||
.containsEntry("failures", 3)
|
||||
.containsEntry("windowMinutes", 5)
|
||||
.containsEntry("remoteIp", "127.0.0.1")
|
||||
.containsEntry("userAgent", "UA-1");
|
||||
.containsEntry("userAgent", "UA-1")
|
||||
.containsEntry("attemptedUsername", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,11 +97,11 @@ class LoginFailureAlertServiceTest {
|
||||
var now = Instant.now();
|
||||
|
||||
// 达到阈值告警一次后窗口重开:后续失败需重新累计,不会连环告警
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, times(1)).send(any(), any());
|
||||
}
|
||||
@@ -111,11 +112,11 @@ class LoginFailureAlertServiceTest {
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings, snapshot, false, now);
|
||||
service.handle(settings, snapshot, false, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
// 告警后窗口重开,再次累计到阈值 → 第二次告警
|
||||
service.handle(settings, snapshot, false, now);
|
||||
service.handle(settings, snapshot, false, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
|
||||
verify(sender, times(2)).send(any(), any());
|
||||
}
|
||||
@@ -127,13 +128,13 @@ class LoginFailureAlertServiceTest {
|
||||
var now = Instant.now();
|
||||
|
||||
// 第一次失败开启窗口,10 分钟后窗口已过期 → 计数从新窗口重新开始
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
|
||||
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("failures", 3);
|
||||
@@ -145,16 +146,16 @@ class LoginFailureAlertServiceTest {
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
// 登录成功立即清零:其后失败需重新累计
|
||||
service.handle(settings(3, 5), snapshot, true, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, true, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
verify(sender, times(1)).send(any(), any());
|
||||
}
|
||||
|
||||
@@ -163,7 +164,7 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 302);
|
||||
service.onLoginResult(snapshot, 302, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
@@ -173,8 +174,8 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 200);
|
||||
service.onLoginResult(snapshot, 204);
|
||||
service.onLoginResult(snapshot, 200, null);
|
||||
service.onLoginResult(snapshot, 204, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
@@ -184,11 +185,38 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldIncludeAttemptedUsernameInPayload() {
|
||||
// 登录尝试用户名(功能评审 P0-1):进入负载 content 与 data,接收方可区分定向撞库
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401, "admin");
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).contains("尝试的账号:admin");
|
||||
assertThat((Map<String, Object>) payload.get("data"))
|
||||
.containsEntry("attemptedUsername", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOmitAttemptedUsernameSegmentWhenAbsent() {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
|
||||
assertThat((Map<String, Object>) payload.get("data"))
|
||||
.containsEntry("attemptedUsername", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipWhenAlertDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(
|
||||
@@ -196,8 +224,8 @@ class LoginFailureAlertServiceTest {
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
|
||||
service.onLoginResult(snapshot, 401);
|
||||
service.onLoginResult(snapshot, 401);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
assertThat(service.failureCount).isZero();
|
||||
@@ -209,7 +237,7 @@ class LoginFailureAlertServiceTest {
|
||||
new AlertSettings(true, " ", 1, 5)));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
@@ -219,7 +247,8 @@ class LoginFailureAlertServiceTest {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(snapshot, 401)).doesNotThrowAnyException();
|
||||
assertThatCode(() -> service.onLoginResult(snapshot, 401, null))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
@@ -230,7 +259,7 @@ class LoginFailureAlertServiceTest {
|
||||
doThrow(new IllegalStateException("webhook broken"))
|
||||
.when(sender).send(any(), any());
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401))
|
||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401, null))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@@ -241,7 +270,7 @@ class LoginFailureAlertServiceTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
service.onLoginResult(snapshot, 401);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).doesNotContain("()");
|
||||
|
||||
+20
-18
@@ -39,7 +39,7 @@ class AuditExportEndpointTest {
|
||||
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
|
||||
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private ReactiveExtensionClient client;
|
||||
private WebTestClient webClient;
|
||||
@@ -57,13 +57,14 @@ class AuditExportEndpointTest {
|
||||
}
|
||||
|
||||
private static AuditLog auditLog(String name, Instant creationTimestamp, String username,
|
||||
String method, String resourceType, String resourceName, String path,
|
||||
Integer statusCode, String remoteIp, String userAgent) {
|
||||
String attemptedUsername, String method, String resourceType, String resourceName,
|
||||
String path, Integer statusCode, String remoteIp, String userAgent) {
|
||||
var metadata = new Metadata();
|
||||
metadata.setName(name);
|
||||
metadata.setCreationTimestamp(creationTimestamp);
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username);
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(method);
|
||||
spec.setResourceType(resourceType);
|
||||
spec.setResourceName(resourceName);
|
||||
@@ -94,11 +95,12 @@ class AuditExportEndpointTest {
|
||||
void shouldExportCsvWithBomHeaderAndRows() {
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
stubSinglePage(List.of(
|
||||
auditLog("auditlog-1", time, "admin", "POST", "users", "zhangsan",
|
||||
auditLog("auditlog-1", time, "admin", null, "POST", "users", "zhangsan",
|
||||
"/apis/api.console.halo.run/v1alpha1/users", 201, "127.0.0.1",
|
||||
"Mozilla/5.0"),
|
||||
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "POST", "auth", null,
|
||||
"/login", 401, "10.0.0.8", "Mozilla/5.0")));
|
||||
// 登录失败记录(功能评审 P0-1):尝试用户列为登录时尝试的用户名
|
||||
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 401, "10.0.0.8", "Mozilla/5.0")));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
@@ -106,16 +108,16 @@ class AuditExportEndpointTest {
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(3); // 表头 + 2 行数据(末尾 \r\n 切出的空串不进 split 前段)
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,POST,users,zhangsan,/apis/api.console.halo.run/v1alpha1/users"
|
||||
+ ",admin,,POST,users,zhangsan,/apis/api.console.halo.run/v1alpha1/users"
|
||||
+ ",新建用户,,成功,201,127.0.0.1,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
var log = auditLog("auditlog-1", time, "admin", "PUT", "posts", "abc",
|
||||
var log = auditLog("auditlog-1", time, "admin", null, "PUT", "posts", "abc",
|
||||
"/apis/content.halo.run/v1alpha1/posts/abc", 200, "127.0.0.1", "UA");
|
||||
log.getSpec().setChanges(List.of(
|
||||
change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"),
|
||||
@@ -126,7 +128,7 @@ class AuditExportEndpointTest {
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
|
||||
+ ",admin,,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
|
||||
+ ",修改文章,修改 spec.title:旧标题 → 新标题;新增 spec.cover:c.png"
|
||||
+ ",成功,200,127.0.0.1,UA");
|
||||
}
|
||||
@@ -152,7 +154,7 @@ class AuditExportEndpointTest {
|
||||
void shouldEscapeSpecialCharactersAndFormulaInjection() {
|
||||
stubSinglePage(List.of(
|
||||
// 逗号与引号需加引号且内部引号翻倍;= 开头需加单引号前缀
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-02T00:00:00Z"), "a\"b", "PUT",
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-02T00:00:00Z"), "a\"b", null, "PUT",
|
||||
"posts", "=sum(A1)", "/apis/content.halo.run/v1alpha1/posts/x,y", 200,
|
||||
"127.0.0.1", "@evil")));
|
||||
|
||||
@@ -160,20 +162,20 @@ class AuditExportEndpointTest {
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(2);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-02T00:00:00Z"))
|
||||
+ ",\"a\"\"b\",PUT,posts,'=sum(A1),\"/apis/content.halo.run/v1alpha1/posts/x,y\""
|
||||
+ ",\"a\"\"b\",,PUT,posts,'=sum(A1),\"/apis/content.halo.run/v1alpha1/posts/x,y\""
|
||||
+ ",修改文章,,成功,200,127.0.0.1,'@evil");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatNullStatusCodeAsFailureAndEmptyFields() {
|
||||
stubSinglePage(List.of(
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", "PATCH",
|
||||
"themes", null, null, null, null, null)));
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", null,
|
||||
"PATCH", "themes", null, null, null, null, null)));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-03T00:00:00Z"))
|
||||
+ ",admin,PATCH,themes,,,修改主题,,失败,,,");
|
||||
+ ",admin,,PATCH,themes,,,修改主题,,失败,,,");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -229,8 +231,8 @@ class AuditExportEndpointTest {
|
||||
var page1 = fullBatch(1);
|
||||
var page2 = fullBatch(2);
|
||||
var page3 = List.of(
|
||||
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", "POST",
|
||||
"users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA"));
|
||||
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", null,
|
||||
"POST", "users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA"));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
|
||||
401, page1)),
|
||||
@@ -266,7 +268,7 @@ class AuditExportEndpointTest {
|
||||
for (int i = 0; i < AuditLogCsvExporter.EXPORT_BATCH_SIZE; i++) {
|
||||
items.add(auditLog("auditlog-" + i,
|
||||
Instant.ofEpochSecond(firstTimestampEpochSecond * 1000 + i),
|
||||
"admin", "POST", "users", "user-" + i, "/apis/v1alpha1/users", 200,
|
||||
"admin", null, "POST", "users", "user-" + i, "/apis/v1alpha1/users", 200,
|
||||
"127.0.0.1", "UA"));
|
||||
}
|
||||
return items;
|
||||
|
||||
+23
-9
@@ -55,7 +55,7 @@ class AuditRecorderTest {
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin");
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -78,7 +78,7 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null);
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -89,11 +89,25 @@ class AuditRecorderTest {
|
||||
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordAttemptedUsernameForLoginAttempt() {
|
||||
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan");
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@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");
|
||||
.build()), new ChangeCapture(), 200, "admin", null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -107,7 +121,7 @@ class AuditRecorderTest {
|
||||
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
|
||||
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
||||
200, "admin");
|
||||
200, "admin", null);
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
@@ -117,7 +131,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")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 200, "admin", null)).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
@@ -129,7 +143,7 @@ class AuditRecorderTest {
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
new ChangeCapture(), 500, "admin")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 500, "admin", null)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,7 +161,7 @@ class AuditRecorderTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 200, "admin");
|
||||
recorder.record(snapshot, capture, 200, "admin", null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -172,7 +186,7 @@ class AuditRecorderTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 403, "admin");
|
||||
recorder.record(snapshot, capture, 403, "admin", null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -183,7 +197,7 @@ class AuditRecorderTest {
|
||||
@Test
|
||||
void shouldNotRecordChangesWhenContextMissing() {
|
||||
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
||||
new ChangeCapture(), 200, "admin");
|
||||
new ChangeCapture(), 200, "admin", null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单体解析(成功/无 username/异常静默)、
|
||||
* JSON 体提取、字段白名单(密码绝不提取)、请求体缓存后下游可重复读、
|
||||
* 分块/超限/不支持形态降级为原 exchange。
|
||||
*/
|
||||
class LoginAttemptCaptureTest {
|
||||
|
||||
private LoginAttemptCapture capture;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
capture = new LoginAttemptCapture();
|
||||
}
|
||||
|
||||
private static MockServerWebExchange formExchange(String body) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body));
|
||||
}
|
||||
|
||||
private static MockServerWebExchange jsonExchange(String body) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body));
|
||||
}
|
||||
|
||||
private LoginAttempt prepare(MockServerWebExchange exchange) {
|
||||
var attempt = new LoginAttempt();
|
||||
StepVerifier.create(capture.prepare(exchange, attempt)).expectNextCount(1)
|
||||
.verifyComplete();
|
||||
return attempt;
|
||||
}
|
||||
|
||||
// ===== 表单体解析 =====
|
||||
|
||||
@Test
|
||||
void shouldExtractUsernameFromFormBody() {
|
||||
var attempt = prepare(formExchange("username=admin&password=secret-pw&remember=true"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDecodeUrlEncodedUsername() {
|
||||
var attempt = prepare(formExchange("username=user%40mail.com&password=x"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("user@mail.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotExtractPasswordOrOtherFields() {
|
||||
// 白名单制:仅 username 字段被提取,password 等任何其余字段绝不落库
|
||||
var attempt = prepare(formExchange("password=secret&email=a@b.c"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenUsernameMissingOrBlank() {
|
||||
assertThat(prepare(formExchange("password=x")).getAttemptedUsername()).isNull();
|
||||
assertThat(prepare(formExchange("username=&password=x")).getAttemptedUsername()).isNull();
|
||||
assertThat(prepare(formExchange("username= ")).getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToRawValueOnMalformedEncoding() {
|
||||
// 裸 % 等非法编码:解码失败回退原值,尽力提取且绝不抛出
|
||||
var attempt = prepare(formExchange("username=bad%zz&password=x"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("bad%zz");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExtractSilentlyFromGarbageBody() {
|
||||
// 解析异常静默:任何畸形输入都不抛出、不提取
|
||||
var attempt = prepare(formExchange("&&&"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
// ===== JSON 体提取 =====
|
||||
|
||||
@Test
|
||||
void shouldExtractUsernameFromJsonBody() {
|
||||
var attempt = prepare(jsonExchange("{\"username\":\"admin\",\"password\":\"secret\"}"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenJsonUsernameMissing() {
|
||||
var attempt = prepare(jsonExchange("{\"name\":\"admin\"}"));
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
// ===== 请求体缓存与下游可重复读 =====
|
||||
|
||||
@Test
|
||||
void shouldKeepBodyReadableDownstream() {
|
||||
var body = "username=admin&password=secret";
|
||||
var exchange = formExchange(body);
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
|
||||
// 装饰后的请求可重复读(每次订阅独立 buffer),登录处理可正常读取表单
|
||||
assertThat(prepared).isNotSameAs(exchange);
|
||||
var first = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
.collectList().block();
|
||||
var second = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
.collectList().block();
|
||||
assertThat(first).containsExactly(body);
|
||||
assertThat(second).containsExactly(body);
|
||||
}
|
||||
|
||||
// ===== 形态与边界降级 =====
|
||||
|
||||
@Test
|
||||
void shouldPassthroughUnsupportedContentType() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.contentLength(2)
|
||||
.body("x=1"));
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughChunkedBodyWithoutContentLength() {
|
||||
var request = MockServerHttpRequest.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
||||
.wrap("username=admin".getBytes(StandardCharsets.UTF_8))));
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
// 分块传输(无 Content-Length):不读请求体,避免中断流式请求
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughOversizedBody() {
|
||||
var oversized = "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES + 1);
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength(oversized.length())
|
||||
.body(oversized));
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughEmptyBody() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
// ===== 兜底脱敏(现有敏感字段规则约束) =====
|
||||
|
||||
@Test
|
||||
void shouldRedactWhitelistedFieldMatchingSensitiveRule() {
|
||||
// 白名单当前仅 username(不命中敏感规则,值原样提取);
|
||||
// 兜底约束:字段名若命中现有敏感字段规则,值一律以 ****** 代替
|
||||
assertThat(LoginAttemptCapture.maskIfSensitive("username", "admin")).isEqualTo("admin");
|
||||
assertThat(LoginAttemptCapture.maskIfSensitive("password", "secret"))
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotTouchResponse() {
|
||||
var exchange = formExchange("username=admin&password=x");
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
capture.prepare(exchange, attempt).block();
|
||||
|
||||
// 提取过程只读请求侧,不写响应(状态码仍为未设置的 null)
|
||||
assertThat(exchange.getResponse().getStatusCode()).isNull();
|
||||
}
|
||||
|
||||
// ===== 提取函数直接断言 =====
|
||||
|
||||
@Test
|
||||
void shouldExtractLastUsernameWhenDuplicated() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm("username=first&username=second"))
|
||||
.isEqualTo("second");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForBlankFormBody() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(null)).isNull();
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(" ")).isNull();
|
||||
}
|
||||
}
|
||||
+39
-13
@@ -3,15 +3,18 @@ package run.halo.operationaudit.audit;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
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;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
@@ -27,6 +30,7 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
||||
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。
|
||||
* 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
@@ -73,8 +77,9 @@ class OperationAuditWebFilterTest {
|
||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||
any(ChangeCapture.class)))
|
||||
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
||||
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
|
||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker,
|
||||
loginFailureAlertService);
|
||||
new LoginAttemptCapture(), loginFailureAlertService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -92,7 +97,7 @@ class OperationAuditWebFilterTest {
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq("admin"));
|
||||
eq("admin"), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -103,7 +108,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,7 +121,25 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME));
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordAndAlertAttemptedUsernameOnLoginAttempt() {
|
||||
// 登录尝试用户名(功能评审 P0-1):表单体中的 username 白名单提取,
|
||||
// 随告警回调与审计记录透传;密码等其余字段绝不提取
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength("username=admin&password=secret".getBytes(StandardCharsets.UTF_8).length)
|
||||
.body("username=admin&password=secret"));
|
||||
|
||||
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("admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -128,7 +151,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -145,7 +168,7 @@ class OperationAuditWebFilterTest {
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,7 +186,8 @@ class OperationAuditWebFilterTest {
|
||||
.verifyComplete();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"));
|
||||
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"),
|
||||
isNull());
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
@@ -195,7 +219,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
||||
eq("admin"));
|
||||
eq("admin"), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -222,7 +246,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
verify(writeMarker).onRequestStart(any());
|
||||
verify(writeMarker).onRequestComplete(any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -247,7 +271,8 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -261,7 +286,8 @@ class OperationAuditWebFilterTest {
|
||||
.verifyComplete();
|
||||
|
||||
// 非常响应(401)同样回调,由告警服务按失败累计
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -278,7 +304,7 @@ class OperationAuditWebFilterTest {
|
||||
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), any());
|
||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -290,6 +316,6 @@ class OperationAuditWebFilterTest {
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), any());
|
||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
+108
@@ -6,6 +6,7 @@
|
||||
"": {
|
||||
"name": "plugin-operation-audit-ui",
|
||||
"dependencies": {
|
||||
"@formkit/vue": "^1.7.2",
|
||||
"@halo-dev/api-client": "2.26.0",
|
||||
"@halo-dev/components": "2.26.0",
|
||||
"@halo-dev/console-shared": "^2.21.0",
|
||||
@@ -535,6 +536,113 @@
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@formkit/core": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/core/-/core-1.7.2.tgz",
|
||||
"integrity": "sha512-XDRVqkDtOziU3z44hdvgWEqGpiv6nTNeCmP8cnESKkr24a4keQuEwmfDVvibYV0ywyTMg6ylp2lyklCYeRHykQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/dev": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/dev/-/dev-1.7.2.tgz",
|
||||
"integrity": "sha512-W38xbbFS4h4LTV22kUC6ZbPHBmlM2lVbAz5PSYU3SPaNc4FeXp4GTe4GzLEmcS82B+5L1zbSOgGB43kWZts7wA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/i18n": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/i18n/-/i18n-1.7.2.tgz",
|
||||
"integrity": "sha512-Zs6f+rtP2j2Nnt1HkNrL85WU6rtS1l1Q0BAQjCMGQPsbrppiL7/TZ5bNIrVm0DTntLgG3firDS7bNWAxPSwerQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/inputs": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/inputs/-/inputs-1.7.2.tgz",
|
||||
"integrity": "sha512-4xs7RJN8EFGctTCNRXBTvor2O8RvuEEK3q2Hl/RMU5lhhn5tmck90fkkeAr9o+rWRoSNiV8XgbLQArQ/B1IYPw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/observer": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/observer/-/observer-1.7.2.tgz",
|
||||
"integrity": "sha512-KUr5mcu2SAeHOOK1FaMyFigtA8hkHLsUkaPFWpTC81j79o1AUjJppmfPaX6PbtlHLeMs2Zq8Qhp6VAhi7D2WJg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/rules": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/rules/-/rules-1.7.2.tgz",
|
||||
"integrity": "sha512-2e5qKlXzmL9LAetncFp7xkHEX/UAJsU3bo1iL3idloH3HALf5fIdg3lgOKwCNDMdLjbfiKJ6lVwFaeFfFpcDKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/themes": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/themes/-/themes-1.7.2.tgz",
|
||||
"integrity": "sha512-AaZHy7l9D44Ya3cQRqZ8RIpaTTsCjTB1gX13NlpqYSs6yG0yBTmJ7L7kW60bOGdhs/vmIwSel578EBwz98nybQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/utils": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/utils/-/utils-1.7.2.tgz",
|
||||
"integrity": "sha512-bBF6alUBOqFfJHjVB95Vck0hp36vlw4QfFJxGfTO6BX68AEaFzzzabtpwfy0DbcHtwHh4Yn7l/rOWGxXEve+QQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@formkit/validation": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/validation/-/validation-1.7.2.tgz",
|
||||
"integrity": "sha512-JJsLP7AI/++VujdwtBeUcPhCqY3FXSKZ7hajT7Ow5Feab7JLqVPjxVMFbXDgEOLjq0ex1NX/I+EQHfm5sqMRsA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/observer": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/vue": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/vue/-/vue-1.7.2.tgz",
|
||||
"integrity": "sha512-jrvXl2ZhS6X5klTbP4N5zc0Dg37AjbAf8SCVoz7mfligVkmwrrF4SN3waMBcH+n9gqT+vrkOYb6bQXdvjUdnCQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/dev": "^1.7.2",
|
||||
"@formkit/i18n": "^1.7.2",
|
||||
"@formkit/inputs": "^1.7.2",
|
||||
"@formkit/observer": "^1.7.2",
|
||||
"@formkit/rules": "^1.7.2",
|
||||
"@formkit/themes": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@halo-dev/api-client": {
|
||||
"version": "2.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@halo-dev/api-client/-/api-client-2.26.0.tgz",
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@formkit/vue": "^1.7.2",
|
||||
"@halo-dev/api-client": "2.26.0",
|
||||
"@halo-dev/components": "2.26.0",
|
||||
"@halo-dev/console-shared": "^2.21.0",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的测试告警链路。
|
||||
// 「发送测试告警」为插件设置「告警通知」区的自定义 FormKit 输入(功能评审 P0-2):
|
||||
// 点击 → POST 测试告警端点(无请求体)→ 同步反馈结果提示(成功/失败两色),
|
||||
// 期间按钮 loading。历史上验证 webhook 配置只能等真实告警触发,本测试锁定
|
||||
// 端点路径与反馈链路形态,防止路径漂移或链路残缺。
|
||||
const sfc = readFileSync(
|
||||
fileURLToPath(new URL('./TestAlertButton.vue', import.meta.url)),
|
||||
'utf-8',
|
||||
)
|
||||
|
||||
describe('TestAlertButton 测试告警', () => {
|
||||
it('声明与后端一致的测试告警端点路径', () => {
|
||||
expect(sfc).toContain(
|
||||
"const TEST_ALERT_ENDPOINT = '/apis/audit.guichumo.com/v1alpha1/alerts/-/test'",
|
||||
)
|
||||
})
|
||||
|
||||
it('点击 POST 测试告警端点,按钮 loading、防重复点击', () => {
|
||||
expect(sfc).toContain("await fetch(TEST_ALERT_ENDPOINT, { method: 'POST' })")
|
||||
expect(sfc).toContain('if (sending.value)')
|
||||
expect(sfc).toMatch(/<VButton :loading="sending"[^>]*@click="sendTestAlert">/)
|
||||
expect(sfc).toContain('发送测试告警')
|
||||
})
|
||||
|
||||
it('推送结果以提示反馈:成功/失败两色,非 2xx 抛出后进失败提示', () => {
|
||||
expect(sfc).toContain('hintType.value = body.success ? \'success\' : \'error\'')
|
||||
expect(sfc).toMatch(/throw new Error\(body\.message \|\| `发送失败(HTTP \$\{response\.status\})`\)/)
|
||||
expect(sfc).toContain("hintType.value = 'error'")
|
||||
expect(sfc).toContain('hint-success')
|
||||
expect(sfc).toContain('hint-error')
|
||||
expect(sfc).toMatch(/v-if="hint"/)
|
||||
// 无论成败都复位按钮 loading
|
||||
expect(sfc).toMatch(/finally\s*\{\s*sending\.value = false\s*\}/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { VButton } from '@halo-dev/components'
|
||||
|
||||
/**
|
||||
* 「发送测试告警」自定义 FormKit 输入(功能评审 P0-2):
|
||||
* 在插件设置「告警通知」区提供手动推送入口——向当前已保存的 Webhook 地址
|
||||
* 推送一条 type=test 测试消息,并同步反馈发送结果(成功/失败 + 原因摘要)。
|
||||
* 不承载任何配置值(settings.yaml 中以 ignore: true 声明,不新增设置项)。
|
||||
*/
|
||||
|
||||
/** 测试告警端点(与后端 AlertTestEndpoint 保持一致)。 */
|
||||
const TEST_ALERT_ENDPOINT = '/apis/audit.guichumo.com/v1alpha1/alerts/-/test'
|
||||
|
||||
const sending = ref(false)
|
||||
const hint = ref('')
|
||||
const hintType = ref<'success' | 'error'>('success')
|
||||
|
||||
async function sendTestAlert() {
|
||||
if (sending.value) {
|
||||
return
|
||||
}
|
||||
sending.value = true
|
||||
hint.value = ''
|
||||
try {
|
||||
const response = await fetch(TEST_ALERT_ENDPOINT, { method: 'POST' })
|
||||
const body = (await response.json()) as { success?: boolean; message?: string }
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || `发送失败(HTTP ${response.status})`)
|
||||
}
|
||||
hintType.value = body.success ? 'success' : 'error'
|
||||
hint.value = body.success ? `发送成功(${body.message})` : `发送失败:${body.message}`
|
||||
} catch (e) {
|
||||
hintType.value = 'error'
|
||||
hint.value = e instanceof Error ? e.message : String(e)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="test-alert">
|
||||
<VButton :loading="sending" size="sm" @click="sendTestAlert">发送测试告警</VButton>
|
||||
<span v-if="hint" class="test-alert-hint" :class="`hint-${hintType}`">{{ hint }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.test-alert {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.test-alert-hint {
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.4;
|
||||
word-break: break-all;
|
||||
}
|
||||
.hint-success {
|
||||
color: #0f766e;
|
||||
}
|
||||
.hint-error {
|
||||
color: #d71d1d;
|
||||
}
|
||||
</style>
|
||||
@@ -2,9 +2,15 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RouteRecordAppend } from '@halo-dev/console-shared'
|
||||
|
||||
// 结构性回归测试:无需真实渲染,将视图组件与图标库打桩,
|
||||
// 仅断言 definePlugin 暴露的路由注册形态。
|
||||
// 仅断言 definePlugin 暴露的路由注册与自定义 FormKit 输入注册形态。
|
||||
vi.mock('@/views/AuditLogList.vue', () => ({ default: { name: 'AuditLogListStub' } }))
|
||||
vi.mock('@/components/TestAlertButton.vue', () => ({
|
||||
default: { name: 'TestAlertButtonStub' },
|
||||
}))
|
||||
vi.mock('@halo-dev/components', () => ({ IconEye: { name: 'IconEyeStub' } }))
|
||||
vi.mock('@formkit/vue', () => ({
|
||||
createInput: (component: unknown) => ({ wrapped: component }),
|
||||
}))
|
||||
|
||||
const { default: plugin } = await import('./index')
|
||||
|
||||
@@ -46,3 +52,17 @@ describe('console 路由注册', () => {
|
||||
expect(menu.icon).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('自定义 FormKit 输入注册(功能评审 P0-2)', () => {
|
||||
const formkit = (plugin as typeof plugin & {
|
||||
formkit?: { inputs: Record<string, unknown> }
|
||||
}).formkit
|
||||
|
||||
it('注册「发送测试告警」输入类型(带插件标识前缀,避免与内置类型冲突)', () => {
|
||||
expect(formkit).toBeDefined()
|
||||
const input = formkit?.inputs.operationAuditTestAlert
|
||||
expect(input).toBeDefined()
|
||||
// createInput 包装后的定义携带被包装组件(打桩后可识别)
|
||||
expect(input).toMatchObject({ wrapped: { name: 'TestAlertButtonStub' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import { createInput } from '@formkit/vue'
|
||||
import { definePlugin } from '@halo-dev/console-shared'
|
||||
import type { PluginModule } from '@halo-dev/console-shared'
|
||||
import { markRaw } from 'vue'
|
||||
import { IconEye } from '@halo-dev/components'
|
||||
import AuditLogList from '@/views/AuditLogList.vue'
|
||||
import TestAlertButton from '@/components/TestAlertButton.vue'
|
||||
|
||||
export default definePlugin({
|
||||
// 自定义 FormKit 输入(功能评审 P0-2):注册「发送测试告警」按钮类型,
|
||||
// 供 settings.yaml 告警通知组引用($formkit: operationAuditTestAlert)。
|
||||
// Halo 2.25+ 支持插件经 formkit.inputs 注册自定义输入(bundler kit 已将
|
||||
// @formkit/vue 外部化为宿主共享模块,运行时由控制台提供)。
|
||||
const formkitInputs = {
|
||||
operationAuditTestAlert: createInput(TestAlertButton),
|
||||
}
|
||||
|
||||
// PluginModule 未声明 formkit 字段(Halo 运行时契约先行于类型定义):
|
||||
// 以变量 + 交叉类型绕过对象字面量的多余属性检查
|
||||
const plugin: PluginModule & { formkit: { inputs: typeof formkitInputs } } = {
|
||||
components: {},
|
||||
formkit: {
|
||||
inputs: formkitInputs,
|
||||
},
|
||||
routes: [
|
||||
{
|
||||
// 追加到控制台 Root 路由(BasicLayout)下,页面才能保留左侧导航,
|
||||
@@ -30,4 +46,6 @@ export default definePlugin({
|
||||
},
|
||||
],
|
||||
extensionPoints: {},
|
||||
})
|
||||
}
|
||||
|
||||
export default definePlugin(plugin)
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
export interface AuditLogSpec {
|
||||
username: string
|
||||
/** 登录尝试的用户名(功能评审 P0-1):仅 POST /login 请求提取落库,其余为 null。 */
|
||||
attemptedUsername?: string | null
|
||||
method: string
|
||||
resourceType: string
|
||||
resourceName?: string | null
|
||||
|
||||
@@ -78,6 +78,11 @@ const rawJson = computed(() =>
|
||||
<dt>操作者</dt>
|
||||
<dd>{{ displayUsername(log.spec.username) }}</dd>
|
||||
</div>
|
||||
<!-- 登录尝试的用户名(功能评审 P0-1):仅登录请求落库,历史记录/其他请求缺失 -->
|
||||
<div v-if="log.spec.attemptedUsername" class="detail-row">
|
||||
<dt>尝试用户</dt>
|
||||
<dd class="break-all">{{ log.spec.attemptedUsername }}</dd>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<dt>描述</dt>
|
||||
<dd>{{ describeOperation(log.spec) }}</dd>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的资源历史快捷链路。
|
||||
// 「查看该资源历史」为列表行内快捷动作(功能评审 P1-1):产品定位第一个典型场景
|
||||
// ("这篇文章谁改过的")——点击预填 resourceType + 资源名关键字(关键字匹配资源
|
||||
// 名称/路径)并刷新列表;不新增后端参数,与现有筛选/导出条件共用同一套状态。
|
||||
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
|
||||
|
||||
describe('AuditLogList 查看该资源历史', () => {
|
||||
it('行内快捷动作:仅在有资源名称的记录上渲染,stop 冒泡避免触发详情抽屉', () => {
|
||||
const rowStart = sfc.indexOf('<VEntity')
|
||||
const rowEnd = sfc.indexOf('</VEntity>', rowStart)
|
||||
const row = sfc.slice(rowStart, rowEnd)
|
||||
expect(row).toContain('v-if="log.spec.resourceName"')
|
||||
expect(row).toContain('@click.stop="viewResourceHistory(log)"')
|
||||
expect(row).toContain('查看该资源的历史操作')
|
||||
})
|
||||
|
||||
it('预填筛选:资源类型 + 资源名关键字,并走统一查询入口刷新列表', () => {
|
||||
const fnStart = sfc.indexOf('function viewResourceHistory(log: AuditLog)')
|
||||
expect(fnStart).toBeGreaterThan(-1)
|
||||
const fn = sfc.slice(fnStart, sfc.indexOf('</script>', fnStart))
|
||||
expect(fn).toContain('filterResourceType.value = log.spec.resourceType')
|
||||
expect(fn).toContain("filterKeyword.value = log.spec.resourceName ?? ''")
|
||||
expect(fn).toContain('applyFilters()')
|
||||
})
|
||||
|
||||
it('不新增后端参数:复用现有 resourceType fieldSelector 与 keyword 模糊匹配', () => {
|
||||
// 与现有筛选/导出条件共用同一套状态——buildQuery 生成相同参数形态
|
||||
expect(sfc).toContain("params.append('fieldSelector', `spec.resourceType=${filterResourceType.value}`)")
|
||||
expect(sfc).toContain("params.set('keyword', filterKeyword.value.trim())")
|
||||
})
|
||||
})
|
||||
@@ -176,6 +176,17 @@ function resetFilter() {
|
||||
filterEndTime.value = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看该资源历史(功能评审 P1-1):行内快捷动作——预填资源类型 + 资源名关键字
|
||||
* (关键字匹配资源名称/路径)并刷新列表,与现有筛选/导出条件共用同一套状态,
|
||||
* 不新增后端参数。仅在有资源名称的记录上提供(集合级/登录操作无可回溯的具体资源)。
|
||||
*/
|
||||
function viewResourceHistory(log: AuditLog) {
|
||||
filterResourceType.value = log.spec.resourceType
|
||||
filterKeyword.value = log.spec.resourceName ?? ''
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
watch([filterUsername, filterResourceType, filterMethod, filterAction, filterResult], () => {
|
||||
page.value = 1
|
||||
fetchLogs()
|
||||
@@ -348,6 +359,14 @@ onMounted(fetchLogs)
|
||||
{{ log.spec.resourceType }}
|
||||
<template v-if="log.spec.resourceName">/ {{ log.spec.resourceName }}</template>
|
||||
</span>
|
||||
<!-- 行内快捷动作(功能评审 P1-1):查看该资源的历史操作;
|
||||
stop 冒泡避免触发行点击的详情抽屉 -->
|
||||
<a
|
||||
v-if="log.spec.resourceName"
|
||||
class="resource-history-link"
|
||||
title="查看该资源的历史操作"
|
||||
@click.stop="viewResourceHistory(log)"
|
||||
>历史</a>
|
||||
</template>
|
||||
<template #description>
|
||||
<span class="row-sub">{{ log.spec.path }}</span>
|
||||
@@ -506,6 +525,16 @@ onMounted(fetchLogs)
|
||||
.resource-text {
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
/* 行内快捷动作:查看该资源历史(P1-1),主题绿小链接 */
|
||||
.resource-history-link {
|
||||
margin-left: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--audit-green);
|
||||
cursor: pointer;
|
||||
}
|
||||
.resource-history-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.method-badge {
|
||||
display: inline-block;
|
||||
padding: 0.1rem 0.4rem;
|
||||
|
||||
Reference in New Issue
Block a user